http://stackoverflow.com/comment/84165014
has text: @ThomasKühn let's say then that x and y are 6-element arrays. I'll edit the question.
score: 0
comment on: http://stackoverflow.com/q/48583961
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84185264
comment on: http://stackoverflow.com/q/48593999
has text: The data is pretty big, but here is an example df = pd.DataFrame([{'City Name': 'Dallas'} ,{'City Name': 'New York (NY)'} ,{'City Name': 'West Orange 07052'} ,{'City Name': 'Orlando (Florda)'} ,{'City Name': 'Camdem (NJ)'} ,{'City Name': 'Boston'} ,{'City Name': 'Harrison07029'}]) And I want to just get the city names
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/48635649
tagged with: python
tagged with: amazon-web-services
has title: Python - How to solve OS Error: [Errno 2] No such file or directory?
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48635836
has comment: http://stackoverflow.com/comment/84268200
type: Question
tagged with: amazon-s3
has body: I'm running this command: AWS_PROFILE=sandbox aws s3 cp local_path bucket --recursive and this works just fine. I want to run a python script. This is my code: cmd = ['AWS_PROFILE=sandbox', 'aws', 's3', 'cp', local_path, bucket, '--recursive'] subprocess.Popen(cmd).communicate() and it doesn't work. Error traceback: File "bin/run_report.py", line 128, in main subprocess.Popen(cmd).communicate() File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 390, in __init__ errread, errwrite) File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1025, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I don't understand what I'm doing wrong. I have triple checked the path to local and to bucket, as mentioned, it works from the shell (I don't want to run shell=True)
has answer: http://stackoverflow.com/a/48635836
score: 1
has comment: http://stackoverflow.com/comment/84268068
has comment: http://stackoverflow.com/comment/84327264
tagged with: command-line-interface
tagged with: subprocess
type: AnsweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48633288
has body: a=np.zeros((3,3,3)) b=np.arange(3) c=np.arange(9).reshape(3,3) I wanna put the elements of the array b or c along the diagonal (or above/below the diagonal) of the 3d matrix (tensor) a with respect to a specific axis. I tired numpy.diagflat, but it only works for 2d matrix. For instance, how to make the following matrix? array([[[ 0., 0., 0.], [ 0., 1., 0.], [ 0., 0., 2.]], [[ 0., 0., 0.], [ 0., 1., 0.], [ 0., 0., 2.]], [[ 0., 0., 0.], [ 0., 1., 0.], [ 0., 0., 2.]]])
downvote count: 0
has answer: http://stackoverflow.com/a/48633379
tagged with: matrix
has title: How to assign elements into the diagonal of a 3d matrix efficiently?
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/7685128
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: diagonal
tagged with: python
has answer: http://stackoverflow.com/a/48633376
answer count: 2

http://stackoverflow.com/a/48550599
answers question: http://stackoverflow.com/q/48550159
has body: Best practice is to avoid hard coding the batch size in the graph. As discussed here (see "How do I build a graph that works with variable batch sizes?") you should specify shapes as [None, nx, ny, nz], and retrieve batch sizes using tf.shape(input)[0]. Also, for reshaping you can use a form like this: tf.reshape(input, [-1, nx, ny, nz]) where the -1 specifies that the batch dimension should be set to the appropriate size during runtime.
type: Answer
score: 0

http://stackoverflow.com/q/48612105
has comment: http://stackoverflow.com/comment/84224404
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84221050
tagged with: plotly-dash
has comment: http://stackoverflow.com/comment/84459246
has title: How to render a plot.ly Jupyter Notebook file into Dash python Dashboard
upvote count: 2
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48779917
tagged with: python
has answer: http://stackoverflow.com/a/48779917
score: 2
type: AnsweredQuestion
has body: I would like to have you sharing the template in Dash python where it generate a scatter charter with the help of plot.ly stunning graphics. I am unable to make my Dash framework running but I do the same flawlessly in Jupyter Notebook. Just was wondering if I could run it on Dash. Your help is much appreciated. Regards.
has comment: http://stackoverflow.com/comment/84546793

http://stackoverflow.com/comment/84163417
has text: Indeed much more elegant! Thanks for the quick answer.
type: Comment
comment on: http://stackoverflow.com/a/48583434
score: 0
type: AnswerComment

http://stackoverflow.com/q/48625812
type: Question
has answer: http://stackoverflow.com/a/48626600
has body: Before anything: I did read Wrapping around a python list as a slice operation and wrapping around slices in Python / numpy This question is not a duplicate of any of those two questions simply because this question is a totally different question. So stop downvoting it and do not mark it as a duplicate. In the first mentioned thread, the "wrap" there means something different. For the second mentioned thread, they dealt with ndarray and can only work for integers only. Real question: How to slice a string or an array from a point to another point with an end between them? Essentially, we want to do something like this, n = whatever we want print(string[n-5:n+6]) The above code may look normal. But it doesn't work near the edges (near the beginning of the string/array or the end of the string/array). Because Python's slicing doesn't allow slicing through the end of the array and continuing from the beginning. What if n is smaller than 5 or length of string longer than n+6? Here's a better example, consider that we have array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] We want to print an element with its nearest two neighbors in string for all elements in an array print("Two neighbors:") for i, x in enumerate(array): print(array[i-1] + array[i] + array[(i+1)%len(array)]) Output: Two neighbors: kab abc bcd cde def efg fgh ghi hij ijk jka So far so good, let's do it with four neighbors. print("Four neighbors:") for i, x in enumerate(array): print(array[i-2] + array[i-1] + array[i] + array[(i+1)%len(array)] + array[(i+2)%len(array)]) Output: Four neighbors: jkabc kabcd abcde bcdef cdefg defgh efghi fghij ghijk hijka ijkab You can see where this is going, as the desired number of neighbors grow, the number of times we must type them out one by one increases. Is there a way instead of s[n-3]+s[n-2]+s[n-1]+s[n]+s[n+1]+s[n+2]+s[n+3], we can do something like s[n-3:n+4]? Note that s[n-3:n]+s[n:(n+4)%len(s)] doesn't work at the edges. NOTE: For the particular e…
downvote count: 0
has title: How to wrap a string or an array around and slice the wrapped string or array in Python?
possible better answer: http://stackoverflow.com/a/48626155
linked to: http://stackoverflow.com/q/17739543
tagged with: arrays
has comment: http://stackoverflow.com/comment/84249001
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48626155
has answer: http://stackoverflow.com/a/48626158
linked to: http://stackoverflow.com/q/4528740
has comment: http://stackoverflow.com/comment/84248880
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48626227
score: 1
answer count: 4
accepted answer: http://stackoverflow.com/a/48626600
favorite count: 0

pandas
tags question: http://stackoverflow.com/q/48629253
tags question: http://stackoverflow.com/q/48593835
tags question: http://stackoverflow.com/q/48505818
tags question: http://stackoverflow.com/q/48526062
tags question: http://stackoverflow.com/q/48607132
tags question: http://stackoverflow.com/q/48623332
tags question: http://stackoverflow.com/q/48595445
tags question: http://stackoverflow.com/q/48619840
tags question: http://stackoverflow.com/q/48603156
tags question: http://stackoverflow.com/q/48566268
tags question: http://stackoverflow.com/q/48615563
tags question: http://stackoverflow.com/q/48559991
tags question: http://stackoverflow.com/q/48491925
tags question: http://stackoverflow.com/q/48645409
tags question: http://stackoverflow.com/q/48518338
tags question: http://stackoverflow.com/q/48580235
tags question: http://stackoverflow.com/q/48580413
tags question: http://stackoverflow.com/q/48645354
tags question: http://stackoverflow.com/q/48614158
tags question: http://stackoverflow.com/q/48630060
tags question: http://stackoverflow.com/q/48553446
tags question: http://stackoverflow.com/q/48488821
tags question: http://stackoverflow.com/q/48616470
tags question: http://stackoverflow.com/q/48607163
tags question: http://stackoverflow.com/q/48573148
tags question: http://stackoverflow.com/q/48527637
tags question: http://stackoverflow.com/q/48636751
tags question: http://stackoverflow.com/q/48576044
tags question: http://stackoverflow.com/q/48591021
tags question: http://stackoverflow.com/q/48617147
tags question: http://stackoverflow.com/q/48613671
tags question: http://stackoverflow.com/q/48641924
tags question: http://stackoverflow.com/q/48527091
tags question: http://stackoverflow.com/q/48580365
tags question: http://stackoverflow.com/q/48572970
tags question: http://stackoverflow.com/q/48488519
tags question: http://stackoverflow.com/q/48502095
tags question: http://stackoverflow.com/q/48635810
tags question: http://stackoverflow.com/q/48535239
tags question: http://stackoverflow.com/q/48524362
tags question: http://stackoverflow.com/q/48636680
tags question: http://stackoverflow.com/q/48509590
tags question: http://stackoverflow.com/q/48570585
tags question: http://stackoverflow.com/q/48637888
tags question: http://stackoverflow.com/q/48573771
tags question: http://stackoverflow.com/q/48512449
tags question: http://stackoverflow.com/q/48512352
tags question: http://stackoverflow.com/q/48515037
tags question: http://stackoverflow.com/q/48554855
tags question: http://stackoverflow.com/q/48553978
tags question: http://stackoverflow.com/q/48573622
tags question: http://stackoverflow.com/q/48574444
tags question: http://stackoverflow.com/q/48585073
tags question: http://stackoverflow.com/q/48530658
tags question: http://stackoverflow.com/q/48497795
tags question: http://stackoverflow.com/q/48497449
tags question: http://stackoverflow.com/q/48570481
tags question: http://stackoverflow.com/q/48591723
tags question: http://stackoverflow.com/q/48522206
tags question: http://stackoverflow.com/q/48605016
tags question: http://stackoverflow.com/q/48638220
tags question: http://stackoverflow.com/q/48603283
tags question: http://stackoverflow.com/q/48598394
tags question: http://stackoverflow.com/q/48567360
tags question: http://stackoverflow.com/q/48501822
tags question: http://stackoverflow.com/q/48559995
tags question: http://stackoverflow.com/q/48521360
tags question: http://stackoverflow.com/q/48503953
tags question: http://stackoverflow.com/q/48500534
tags question: http://stackoverflow.com/q/48591768
tags question: http://stackoverflow.com/q/48512562
tags question: http://stackoverflow.com/q/48556239
tags question: http://stackoverflow.com/q/48630089
tags question: http://stackoverflow.com/q/48569684
tags question: http://stackoverflow.com/q/48505874
tags question: http://stackoverflow.com/q/48553276
tags question: http://stackoverflow.com/q/48593118
tags question: http://stackoverflow.com/q/48511319
tags question: http://stackoverflow.com/q/48522563
tags question: http://stackoverflow.com/q/48545535

http://stackoverflow.com/a/56134565
score: 0
answers question: http://stackoverflow.com/q/48631759
type: Answer
has body: if you used pycharm you can add windows-curses from Project Interpreter. go to file -> setting -> Project Interpreter -> click + icon -> search windows-curses-> install. Then you can import curses

http://stackoverflow.com/comment/83983094
has text: Another, sillier way: `sum(int(x) for x in bin(n)[2:]) == 1` and never worry about floatpoint arithmetic :)
score: 2
type: Comment
comment on: http://stackoverflow.com/q/48495015
type: QuestionComment

http://stackoverflow.com/comment/84244476
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48623671
has text: Why on earth would you even *want* to use `list(map(lambda...` instead of a list comprehension?
score: 0

http://stackoverflow.com/q/48575757
has answer: http://stackoverflow.com/a/48584359
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: how to restrict Qlineedit input?
tagged with: qlineedit
has body: I have a QLineEdit and I want to restrict inputting some characters and in it. I have used QValidator but I found out that it could not (or maybe I don't know how to) restrict inputting some characters only as what it did was allowing certain inputs only, further more, setting input restriction like [a-z-A-Z-0-9] or such will also limiting Unicode characters input, which is not what I want. Is there a way that can setup a block list to prevent inputting some illegal characters? Thanks!
tagged with: pyqt
score: 1
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/48638926
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48630109
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/48630109
has body: The request did not succeeded because the POST payload (the dict for the data parameter) need to be wrap in json. response = requests.post( "http://mayaapi.tase.co.il/api/report/filter?logo=0", data=json.dumps({ "Page": 1, "GroupData": [], "DateFrom": "2016-12-31T22:00:00.000Z", "DateTo": "2018-02-03T22:00:00.000Z", "IsBreakingAnnouncement": False, "IsForTaseMember": False, "IsSpecificFund": False, "Q": "דוח חודשי", "QOpt": 1, "ViewPage": 4, }), headers={ "Content-Type": "application/json;charset=UTF-8", "Origin": "http://maya.tase.co.il", "Referer": "http://maya.tase.co.il/reports/fund?q=%7B%22DateFrom%22:%222016-12-31T22:00:00.000Z%22,%22DateTo%22:%222018-02-03T22:00:00.000Z%22,%22QOpt%22:1,%22Page%22:1,%22Q%22:%22%D7%93%D7%95%D7%97%20%D7%97%D7%95%D7%93%D7%A9%D7%99%22,%22events%22:%5B%5D,%22subevents%22:%5B%5D%7D", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", "X-Maya-With": "allow", }, cookies={} ) print('req1', response)

http://stackoverflow.com/comment/84022750
has text: Possible duplicate of [Finding last item that matches criteria in python?](https://stackoverflow.com/questions/37966943/finding-last-item-that-matches-criteria-in-python)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48513956

http://stackoverflow.com/a/48502449
answers question: http://stackoverflow.com/q/48502077
score: 0
type: Answer
has body: If the task in hand is to code it manually; Create a list that we will use to assert the data to at the end. This will be used to store the new order of the list you want order_list = [] We insert the first and second elements of data as this is not being manipulated or re-ordered. order_list.append(data[0]) order_list.append(data[1]) now we check which is bigger out of data[2] and data[4] if data[2] &gt; data[4]: order_list.append(data[2]) else: order_list.append(data[2]) Then repeat this with data elements 3 and 5. You can then assign that new list to be data, by data = order_list or return the new list. If the task does not require you to do this; there is a built in function max() that returns the largest of two elements passed into the function

http://stackoverflow.com/a/48519936
type: AcceptedAnswer
has body: You can use detail_route or list_route decorators. from rest_framework.decorators import list_route class MessageViewSet(viewsets.ModelViewSet): @list_route() def mark_read(self, request): queryset = Message.objects.update(isread=True) return Response({'read':queryset}) With that mark_read method will be available at api/get_messages/mark_read. And you don't need to create separate router, just use one you created for MessageViewSet docs reference
has comment: http://stackoverflow.com/comment/84050817
accepted answer of: http://stackoverflow.com/q/48519881
type: Answer
answers question: http://stackoverflow.com/q/48519881
upvote count: 2
score: 2
downvote count: 0

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

http://stackoverflow.com/comment/84049370
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48509253
has text: @EliKorvigo, I launch jupyter directly from Anaconda. As far as I know, it is completely independent from Pycharm. Is there a way to do it differently?
score: 0

http://stackoverflow.com/q/48615325
possible better answer: http://stackoverflow.com/a/48615403
has title: Why this way of using fucntions arguments does not work?
duplicate of: http://stackoverflow.com/q/1373164
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84227812
has body: Why does this function print arg1 arg2 instead of Hello world? Shouldn't arg be equal to the arguments arg1 and arg2 and then be used in print()? def printer(arg1, arg2): for i in range(2): arg = 'arg{} '.format(str(i+1)) print(arg, end="") printer('Hello', 'world')
has answer: http://stackoverflow.com/a/48615403
has answer: http://stackoverflow.com/a/48615430
has comment: http://stackoverflow.com/comment/84227671
tagged with: python
accepted answer: http://stackoverflow.com/a/48615430
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/48615417
score: 1
linked to: http://stackoverflow.com/q/1373164
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48607152
has body: I give you program example here You can easily understand How objects store in list class my_class: def __init__(self): self.var=1 def setparameter(self,txt): self.txt=txt objects = [my_class() for i in range(3)] # creates multiple objects here for obj in objects: obj.setparameter(5) Objects in a list are pointer for class instances. See its data structures See another example these lists are pointer for sublists List of list a=[[1,2,34],[12,4,5]]
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48606935
type: Answer

http://stackoverflow.com/q/48644137
score: 1
answer count: 1
has body: I am building and fitting an hdbscan model on my data and when I run the script from within the file it works well and quickly, but when I import the file and run it from 'outside' it goes into a weird loop that I don't understand how it started. And I get the following error: ImportError: [joblib] Attempting to do parallel computing without protecting your import on a system that does not support forking. To use parallel-computing in a script, you must protect your main loop using "if __name__ == '__main__'". Please see the joblib documentation on Parallel for more information Here is an excerpt of the code: df_pos_raw, df_pos_training = pre_process_data(df_pos) df_pos_training_std = standardize_df(df_pos_training) # Standardized data, column-wise print "generating model" pos_cls = hdbscan.HDBSCAN(min_cluster_size=10, prediction_data=True) print "fitting model to data" pos_cls.fit(df_pos_training_std) print 'done fitting model' # sns.distplot(pos_cls.labels_, bins=len(set(pos_cls.labels_))) df_filtered = filter_cons_types(df, [3, 5]) print "Done. returning variables" return pos_cls, df_filtered Here is the output when running from 'outside' the file: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; generating model File "C:\ProgramData\Anaconda2\Lib\multiprocessing\forking.py", line 380, in main fitting model to data prepare(preparation_data) File "C:\ProgramData\Anaconda2\Lib\multiprocessing\forking.py", line 510, in prepare '__parents_main__', file, path_name, etc File "C:\Users\sareetn\PycharmProjects\Arad\DataImputation\ClusteringExtrapolation\Dev\run_clustering_based_prediction.py", line 4, in &lt;module&gt; model, raw_df = clustering() File "C:\Users\sareetn\PycharmProjects\Arad\DataImputation\ClusteringExtrapolation\Dev\clustering_model_constype_3_5.py", line 86, in main pos_cls.fit(df_pos_training_std) File "C:\Users\sareetn\PycharmProjects\Arad\venv\lib\site-packages\hdbscan\hdbscan_.py", line 816, in fit self._min_spanni…
favorite count: 0
tagged with: scope
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/48671386
tagged with: joblib
has title: hdbscan Parallel Error When Running After Import
has answer: http://stackoverflow.com/a/48671386
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84123372
type: QuestionComment
has text: Does this "data" folder even exist in specified location?
comment on: http://stackoverflow.com/q/48558677
score: 0
type: Comment

blogger
type: Tag
tags question: http://stackoverflow.com/q/48527480
tag name: blogger

http://stackoverflow.com/q/48571682
has comment: http://stackoverflow.com/comment/84259135
tagged with: python
has title: Make changes in one Column while keeping the dataframe unchanged
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84140400
has body: I would like to make changes in 'Column C' of the dataframe(df) while keeping other values unchanged in the dataframe using python. Condition: If any value in 'Column C' &lt; 5 &amp; 'Column C' > 15,change it to 'NaN' Current Dataframe: Index Column A Column B Column C 0 6 12 15 1 8 8 2 2 10 14 6 3 9 16 3 4 4 3 7 5 2 18 7 Expected Dataframe Output: Index Column A Column B Column C 0 6 12 NaN 1 8 8 NaN 2 10 14 6 3 9 16 NaN 4 4 3 7 5 2 18 7 I tried to use the df.apply() method as shown below but it messed up my indexes. Could you please help? df.loc[df['Column C'].apply(lambda x:np.nan if x &lt;5 and x&gt;15 else x)]
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/48571778
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48571778

http://stackoverflow.com/comment/84196631
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48599902
has text: I'm not sure that you can bring in a class or method any other way. Please see my edits for some additional options.
type: AnswerComment

http://stackoverflow.com/a/48607018
type: Answer
score: 2
has body: I think you need, df=pd.read_csv() first_col=np.array(df.iloc[:0]) df_array=np.array(df.iloc[:,1:])
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48606909

http://stackoverflow.com/comment/84306250
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48644170
type: AnswerComment
has text: Your server should place SSL certificate using the same certificate file. If you want to generate a simple certificate you can see https://stackoverflow.com/questions/8169999/how-can-i-create-a-self-signed-cert-for-localhost/32169444#32169444

http://stackoverflow.com/q/48493722
score: 0
answer count: 0
has body: I am new to flask and web development and having hard time figuring out calling a function inside my flask python app from html side. I am trying to create a button to invoke a function in my python (2.7) side. I tried below html button and python code, but realized it cause submission and web page refreshing. html side: python side: @app.route('/', methods=['post']) def foo(): # some operations here So, I was thinking that I can do something similar to below but, I am having hard time finding out what to do once javascript catches the event. html side: Click python side: # how should this function be exposed? def call_me(): # trying to do something here Could you please explain how to expose a function from flask app to html side without causing webpage refresh or creating form submission or post? Thanks
upvote count: 1
duplicate of: http://stackoverflow.com/q/13081532
linked to: http://stackoverflow.com/q/36846784
downvote count: 1
has title: Flask, exposing a function to html side javascript
duplicate of: http://stackoverflow.com/q/3066070
duplicate of: http://stackoverflow.com/q/5570747
has comment: http://stackoverflow.com/comment/83981169
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83980679
duplicate of: http://stackoverflow.com/q/36143283
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3066070
duplicate of: http://stackoverflow.com/q/20001229
tagged with: python
tagged with: flask

http://stackoverflow.com/comment/84010786
has text: Thanks for your incredibly quick and helpful reply Tai. This is excellent :)
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48507565

http://stackoverflow.com/q/48509732
score: 5
type: UnansweredQuestion
has title: Amazon Web Services: -bash: activate: No such file or directory
has answer: http://stackoverflow.com/a/69626386
has comment: http://stackoverflow.com/comment/84014854
tagged with: python
has body: I'm trying to use Deep Learning AMI (Ubuntu) on Amazon Web Services (AWS). When you login, you get a message as follows (I'm showing part of it here): Please use one of the following commands to start the required environment with the framework of your choice: for MXNet(+Keras1) with Python3 (CUDA 9) _____________________ source activate mxnet_p36 for MXNet(+Keras1) with Python2 (CUDA 9) _____________________ source activate mxnet_p27 for TensorFlow(+Keras2) with Python3 (CUDA 8) ________________ source activate tensorflow_p36 So, what I understood if I would like to run the last environment shown above for instance, is to run the following command: source activate tensorflow_p36 When I run the command however, I get the following: -bash: activate: No such file or directory This is also happening for other environment. Why is that? What should I do to solve the issue? Thanks.
tagged with: amazon-web-services
tagged with: bash
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84016394
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84014571
upvote count: 5

http://stackoverflow.com/a/50128651
answers question: http://stackoverflow.com/q/48533885
type: AcceptedAnswer
downvote count: 0
has body: I think this repo can be useful to you. Robinhood recently opened the web version, and you can easily find the different API calls from Chrome Developer tools. Anyway, this repo already gets most of the endpoints for you. Sample code: from robinhood_crypto_api import Robinhood # user and password are your Robinhood login credentials r = Robinhood(user, password) # Current BTC quotes. quote_info = r.quotes() # Market order to buy/sell BTC market_order_info = r.trade( 'BTCUSD', price=round(float(quote_info['mark_price']) * 1.005, 2), quantity="0.00005", side="buy", time_in_force="gtc", type="market" )
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/48533885
upvote count: 4

http://stackoverflow.com/a/48533526
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48531960
has body: In Django you can change the structure somewhat providing you add your apps to your settings.py file. The structure is mostly just a recommended way, so you could choose to mess around with it, but most people don't mess around too much otherwise it will throw other people who are used to the standard structure. You could take a look at how Ruby On Rails structures their projects for some alternative thoughts: https://www.sitepoint.com/a-quick-study-of-the-rails-directory-structure/

http://stackoverflow.com/a/48527112
has body: The problem is that the tags given for the insert statement needs to be a list. You are using (item) which, I'm guessing, you think is a one-item tuple. It is not a tuple, it's just a string expression. For it to be a tuple it needs a comma (eg: (item,)). Thus, what is getting passed to the widget is something like "DejaVu Sans Mono". The underlying tcl interpreter sees this as a list of three tags: "DejaVu", "Sans", and "Mono". To pass a proper list, either use brackets or include a comma to change your expression into a tuple. Notice in the following example, the command at the end of (item,). display.insert(END, (("%s: " % i) + item +'\n'),(item,))
answers question: http://stackoverflow.com/q/48526888
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84049823
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84159901
has text: I used a list for the dropdown. Thank you for changing the post with a list! OptionMenu(root, self.dropBoard, *ids).grid(row=0, column=0)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48581621
type: Comment

http://stackoverflow.com/q/48575235
has body: I am attempting to create a new task using the Asana API with https://app.asana.com/api/1.0/tasks endpoint. I have been successful in creating some test tasks in the desired project. However I am now trying to also set the values of the custom fields and seem to be hitting a road block. I am using the Python request library. I have a feeling this is an issue with the way I have formatted the post. I have checked a number of sources, including here, as well tinkered and modified the way in which I structure the "options" dictionary. However it does not seem to help. def postTaskToAsana(taskName, taskURL, taskCreated, taskCompleted, taskDue): token = "&lt;TOKEN&gt;" bearerToken = "Bearer " + token header = { "Authorization" : bearerToken } options = { "projects" : ["234234234"], "name" : "Hello, World!", "notes" : "How are you", "assignee" : "2342342342", "custom_fields" : { "234234234234" : "hello" } } url = "https://app.asana.com/api/1.0/tasks" r = requests.post(url, headers=header, data=options) return r If I remove the "custom_fields" from the options dictionary above then the post request works and I can see the newly created task. The response I get back from the above code is: {"errors":[{"message":"Oops! An unexpected error occurred while processing this request. The input may have contained something the server did not know how to handle. For more help, please contact api-support@asana.com and include the error phrase from this response.","phrase":"9 "}]} As noted in this post the goal is to generate JSON for the request in this format: { "data" : { "custom_fields" : { "2342342342" : "INFO" } } } Which as far as I can tell is what my code should be doing. Any help on this would be great, thanks.
answer count: 1
tagged with: asana
tagged with: zapier
tagged with: python-requests
has answer: http://stackoverflow.com/a/48592153
favorite count: 0
type: Question
has title: Asana bad request when attempting to set custom field values (API)
has comment: http://stackoverflow.com/comment/84180762
upvote count: 2
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/41257621
type: AnsweredQuestion
score: 2
tagged with: asana-api
has comment: http://stackoverflow.com/comment/84180766
accepted answer: http://stackoverflow.com/a/48592153

http://stackoverflow.com/q/48502932
score: -1
has answer: http://stackoverflow.com/a/48503093
has answer: http://stackoverflow.com/a/48502971
type: Question
answer count: 2
upvote count: 0
tagged with: python
downvote count: 1
has title: Change the name of rows in Python
favorite count: 0
tagged with: series
type: AnsweredQuestion
has body: I would like to change the name of my rows in python. I got the means of a dataframe via df10mean = df10.mean() This was my output: 1- 256.098455 1+ 302.581844 2- 19116.212118 2+ 23312.823240 3- 1484.770812 3+ 1689.325187 4- 1412.037664 4+ 2042.475828 5- 1109.064987 5+ 1604.215015 6- 1165.800898 6+ 1390.945443 7- 19309.453761 7+ 24180.334620 dtype: float64 Now I wanted to rename the first column. I tried it via df10mean3 = df10mean2.rename(columns={'1-': 'EVC -', '1+': 'EVC +', '2-': 'RBS* mVenus -', '2+': 'RBS* mVenus +', '3-': 'H56-1 mVenus -', '3+': 'H56-1 mVenus +', '4-': 'H56-1 mVenus + T56-0 -', '4+': 'H56-1 mVenus + T56-0 +', '5-': 'H56-2 mVenus -', '5+': 'H56-2 mVenus +', '6-': 'H56-2 mVenus + T56-0 -', '6+': 'H56-2 + T56-0 +', '7-': 'RBS* mVenus T56-0 -', '7+': 'RBS* mVenus T56-0 +'}, inplace = true) The output gives me the same column names as before. It didn't change anything. I tried to fix this problem for two days now. Could you please help me? Thank you!
possible better answer: http://stackoverflow.com/a/48503093
accepted answer: http://stackoverflow.com/a/48502971
tagged with: rename

matlab
tags question: http://stackoverflow.com/q/48579512
tags question: http://stackoverflow.com/q/48574135
type: Tag
tags question: http://stackoverflow.com/q/48618015
tag name: matlab
tags question: http://stackoverflow.com/q/48622269
tags question: http://stackoverflow.com/q/48542674
tags question: http://stackoverflow.com/q/48619840
tags question: http://stackoverflow.com/q/48498595
tags question: http://stackoverflow.com/q/48552517
tags question: http://stackoverflow.com/q/48621407
tags question: http://stackoverflow.com/q/48604370

http://stackoverflow.com/a/48633113
answers question: http://stackoverflow.com/q/48633081
has body: Something like this you mean? &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; data = [[1,3], [2,2], [5,2], [11,11]] &gt;&gt;&gt; data = np.array(data) &gt;&gt;&gt; data array([[ 1, 3], [ 2, 2], [ 5, 2], [11, 11]]) &gt;&gt;&gt; [x for x in data if x[0] == x[1]] [array([2, 2]), array([11, 11])] &gt;&gt;&gt;
type: Answer
has comment: http://stackoverflow.com/comment/84263326
score: 0

pygame
tags question: http://stackoverflow.com/q/48643605
tags question: http://stackoverflow.com/q/48552169
tags question: http://stackoverflow.com/q/48574467
tag name: pygame
tags question: http://stackoverflow.com/q/48608112
tags question: http://stackoverflow.com/q/48525583
tags question: http://stackoverflow.com/q/48502354
tags question: http://stackoverflow.com/q/48545516
tags question: http://stackoverflow.com/q/48500162
tags question: http://stackoverflow.com/q/48601642
tags question: http://stackoverflow.com/q/48601743
tags question: http://stackoverflow.com/q/48572051
tags question: http://stackoverflow.com/q/48516215
tags question: http://stackoverflow.com/q/48631247
tags question: http://stackoverflow.com/q/48601018
tags question: http://stackoverflow.com/q/48490948
tags question: http://stackoverflow.com/q/48614754
tags question: http://stackoverflow.com/q/48503501
tags question: http://stackoverflow.com/q/48596758
tags question: http://stackoverflow.com/q/48631672
type: Tag

http://stackoverflow.com/comment/84256179
type: Comment
comment on: http://stackoverflow.com/a/48629378
type: AnswerComment
score: 0
has text: once I run 10th line of code. However, when I run " If your column is a string" I get the following error - " raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string:"

http://stackoverflow.com/comment/83977615
has text: @sacul Thanks for your comment, good catch. I have added the link to the tutorial now :-)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48492164
score: 0

http://stackoverflow.com/q/48599464
accepted answer: http://stackoverflow.com/a/48599974
answer count: 1
downvote count: 0
upvote count: 10
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has title: Does calling the model.fit method again reinitialize the already trained weights?
score: 10
tagged with: neural-network
tagged with: python
has answer: http://stackoverflow.com/a/48599974
type: AnsweredQuestion
has body: I am using Keras to train a network. Let's say that after 20 epochs I want to stop the training to check if everything is fine, then continue form the 21st epoch. Does calling the model.fit method for a second time reinitialize the already trained weights?
linked to: http://stackoverflow.com/q/42666046

http://stackoverflow.com/comment/84009194
has text: a perfect workaround can be limit the 'p' tags that bs4 finds, for example i write "4", it should print the first 4 'p' tags it find
type: Comment
comment on: http://stackoverflow.com/q/48506950
type: QuestionComment
score: 0

http://stackoverflow.com/q/48603717
has title: Reading a text file into a matrix in Python
has comment: http://stackoverflow.com/comment/84219891
type: UnansweredQuestion
has body: I have text file variable in python containing: A -1 2 -3 4 5 6 B 4 5 6 3 23 5 How do I numpy matrices from this text file in a compact way? I have solved it but it's an ugly and long solution.. idx_A = read_data.find('A') matrix = [item.split() for item in read_data[idx_A:(idx_B+1)].split('\n')[:-1]] A = np.array(list(map(float, matrix[1]))) for i in range(2,len(matrix)-1): A = np.vstack([A,list(map(float, matrix[i]))]) And so forth..
has answer: http://stackoverflow.com/a/48604062
tagged with: python
tagged with: text-files
tagged with: numpy
score: 0
answer count: 2
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/48603749
favorite count: 0
type: Question

http://stackoverflow.com/q/48607694
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/84215109
accepted answer: http://stackoverflow.com/a/48628759
has title: Couldn't open python .exe application
has answer: http://stackoverflow.com/a/48628759
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84255462
has comment: http://stackoverflow.com/comment/84222491
possible better answer: http://stackoverflow.com/a/48628671
has comment: http://stackoverflow.com/comment/84252439
tagged with: anaconda
has comment: http://stackoverflow.com/comment/84254372
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/48628671
tagged with: python
has body: I created a simple face detection app using pyqt5 and opencv 3. I used anaconda 3.6 and anaconda command prompts and used pyinstaller to create the .exe file. After running pyinstaller, the .py file converted to .exe file, and then it's no longer running. Whenever it's clicked on a command prompt it shows an error. I have attached the image. I also tried cx_freeze and with that the command prompt pops up and goes away again within a millisecond. There I could see some numpy import error something, which I couldn't make an image of. For everything I used anaconda cmd prompt and python from anaconda is used. Please help me with a solution
score: -1
has comment: http://stackoverflow.com/comment/84254274
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84217954

http://stackoverflow.com/q/48638398
has comment: http://stackoverflow.com/comment/84274613
has comment: http://stackoverflow.com/comment/84273083
has comment: http://stackoverflow.com/comment/84274675
tagged with: rounding
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84276230
score: 10
has comment: http://stackoverflow.com/comment/84273177
has comment: http://stackoverflow.com/comment/84273805
tagged with: python
has comment: http://stackoverflow.com/comment/84277100
tagged with: rounding-error
has comment: http://stackoverflow.com/comment/84274819
answer count: 4
has comment: http://stackoverflow.com/comment/84274305
has answer: http://stackoverflow.com/a/48659524
has answer: http://stackoverflow.com/a/48639813
upvote count: 11
has comment: http://stackoverflow.com/comment/84273350
has comment: http://stackoverflow.com/comment/84274116
tagged with: numpy
has comment: http://stackoverflow.com/comment/84275582
has title: Numpy rounds in a different way than python
has comment: http://stackoverflow.com/comment/84274432
has comment: http://stackoverflow.com/comment/84276550
has body: The code import numpy as np a = 5.92270987499999979065 print(round(a, 8)) print(round(np.float64(a), 8)) gives 5.92270987 5.92270988 Any idea why? Found nothing relevant in numpy sources. Update: I know that the proper way to deal with this problem is to construct programs in such a way that this difference is irrelevant. Which I do. I stumbled into it in regression testing. Update2: Regarding the @VikasDamodar comment. One shouldn't trust the repr() function: &gt;&gt;&gt; np.float64(5.92270987499999979065) 5.922709875 &gt;&gt;&gt; '%.20f' % np.float64(5.92270987499999979065) '5.92270987499999979065' Update3: Tested on python3.6.0 x32, numpy 1.14.0, win64. Also on python3.6.4 x64, numpy 1.14.0, debian. Update4: Just to be sure: import numpy as np a = 5.92270987499999979065 print('%.20f' % round(a, 8)) print('%.20f' % round(np.float64(a), 8)) 5.92270987000000026512 5.92270988000000020435 Update5: The following code demonstrates on which stage the difference takes place without using str: &gt;&gt;&gt; np.float64(a) - 5.922709874 1.000000082740371e-09 &gt;&gt;&gt; a - 5.922709874 1.000000082740371e-09 &gt;&gt;&gt; round(np.float64(a), 8) - 5.922709874 6.000000496442226e-09 &gt;&gt;&gt; round(a, 8) - 5.922709874 -3.999999442783064e-09 Clearly, before applying 'round' they were the same number. Update6: In contrast to @user2357112's answer, np.round is roughly 4 times slower than round: %%timeit a = 5.92270987499999979065 round(a, 8) 1.18 µs ± 26.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %%timeit a = np.float64(5.92270987499999979065) round(a, 8) 4.05 µs ± 43.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Also in my opinion np.round did a better job rounding to the nearest even than builtin round: originally I got this 5.92270987499999979065 number through dividing 11.84541975 by two.
has comment: http://stackoverflow.com/comment/84273839
has comment: http://stackoverflow.com/comment/84273268
has answer: http://stackoverflow.com/a/48643563
has comment: http://stackoverflow.com/comment/84273255
has comment: http://stackoverflow.com/comment/84273934
has answer: http://stackoverflow.com/a/48643809
has comment: http://stackoverflow.com/comment/84273355
has comment: http://stackoverflow.com/comment/84275960
has comment: http://stackoverflow.com/comment/84274931
downvote count: 1
has comment: http://stackoverflow.com/comment/84275929
has comment: http://stackoverflow.com/comment/84273594
has comment: http://stackoverflow.com/comment/84274737
has comment: http://stackoverflow.com/comment/84276309
favorite count: 0
has comment: http://stackoverflow.com/comment/84274936
type: Question
has comment: http://stackoverflow.com/comment/84276826

http://stackoverflow.com/comment/84275982
has text: that seems like a non-reproduceable error. the code looks fine
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48639744

http://stackoverflow.com/comment/84241032
score: 0
type: Comment
type: QuestionComment
has text: Could you elaborate what you mean by "but none of the approaches worked properly"?
comment on: http://stackoverflow.com/q/48621588

http://stackoverflow.com/comment/84123610
comment on: http://stackoverflow.com/q/48555402
has text: I can do that, but later I still would grab those bayer format frames from a usb camera. Right now I looking at gstreamer pipeline, which is enabled starting cv 3.1.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84200202
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48566181
has text: If I had to do something like dynamic layout, I will look toward [bokeh.models api](https://bokeh.github.io/blog/2017/7/5/idiomatic_bokeh/). You can easily add and remove glyphs from plot renderers (which is a list), I imagine you can do same with document/layout..

http://stackoverflow.com/comment/84133520
comment on: http://stackoverflow.com/a/48568505
type: Comment
type: AnswerComment
has text: Did you reproduce OP's problem?
score: 0

http://stackoverflow.com/comment/84203135
type: Comment
comment on: http://stackoverflow.com/a/48603111
type: AnswerComment
has text: `pandas` method isn't good because it builds the entire list of days (which could be very long) and then filters for ones with day = 16. The second method is roughly equivalent to @DYZ's solution, but you might get a small benefit from using list comprehension versus looping `list.append`.
score: 0

http://stackoverflow.com/q/48593578
tagged with: arguments
has comment: http://stackoverflow.com/comment/84190086
type: Question
tagged with: args
has title: Validating parameters with default value using both *args and **kwargs in Python
has answer: http://stackoverflow.com/a/48593659
type: UnansweredQuestion
downvote count: 0
tagged with: keyword-argument
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48593622
has comment: http://stackoverflow.com/comment/84184387
favorite count: 0
answer count: 3
has body: I have been looking for the answer to this for sometime but I always end up looking at tutorials covering the basics. My problem is - If I have a function: def foo(a, b, *args, **kwargs): if args[0]: if args[0] in range(1, 4): x=args[0] else: raise ValueError("Eww that is one ugly x!") else: x = kwargs.get('x', 3) if args[1]: if args[1] in ['some','list','of','strings']: y = args[1] else: raise ValueError("Invalid y") else: y = kwargs.get('y', "some") if x == 1: print("Good") elif x == 2: print("Bad") elif x == 3: print("Clint") else: raise ValueError("Eww that is one ugly x!") if y == 'some': print(y + str(x)) elif y == 'list': print("happy") elif y == 'of': print("healthy") elif y == 'strings': print(y + 'me') else: raise ValueError("Invalid y") I am looking for a simpler way of treating args[0] and kwargs.get('x') as equivalent - insofar as I would like to perform the same type and value validation checks on which ever is assigned. In short how do I map the value of both args[i] and kwargs.get(k) to the same object.
linked to: http://stackoverflow.com/q/36901
score: 1
has answer: http://stackoverflow.com/a/65061967

http://stackoverflow.com/a/48611462
score: 0
has comment: http://stackoverflow.com/comment/84219610
has comment: http://stackoverflow.com/comment/84219403
has body: You can do the following: # Note: if id field is primary key, you don´t need to consult by user also message_updated = Message.objects.filter(user=pk, id=id).update(**json_data)
type: Answer
has comment: http://stackoverflow.com/comment/84219532
answers question: http://stackoverflow.com/q/48611154
has comment: http://stackoverflow.com/comment/84219501

http://stackoverflow.com/comment/84220625
type: Comment
type: QuestionComment
score: 0
has text: Hi, Simon. A python code.
comment on: http://stackoverflow.com/q/48612084

send
type: Tag
tags question: http://stackoverflow.com/q/48584098
tag name: send

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/48523047
tags question: http://stackoverflow.com/q/48641130
tags question: http://stackoverflow.com/q/48611154
tags question: http://stackoverflow.com/q/48600911
tags question: http://stackoverflow.com/q/48590064
tags question: http://stackoverflow.com/q/48606037
tags question: http://stackoverflow.com/q/48552470
tags question: http://stackoverflow.com/q/48582148
tags question: http://stackoverflow.com/q/48508000
tags question: http://stackoverflow.com/q/48525645
tags question: http://stackoverflow.com/q/48592239
tags question: http://stackoverflow.com/q/48497115
tags question: http://stackoverflow.com/q/48506031
tags question: http://stackoverflow.com/q/48636633
tags question: http://stackoverflow.com/q/48637315
tags question: http://stackoverflow.com/q/48572581
tags question: http://stackoverflow.com/q/48598429
tags question: http://stackoverflow.com/q/48544128
tags question: http://stackoverflow.com/q/48516612
tags question: http://stackoverflow.com/q/48573874
tags question: http://stackoverflow.com/q/48607309
tags question: http://stackoverflow.com/q/48585865
tags question: http://stackoverflow.com/q/48587558
tags question: http://stackoverflow.com/q/48623389
tags question: http://stackoverflow.com/q/48632877
tags question: http://stackoverflow.com/q/48619044
tags question: http://stackoverflow.com/q/48488703
tags question: http://stackoverflow.com/q/48532194
tags question: http://stackoverflow.com/q/48568959
tags question: http://stackoverflow.com/q/48628163
tags question: http://stackoverflow.com/q/48605163
tags question: http://stackoverflow.com/q/48548098
tags question: http://stackoverflow.com/q/48496720
tags question: http://stackoverflow.com/q/48616663
tags question: http://stackoverflow.com/q/48571418
tags question: http://stackoverflow.com/q/48541523
tags question: http://stackoverflow.com/q/48572925
tags question: http://stackoverflow.com/q/48494329
tags question: http://stackoverflow.com/q/48514222
type: Tag
tags question: http://stackoverflow.com/q/48642639
tags question: http://stackoverflow.com/q/48518194
tags question: http://stackoverflow.com/q/48559491

http://stackoverflow.com/comment/84249366
has text: Can you share your code?
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48555860

http://stackoverflow.com/a/48549912
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48549555
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48549555
has comment: http://stackoverflow.com/comment/84113516
score: 2
has body: Use CreateFont and then select the font in to device context, example: dc.StartPage() fontdata = { 'name':'Arial', 'height':100, 'italic':True, 'weight':win32con.FW_NORMAL} font = win32ui.CreateFont(fontdata); dc.SelectObject(font) dc.TextOut(100,2000, 'HELLO WORLD!') ... To make a better calculation for font size, use the following based on CreateFont WinAPI reference: def getfontsize(dc, PointSize): inch_y = dc.GetDeviceCaps(win32con.LOGPIXELSY) return int(-(PointSize * inch_y) / 72) Example: now you can use this to draw with font size 11 at the center of the page fontsize = getfontsize(dc, 11) fontdata = { 'name':'Consolas', 'height':fontsize} font = win32ui.CreateFont(fontdata); dc.SelectObject(font) Also, LOGPIXELSY/LOGPIXELSY and PHYSICALWIDTH/PHYSICALHEIGHT can be used to calculate the coordinates more accurately.
downvote count: 0
type: Answer

http://stackoverflow.com/q/48635607
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84288390
has comment: http://stackoverflow.com/comment/84286135
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84273742
has comment: http://stackoverflow.com/comment/84286177
has comment: http://stackoverflow.com/comment/84318714
has comment: http://stackoverflow.com/comment/84279715
has comment: http://stackoverflow.com/comment/84275954
tagged with: python
has comment: http://stackoverflow.com/comment/84286590
score: -1
has comment: http://stackoverflow.com/comment/84285857
has body: Please find above the Screenshot,
has answer: http://stackoverflow.com/a/48661105
has comment: http://stackoverflow.com/comment/84274866
has comment: http://stackoverflow.com/comment/84287344
has comment: http://stackoverflow.com/comment/84286941
tagged with: odoo
upvote count: 0
has comment: http://stackoverflow.com/comment/84286328
has comment: http://stackoverflow.com/comment/84318424
answer count: 1
has comment: http://stackoverflow.com/comment/84286414
has title: Security Restrictions while creating leave request
has comment: http://stackoverflow.com/comment/84276026
downvote count: 1

http://stackoverflow.com/q/48570625
has comment: http://stackoverflow.com/comment/84138078
tagged with: python
type: AnsweredQuestion
has body: I made a python script using glob (https://docs.python.org/2/library/glob.html) this script matches JPG image with its matching XML annotation and moves it to a different folder (for example I have 1.jpg, 2.jpg, 3.jpg, 1.xml, 3.xml) then it moves (1.jpg,1.xml and 3.jpg,3.xml) to a new folder. 2.jpg is not moved because there no xml matching this image import os import glob import os.path import shutil path = os.getcwd() j=0 os.chdir("path\\to\\folder\\") os.mkdir("image_with_xml") # create a new folder newpath = "path\\to\\folder\\"+"image_with_xml" while j &lt; len(glob.glob(path+"\\*"))-1: a=glob.glob(path+"\\*")[j] b=glob.glob(path+"\\*")[j+1] print(a) a1 = os.path.splitext(a)[0] b1 = os.path.splitext(b)[0] if a1==b1: j=j+2 shutil.move(a,newpath) # move image to new path. shutil.move(b,newpath) # move image to new path. else: j=j+1 The above code works well for moving a few, but not all images to new folder, in order to move the remaining images I have to create new folder inside the script then the remaining images are moved there(For example: Lets say I have 100 jpg with 100 matching XML then the first time I run this script only 62 are moved to new folder, the second time I run the script with different folder name the remaining 38 are moved to next folder). How do I modify script such that all images with matching XML are moved to one folder?
has comment: http://stackoverflow.com/comment/84138401
accepted answer: http://stackoverflow.com/a/48571873
has comment: http://stackoverflow.com/comment/84138746
answer count: 1
downvote count: 0
score: 1
has title: Python script to move matching images to separate folder
upvote count: 1
favorite count: 0
tagged with: pattern-matching
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84138415
tagged with: glob
has comment: http://stackoverflow.com/comment/84138624
has comment: http://stackoverflow.com/comment/84138448
has answer: http://stackoverflow.com/a/48571873

http://stackoverflow.com/comment/84026513
comment on: http://stackoverflow.com/q/48516013
type: Comment
type: QuestionComment
score: 0
has text: Your penultimate line assigns number to a list of integers per the list comprehension. You need to access its elements to get the integers, e.g. `number[0]`.

http://stackoverflow.com/comment/84305358
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48619162
type: QuestionComment
has text: The RubyMarshal project says it is at least partially possible, though it can only translate basic datatypes: float, bool, int, str, nil (mapped to None), array (mapped to list) and hash (mapped to dict).

http://stackoverflow.com/q/48543257
type: AnsweredQuestion
score: 0
has title: What is the difference between oversampling minority data and simulating minority data?
has body: Oversampled data as in those created by the SMOTHE and ADASYN method. Simulated data as in those created by statistics, using extreme mean values, bootstrapping and measuring performance with the p-value. The application is to increase the minority class of underrepresented data using python.
type: Question
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48544648
has answer: http://stackoverflow.com/a/48544648
tagged with: statistics

http://stackoverflow.com/comment/129429647
comment on: http://stackoverflow.com/a/48714519
type: Comment
has text: @gCoh Sorry if my question is trivial, but what is it the `requirements.txt` file?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48628571
score: 1
has comment: http://stackoverflow.com/comment/84326993
answer count: 1
has comment: http://stackoverflow.com/comment/84333373
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84331402
tagged with: crosstab
downvote count: 0
upvote count: 1
has body: So what I'm doing creating a webpage that the user can run a Cross Tabulation analysis on selected rows and columns of a imported datafile. I'm converting the file into a pandas dataframe, and then using pandas.crosstab to process it. However, because crosstab outputs a "stacked", or multi-indexed, table, I'm having to pivot it so it's easier to use and output back to the webpage. I've been trying to use the pivot function that pandas has, but having trouble finding a good, dynamic example. Here's some documentation of the pivoting in pandas I've been looking at, but it doesn't show an example where the column and row labels would be dynamic. Right now my crosstab function is: cross_tab = pd.crosstab([dataframe[row] for row in selected_rows], [dataframe[col] for col in selected_columns], margins=False, dropna=False) And say my dataframe is... +-----+------------+-------+ |id |credit card |gender | +-----+------------+-------+ |1 |chase |F | |2 |visa |M | |3 |chase |M | |4 |chase |F | |5 |mastercard |M | |6 |visa |M | |7 |mastercard |F | |8 |mastercard |M | |9 |mastercard |M | |10 |visa |M | +-----+------------+-------+ And if I run it with the selected rows being ['id'] and columns ['credit card', 'gender'] it would look like... +------------+----------------+-----------+-------+ |credit_card |americanexpress |mastercard |visa | +------------+----------------+-----------+-------+ |gender | F M | F M | F M | +------------+----------------+-----------+-------+ |id | | | | |1 | 1 0 | 0 0 | 0 0 | |2 | 0 0 | 0 0 | 0 1 | |3 | 0 1 | 0 0 | 0 0 | |4 | 1 0 | 0 0 | 0 0 | |5 | 0 0 | 0 1 | 0 0 | |6 | 0 0 | 0 0 | 0 1 | |7 | 0 0 | 1 0 | 0 0 | |8 | 0 0 | 0 1 | 0 0 | |9 | 0 0 | 0 1 | 0 0 | |10 | 0 0 | 0 0 | 0 1 | +------------+----------------+-----------+-------+ I'm having trouble pivoting, or just "unstacking", the crosstab to be stored, then outputted to the webpage afterwards. I've been trying to use the pandas.pivot to do this, but I'm getting errors from it. I'm pretty sure i…
tagged with: python
accepted answer: http://stackoverflow.com/a/48951646
has title: Cross Tab Analysis in Python Pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48951646
has comment: http://stackoverflow.com/comment/84254040
has comment: http://stackoverflow.com/comment/84334193
tagged with: pandas

http://stackoverflow.com/q/48568700
downvote count: 0
has body: I am looking to read a parquet file that is stored in HDFS and I am using Python to do this. I have this code below but it does not open the files in HDFS. Can you help me change the code to do this? sc = spark.sparkContext from pyspark.sql import SQLContext sqlContext = SQLContext(sc) df = sqlContext.read.parquet('path-to-file/commentClusters.parquet') Also, I am looking to save the Dataframe as a CSV file as well.
favorite count: 0
type: Question
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/48572391
tagged with: python
has title: How to open a parquet file in HDFS with Python?
type: AnsweredQuestion
score: 3
tagged with: parquet
upvote count: 3
linked to: http://stackoverflow.com/q/27478096
answer count: 1
has answer: http://stackoverflow.com/a/48572391

http://stackoverflow.com/a/71084005
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/48511076
type: Answer
has body: If you do want to extend the default permissions, this seems to work. Disclaimer: I found it by looking into DRF's code, not sure it is documented. from rest_framework.settings import api_settings class UserViewSet(viewsets.ModelViewSet): permission_classes = [*api_settings.DEFAULT_PERMISSION_CLASSES, TokenHasReadWriteScope]
score: 5

http://stackoverflow.com/q/48553070
score: 0
has title: python: handle out of range numpy indices
tagged with: numpy
type: Question
accepted answer: http://stackoverflow.com/a/48553558
has comment: http://stackoverflow.com/comment/84103350
has comment: http://stackoverflow.com/comment/84102618
has answer: http://stackoverflow.com/a/48553558
tagged with: python
answer count: 1
tagged with: indexing
has body: I am using the following code to rotate an image along it's y-axis. y, x = np.indices(im1.shape[:2]) return im1[y, ((x-im1.shape[1]/2)/math.cos(t*math.pi/2)+im1.shape[1]/2).astype(np.int)] Some of the values are intentionally out-of-range. I would like for out of range pixels to be black (0, 0, 0). How can I allow the in range indices to work, while replacing the out-of range with black?
type: AnsweredQuestion

http://stackoverflow.com/comment/84317239
comment on: http://stackoverflow.com/q/48560138
type: Comment
type: QuestionComment
has text: @elphz Thanks. I may just try to do the same thing on my private computer, to avoid stupid corporate firewalls, so I can see if it works when not using plotly.offline
score: 0

erp
tags question: http://stackoverflow.com/q/48570903
tags question: http://stackoverflow.com/q/48552182
tag name: erp
type: Tag

http://stackoverflow.com/comment/84179395
score: 0
type: AnswerComment
has text: @NikhilRaghunath is it guaranteed that every post title will have a link in it and every link will have a `['title']` attribute?
comment on: http://stackoverflow.com/a/48590431
type: Comment

matplotlib
tags question: http://stackoverflow.com/q/48598829
tags question: http://stackoverflow.com/q/48563526
tags question: http://stackoverflow.com/q/48626335
tags question: http://stackoverflow.com/q/48570059
tags question: http://stackoverflow.com/q/48520393
tags question: http://stackoverflow.com/q/48620803
tags question: http://stackoverflow.com/q/48575854
tags question: http://stackoverflow.com/q/48620858
tags question: http://stackoverflow.com/q/48497092
tags question: http://stackoverflow.com/q/48529905
tags question: http://stackoverflow.com/q/48610439
tags question: http://stackoverflow.com/q/48575657
tags question: http://stackoverflow.com/q/48506782
tags question: http://stackoverflow.com/q/48630998
tags question: http://stackoverflow.com/q/48621085
tags question: http://stackoverflow.com/q/48572340
tags question: http://stackoverflow.com/q/48570021
tags question: http://stackoverflow.com/q/48529746
tags question: http://stackoverflow.com/q/48500152
tags question: http://stackoverflow.com/q/48586174
tags question: http://stackoverflow.com/q/48639625
tags question: http://stackoverflow.com/q/48587997
tags question: http://stackoverflow.com/q/48550643
tags question: http://stackoverflow.com/q/48539462
tags question: http://stackoverflow.com/q/48575325
tags question: http://stackoverflow.com/q/48498868
tags question: http://stackoverflow.com/q/48577990
tags question: http://stackoverflow.com/q/48509752
tags question: http://stackoverflow.com/q/48547697
tags question: http://stackoverflow.com/q/48632617
tags question: http://stackoverflow.com/q/48542805
tags question: http://stackoverflow.com/q/48579733
tags question: http://stackoverflow.com/q/48584159
tags question: http://stackoverflow.com/q/48609442
tags question: http://stackoverflow.com/q/48639369
tags question: http://stackoverflow.com/q/48625019
tags question: http://stackoverflow.com/q/48594447
tags question: http://stackoverflow.com/q/48569684
tags question: http://stackoverflow.com/q/48620370
tags question: http://stackoverflow.com/q/48593644
tags question: http://stackoverflow.com/q/48615377
tags question: http://stackoverflow.com/q/48637793
tags question: http://stackoverflow.com/q/48526663
tags question: http://stackoverflow.com/q/48579947
tags question: http://stackoverflow.com/q/48619933
tags question: http://stackoverflow.com/q/48643243
tags question: http://stackoverflow.com/q/48642846
tags question: http://stackoverflow.com/q/48589567
tags question: http://stackoverflow.com/q/48520968
tags question: http://stackoverflow.com/q/48584730
tags question: http://stackoverflow.com/q/48517298
tags question: http://stackoverflow.com/q/48501080
tags question: http://stackoverflow.com/q/48611156
tags question: http://stackoverflow.com/q/48506842
tags question: http://stackoverflow.com/q/48498766
tags question: http://stackoverflow.com/q/48548081
tags question: http://stackoverflow.com/q/48613920
tags question: http://stackoverflow.com/q/48601175
tag name: matplotlib
tags question: http://stackoverflow.com/q/48491154
tags question: http://stackoverflow.com/q/48514347
tags question: http://stackoverflow.com/q/48627202
tags question: http://stackoverflow.com/q/48530886
tags question: http://stackoverflow.com/q/48618992
tags question: http://stackoverflow.com/q/48586738
tags question: http://stackoverflow.com/q/48587335
tags question: http://stackoverflow.com/q/48530936
tags question: http://stackoverflow.com/q/48570180
tags question: http://stackoverflow.com/q/48633293
tags question: http://stackoverflow.com/q/48527748
tags question: http://stackoverflow.com/q/48639106
tags question: http://stackoverflow.com/q/48630246
tags question: http://stackoverflow.com/q/48603722
tags question: http://stackoverflow.com/q/48498161
tags question: http://stackoverflow.com/q/48539558
tags question: http://stackoverflow.com/q/48505435
tags question: http://stackoverflow.com/q/48588538
tags question: http://stackoverflow.com/q/48495799
tags question: http://stackoverflow.com/q/48639339
tags question: http://stackoverflow.com/q/48491984

http://stackoverflow.com/comment/84245681
type: Comment
type: QuestionComment
has text: Add by editing to your question version info of python, pip, cmake and win10: e.g.command-line: `pip -V` gives pip and python info.
score: 0
comment on: http://stackoverflow.com/q/48624415

http://stackoverflow.com/comment/84088984
comment on: http://stackoverflow.com/q/48546446
type: QuestionComment
score: 0
has text: Sorry, In the dataframe `result` shouldn't one of the indexes where `Hr` and `RR` are `NaN` be 1 instead of zero
type: Comment

http://stackoverflow.com/a/48539569
has comment: http://stackoverflow.com/comment/84076105
has comment: http://stackoverflow.com/comment/84089528
has comment: http://stackoverflow.com/comment/84089044
score: 1
has body: This answer should help in all cases. No imports required and no sorting required for the data. def split_list(l): dividable=False index=0 for i in range(len(l)): if l[i]==sum(l)-l[i]: dividable=True index=i break if dividable: l1=l[index] l.remove(l[index]) return (l1,l) else: return False Might not be the optimised way, but a better and clear way to understand for beginners. split_list([1,2,3,4,5,15]) [15],[1,2,3,4,5] Hope this helps. Thanks
type: Answer
answers question: http://stackoverflow.com/q/48538451
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48532411
has body: I have the following code, which has been simplified: import concurrent.futures pool = concurrent.futures.ThreadPoolExecutor(8) def _exec(x): return x + x myfuturelist = pool.map(_exec,[x for x in range(5)]) # How do I wait for my futures to finish? for result in myfuturelist: # Is this how it's done? print(result) #... stuff that should happen only after myfuturelist is #completely resolved. # Documentation says pool.map is asynchronous The documentation is weak regarding ThreadPoolExecutor.map. Help would be great. Thanks!
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/56264869
answer count: 3
has answer: http://stackoverflow.com/a/56264869
favorite count: 0
upvote count: 17
score: 17
tagged with: python-3.x
has answer: http://stackoverflow.com/a/70003564
has title: How do I wait for ThreadPoolExecutor.map to finish
type: Question
tagged with: python-multithreading
accepted answer: http://stackoverflow.com/a/48534215
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48534215

http://stackoverflow.com/q/48531943
type: Question
upvote count: 3
has body: Building my first gRPC server application. I don't know if this is a common problem, but my rpc servicer is getting quite large. With servicer I mean the class that inherit from the generated xxx_pb2_grpc.xxxServicer (in python at least). At the moment it has 19 RPC calls. So my class which implements these calls is getting quite large. Is there any way of splitting the Servicer into logical segments, considering that some RPC calls are for music playback, some are for data management and some for communicating with a downloader (and more to come probably). I could make multiple service types in proto file however xxx_pb2_grpc.add_xxxServicer_to_server only accepts a single servicer! Thanks in advance. EDIT: FEB 3, 18 I've split up the services in the following manor: service MusicPlayback { ... # rpc calls } service DataManager { ... # rpc calls } service MediaDownloader { ... # rpc calls } Then with the python code generated, I've setup the server like this: # Setup gRPC Server self._gserver = grpc.server(futures.ThreadPoolExecutor(max_workers=self._connection_count)) rpc.add_MusicPlaybackServicer_to_server(self._mplayer, self._gserver) rpc.add_DataManagerServicer_to_server(self._data_manager, self._gserver) rpc.add_MediaDownloaderServicer_to_server(self._media_downloader, self._gserver) self._gserver.add_insecure_port('[::]:' + str(self._port))
downvote count: 0
accepted answer: http://stackoverflow.com/a/48551179
type: AnsweredQuestion
score: 3
tagged with: protocol-buffers
has answer: http://stackoverflow.com/a/48551179
tagged with: grpc
answer count: 1
tagged with: python
has title: Split up servicer gRPC python
favorite count: 0

http://stackoverflow.com/q/48538244
has comment: http://stackoverflow.com/comment/84071966
score: 2
has body: I have an excel spreadsheet which has some formulae with random number generators. This is so every time I reopen the spreadsheet, the numbers are slightly different. I noticed that if I opened the spreadsheet, didn't touch the numbers, then read the spreadsheet into a pandas dataframe, the data in pandas is different to the excel I have open. Does reading in the spreadsheet into pandas have the same effect as reopening the spreadsheet, and therefore randomizes the numbers each time?
answer count: 0
has comment: http://stackoverflow.com/comment/84071559
tagged with: pandas
upvote count: 3
has comment: http://stackoverflow.com/comment/84071561
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42102674
tagged with: python
has title: Does pandas read in excel formulae?
tagged with: excel

http://stackoverflow.com/a/48603305
type: Answer
upvote count: 4
has body: You should merge on indexes, not on columns: s1 = pd.merge(dfA, dfB, left_index=True, right_index=True) Assigning a name to an index does not make it a column.
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48603283

http://stackoverflow.com/comment/86081022
type: Comment
score: 0
type: AnswerComment
has text: Added an edit and I think I got closer to make it work. A new error came out. Please take a look at it if you can.
comment on: http://stackoverflow.com/a/49487542

http://stackoverflow.com/comment/84232197
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48617820
has text: `result = await response.read()` is this not same as sending the callback?

http://stackoverflow.com/q/48491493
has comment: http://stackoverflow.com/comment/84014520
tagged with: python
has body: Say I have two arrays of similar dimensions. One is filled with numbers 1 to 6 and the other is filled with the letters a, b and c. In the end I want to have an array where a, b and c are replaced with the maximum value the corresponding cells in the other array have: x= [[1,2,3],[4,5,6,]] y= [[a,b,c],[b,c,a]] I would like: z = [[6,4,5],[4,5,6]] I cant get my head around it, I feel like it should be possible with np.where and max, but I hope you guys can help me. cheers
answer count: 4
tagged with: reference
has comment: http://stackoverflow.com/comment/83976302
has answer: http://stackoverflow.com/a/48491888
score: 0
has answer: http://stackoverflow.com/a/48491832
has comment: http://stackoverflow.com/comment/83976670
type: Question
tagged with: numpy
has title: python cross referencing two numpy arrays
has answer: http://stackoverflow.com/a/48491921
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48491794
tagged with: arrays

http://stackoverflow.com/a/48629192
upvote count: 1
has body: try this : import operator df.drop((df.loc[operator.and_(df.student == 'current', df.grade == 'fail')]).index, inplace=True)
accepted answer of: http://stackoverflow.com/q/48628883
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48628883
downvote count: 0
type: Answer

http://stackoverflow.com/a/48548893
has comment: http://stackoverflow.com/comment/84108482
accepted answer of: http://stackoverflow.com/q/48547729
has body: As @Florent B. correctly suggested you can simply use direct HTTP request to API to get required data: import requests import json url = 'http://api.seaaroundus.org/api/v1/eez/exploited-organisms/?region_id=8' response = requests.get(url) for fish in response.json()['data']: print("{} ({})".format(fish["common_name"], fish["scientific_name"]))
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48547729
has comment: http://stackoverflow.com/comment/84103022
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48587871
answers question: http://stackoverflow.com/q/48587811
downvote count: 0
type: Answer
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84173183
accepted answer of: http://stackoverflow.com/q/48587811
has body: The error message is pretty clear: ValueError: unsupported format character 'A' (0x41) at index 115 Index 115 of your string is here: "...NORAD_CAT_ID/39090/orderby/TLE_LINE1%20ASC/format/tleid=%" % nn ↑ You're using percent-formatting but your string already contains percent signs for the unrelated percent-encoding in the URL. You can either double-escape your existing percent signs and fix your last format string: "...NORAD_CAT_ID/39090/orderby/TLE_LINE1%%20ASC/format/tleid=%s" % nn ↑ ↑ Or just concatenate the string: "...NORAD_CAT_ID/39090/orderby/TLE_LINE1%20ASC/format/tleid=" + str(nn)
score: 2

http://stackoverflow.com/a/48644795
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48644522
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48644522
upvote count: 1
type: AcceptedAnswer
has body: Ensure that you enclose column names that start with special characters in escaped quotes, like this: \"__ID\"

pyqt
type: Tag
tags question: http://stackoverflow.com/q/48575757
tags question: http://stackoverflow.com/q/48553871
tags question: http://stackoverflow.com/q/48496311
tags question: http://stackoverflow.com/q/48603517
tags question: http://stackoverflow.com/q/48622395
tags question: http://stackoverflow.com/q/48582654
tags question: http://stackoverflow.com/q/48593640
tags question: http://stackoverflow.com/q/48596114
tags question: http://stackoverflow.com/q/48558873
tags question: http://stackoverflow.com/q/48565703
tags question: http://stackoverflow.com/q/48533903
tags question: http://stackoverflow.com/q/48606072
tags question: http://stackoverflow.com/q/48575298
tags question: http://stackoverflow.com/q/48519308
tags question: http://stackoverflow.com/q/48630419
tags question: http://stackoverflow.com/q/48499713
tags question: http://stackoverflow.com/q/48616936
tags question: http://stackoverflow.com/q/48632405
tags question: http://stackoverflow.com/q/48600328
tags question: http://stackoverflow.com/q/48544593
tags question: http://stackoverflow.com/q/48543493
tags question: http://stackoverflow.com/q/48623118
tags question: http://stackoverflow.com/q/48585387
tags question: http://stackoverflow.com/q/48520176
tags question: http://stackoverflow.com/q/48592849
tags question: http://stackoverflow.com/q/48627325
tags question: http://stackoverflow.com/q/48639185
tags question: http://stackoverflow.com/q/48592339
tags question: http://stackoverflow.com/q/48511765
tags question: http://stackoverflow.com/q/48571049
tag name: pyqt
tags question: http://stackoverflow.com/q/48621825
tags question: http://stackoverflow.com/q/48624104
tags question: http://stackoverflow.com/q/48632878
tags question: http://stackoverflow.com/q/48586875
tags question: http://stackoverflow.com/q/48507168
tags question: http://stackoverflow.com/q/48537856
tags question: http://stackoverflow.com/q/48610840

http://stackoverflow.com/comment/84080641
score: 2
has text: @NickA of course not, I don't consider myself an ultimate authority on Python :) the collective knowledge of SO on the other hand...
comment on: http://stackoverflow.com/q/48541691
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48525395
score: 0
has answer: http://stackoverflow.com/a/48525563
has answer: http://stackoverflow.com/a/48525794
has body: I have a bunch of data stored in a single column in a txt file, something like this: name1 address1 number1 name2 address2 number2 name3 address3 number3 name4 address4 number4 etc I want to sort this in 3 columns so it can be imported to excel. Any clues?
has comment: http://stackoverflow.com/comment/84046305
type: Question
has answer: http://stackoverflow.com/a/48526386
tagged with: python
has answer: http://stackoverflow.com/a/48525949
answer count: 4
has title: Txt list divide columns
possible better answer: http://stackoverflow.com/a/48525794
accepted answer: http://stackoverflow.com/a/48525563
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/q/48514410
downvote count: 0
answer count: 1
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84027807
has comment: http://stackoverflow.com/comment/84036511
tagged with: openstack
has comment: http://stackoverflow.com/comment/84023540
favorite count: 0
tagged with: xargs
type: Question
has comment: http://stackoverflow.com/comment/84074276
has comment: http://stackoverflow.com/comment/84078385
has comment: http://stackoverflow.com/comment/84074505
linked to: http://stackoverflow.com/q/47937446
has comment: http://stackoverflow.com/comment/84073899
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84078416
has comment: http://stackoverflow.com/comment/84023583
tagged with: python
has title: use xargs and keep CPU load of remote server to minimum
has body: I used xargs for parallel processing. This thread follows what I had. Parallel processing with xargs in bash But the parallel processing increased CPU load. I was running the script for 57 openstack tenants to fetch results from them. This report is running every 2 hours which is causing CPU spike. To decrease the load, I thought of adding the random sleep time...something like below but it didn't do much help. I am not sure if I can use NICE to set a priority because the results I am fetching are from openstack server. If it's possible, please let me know. I could remove the parallel processing but this will take 6 hours for me to get all the reports from tenants. So that is not an option. If there is any other way to optimize this...any ideas or suggestions would be great. source ../creds/base printf '%s\n' A B C D E F G H I J K L M N O P | xargs -n 3 -P 8 bash -c 'for tenant; do source ../creds/"$tenant" python ../tools/openstack_resource_list.py "$tenant"&gt; ./reports/openstack_reports/"$tenant".html sleep $[ ( $RANDOM % 10 ) + 1 ]s done' _ Python file with open('../floating_list/testReports/'+tenant_file+'.csv', 'wb') as myfile: fields = ['Name', 'Volume', 'Flavor', 'Image', 'Floating IP'] writer = csv.writer(myfile) writer.writerow(fields) try: for i in servers: import io, json with open('../floating_list/testReports/'+tenant_file+'.json', 'w') as e: e.write(check_output(['openstack', 'server', 'show', i.name, '-f', 'json'])) with open('../floating_list/testReports/'+tenant_file+'.json', 'r') as a: data = json.load(a) name.append(i.name) volume = data.get('os-extended-volumes:volumes_attached', None) if volume: vol = [d.get('id', {}) for d in volume if volume] vol_name_perm = [] for i in vol: try: vol_name1 = (check_output(['openstack', 'volume', 'show', i, '-c', 'name', '-f', 'value'])).rstrip() vol_name_perm.append(vol_name1) except: vol_name_perm.append('Error') vol_join = ','.join(vol_name_perm) vol_name.append(vol_join) else: vol_name.append('None') ... …
has comment: http://stackoverflow.com/comment/84023611
has comment: http://stackoverflow.com/comment/84151400
has comment: http://stackoverflow.com/comment/84072879
tagged with: bash
has answer: http://stackoverflow.com/a/48568464
has comment: http://stackoverflow.com/comment/84036489
tagged with: multithreading
has comment: http://stackoverflow.com/comment/84072551

http://stackoverflow.com/q/48535148
type: AnsweredQuestion
tagged with: quantlib
score: 0
answer count: 1
tagged with: quantlib-swig
has title: QuantLib for Python RuntimeError: vega not provided
type: Question
tagged with: python-3.x
has body: Pricing a plain vanilla American option with the binomial pricing engine and Cox-Rubinstein model. When attempting to retrieve vega, I receive the subject error: Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/opt/conda/lib/python3.6/site-packages/QuantLib.py", line 10506, in vega return _QuantLib.VanillaOption_vega(self) RuntimeError: vega not provided This despite vega being a method of american_option: &gt;&gt;&gt; dir(american_option) # scroll to the right --&gt; ['NPV', '__class__', '__del__', '__delattr__', '__deref__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__swig_destroy__', '__weakref__', 'asObservable', 'delta', 'dividendRho', 'errorEstimate', 'freeze', 'gamma', 'impliedVolatility', 'isExpired', 'priceCurve', 'recalculate', 'rho', 'setPricingEngine', 'strikeSensitivity', 'theta', 'thetaPerDay', 'this', 'thisown', 'unfreeze', 'vega'] Here is the code which is based on several online examples: &gt;&gt;&gt; from QuantLib import * &gt;&gt;&gt; maturity_date = Date(15, 1, 2016) &gt;&gt;&gt; spot_price = 127.62 &gt;&gt;&gt; strike_price = 130 &gt;&gt;&gt; volatility = 0.20 # the historical vols for a year &gt;&gt;&gt; dividend_rate = 0.0163 &gt;&gt;&gt; option_type = Option.Call &gt;&gt;&gt; risk_free_rate = 0.001 &gt;&gt;&gt; day_count = Actual365Fixed() &gt;&gt;&gt; calendar = UnitedStates() &gt;&gt;&gt; calculation_date = Date(8, 5, 2015) &gt;&gt;&gt; Settings.instance().evaluationDate = calculation_date &gt;&gt;&gt; payoff = PlainVanillaPayoff(option_type, strike_price) &gt;&gt;&gt; settlement = calculation_date &gt;&gt;&gt; am_exercise = AmericanExercise(settlement, maturity_date) &gt;&gt;&gt; american_option = VanillaOption(payoff, am_exerc…
accepted answer: http://stackoverflow.com/a/48546656
tagged with: python
has answer: http://stackoverflow.com/a/48546656

http://stackoverflow.com/q/48584427
tagged with: boost-python
has comment: http://stackoverflow.com/comment/84167873
has body: I have been working on a piece of new code within ESPResSo++ (http://www.espresso-pp.de/), a molecular dynamic (MD) simulation package. The code connects ESPResSo++ with PLUMED (https://plumed.github.io/), a plugin for MD packages. ESPResSo++ has extensive uses of boost-python library. The Python code loads a shared C++ library that does most of the computing, while providing an interface to users. The PLUMED library is called from the shared C++ library of ESPResSo++. PLUMED can be statically linked to ESPResSo++, or dynamically, or at runtime. When PLUMED is linked statically, I have had no issues. When ESPResSo++ is built with runtime linking of PLUMED, the undefined symbol error arises: +++ Loading the PLUMED kernel runtime +++ +++ PLUMED_KERNEL="/home/theorie/songbin/applications/src/plumed-2.4.0/src/lib/libplumedKernel.so" +++ +++ PLUMED kernel not found ! +++ +++ error message from dlopen(): /home/theorie/songbin/applications/src/plumed-2.4.0/src/lib/libplumedKernel.so: undefined symbol: plumed_cmd +++ ERROR: you are trying to use plumed, but it is not available +++ +++ Check your PLUMED_KERNEL environment variable +++ . I ran ldd -r libplumedKernel.so . Among the output is: undefined symbol: plumed_cmd (./libplumedKernel.so) undefined symbol: plumed_kernel_register (./libplumedKernel.so) undefined symbol: plumed_finalize (./libplumedKernel.so) undefined symbol: plumed_create (./libplumedKernel.so) . Then I ran nm _espressopp.so | grep plumed . I got 000000000275b8a0 T plumed_c2f 000000000275b660 T plumed_cmd 000000000275b5d0 T plumed_create 000000000275b450 T plumed_dummy_cmd 000000000275b430 T plumed_dummy_create 000000000275b440 T plumed_dummy_finalize 000000000275b900 T plumed_f2c 000000000275ba30 T plumed_f_cmd 000000000275bc20 T plumed_f_cmd_ 000000000275bc30 T plumed_f_cmd__ 000000000275ba10 T plumed_f_create 000000000275bbd0 T plumed_f_create_ 000000000275bbe0 T plumed_f_create__ 000000000275ba60 T plumed_f_finalize 000000000275bc70 T plumed_f_finaliz…
tagged with: python
has comment: http://stackoverflow.com/comment/84167828
has title: undefined symbols when loading C++ shared lib within a shared C++ lib, which itself is loaded by python
favorite count: 0
has comment: http://stackoverflow.com/comment/84169250
type: Question
tagged with: c++
has comment: http://stackoverflow.com/comment/84169688
has answer: http://stackoverflow.com/a/50747019
type: UnansweredQuestion
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86605991
has comment: http://stackoverflow.com/comment/84169863
has comment: http://stackoverflow.com/comment/86798587

http://stackoverflow.com/q/48589235
has answer: http://stackoverflow.com/a/48589390
type: Question
has body: Ok, so what I want to do is to calculate the power of given password.Each "cddd" gives 20 power, "cdd" 10 and "cd" 5. The thing is they can't overlap.So if we take string "cdddd", it will have 20 power instead of 35. My solution works but it's soooo ugly, I don't like it at all.It should be more general instead of matching only one specific dict:/ I just sort the dict so It starts with the longest substring, iterate over dict and then cut the substring out from the original password.I was wondering how else could I approach this. import re import collections def passwordCalculator(password): passwordPower = 0 initialDict = {"cddd": 20, "cdd": 10,"cd": 5} phrases = collections.OrderedDict(sorted(initialDict.items(), key=lambda t: len(t[0]), reverse=True)) for phrase in phrases.keys(): count = (len(re.findall(phrase, password))) passwordPower += phrases.get(phrase) * count password = str.replace(password, phrase, '') return passwordPower
has comment: http://stackoverflow.com/comment/84175726
accepted answer: http://stackoverflow.com/a/48589390
tagged with: python
has title: Python overlapping substrings
has comment: http://stackoverflow.com/comment/84175682
has comment: http://stackoverflow.com/comment/84175621
has answer: http://stackoverflow.com/a/48589517
possible better answer: http://stackoverflow.com/a/48589517
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48589974
answer count: 3

http://stackoverflow.com/a/51053916
score: 18
has comment: http://stackoverflow.com/comment/100343407
type: Answer
upvote count: 18
has body: You could try argmax like this: dataframe['name'].value_counts().argmax() Out[13]: 'alex' The value_counts will return a count object of pandas.core.series.Series and argmax could be used to achieve the key of max values.
answers question: http://stackoverflow.com/q/48590268
has comment: http://stackoverflow.com/comment/93364992
downvote count: 0

http://stackoverflow.com/comment/84068689
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48536834
has text: better look over here for request 1 i think: [https://stackoverflow.com/questions/44834/can-someone-explain-all-in-python](https://stackoverflow.com/questions/44834/can-someone-explain-all-in-python)
type: Comment

http://stackoverflow.com/comment/84087271
comment on: http://stackoverflow.com/q/48514315
score: 0
type: Comment
type: QuestionComment
has text: @caramel1995 thanks for that tip. I'm going to double check the whole app...

http://stackoverflow.com/q/48533200
downvote count: 0
favorite count: 0
has title: Python equivalent for poly(x, 2) adds an orthogonal polynomial of degree 2
tagged with: http://stackoverflow.com/tag/r
tagged with: statsmodels
has body: Here is the R code model1 &lt;- glm(wt82_71 ~ qsmk + sex + race + poly(age, 2, raw = TRUE) + education + poly(smokeintensity, 2, raw = TRUE) + poly(smokeyrs, 2, raw = TRUE) + exercise + active + poly(wt71, 2, raw = TRUE) + qsmk:smokeintensity,data = nhefs) In Python I wrote: mod3 = smf.glm(formula='qsmk ~ sex + race + education + exercise + active + poly(age,2) + poly(smokeintensity,2) + poly(smokeyrs,2) + poly(wt71,2)', family=sm.families.Binomial(), data=nhefs).fit() mod3.summary() What would poly() be in python? Here is some comments model 1: regression on covariates, allowing for some effect modification notes: (1) poly(x, 2) adds an orthogonal polynomial of degree 2, add the argument raw = TRUE if you want it to produce the same coefficients as would x + x^2 (2) x1*x2 enters the main effects of x1 and x2 and their product term x1:x2 enters just the product term (necessary here for smokeintensity because we want smokeintensity treated linearly in the interaction but quadratically in the main effect and thus a linear term for smokeintensity is not estimable) (3) observations with missing values are automatically deleted
has answer: http://stackoverflow.com/a/48534793
tagged with: python
has comment: http://stackoverflow.com/comment/84062218
score: 4
linked to: http://stackoverflow.com/q/31978948
type: Question
upvote count: 4
tagged with: glm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84062958
answer count: 1

http://stackoverflow.com/a/48639406
downvote count: 0
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/48616694
has comment: http://stackoverflow.com/comment/84317819
has comment: http://stackoverflow.com/comment/84310163
type: AcceptedAnswer
has body: (As it turned out that my previous answer does not really satisfy the constraints of the question, here's another one. I'm posting this as a separate answer, as the approach is vastly different and the original answer may still help others.) You can implement this recursively, each time before recursing to add another element to the combinations checking whether that would violate one of the exclude-sets. This does not generate and invalid combinations, and it works with overlapping exclude-sets (like (1,3), (1,5)), and exclude-sets with more than two elements (like (2,4,5), allowing any combinations except all of them together). def comb_with_excludes(lst, n, excludes, i=0, taken=()): if n == 0: yield taken # no more needed elif i &lt;= len(lst) - n: t2 = taken + (lst[i],) # add current element if not any(e.issubset(t2) for e in excludes): yield from comb_with_excludes(lst, n-1, excludes, i+1, t2) if i &lt; len(lst) - n: # skip current element yield from comb_with_excludes(lst, n, excludes, i+1, taken) Example: &gt;&gt;&gt; lst = [1, 2, 3, 4, 5, 6] &gt;&gt;&gt; excludes = [{1, 3}, {1, 5}, {2, 4, 5}] &gt;&gt;&gt; list(comb_with_excludes(lst, 4, excludes)) [[1, 2, 4, 6], [2, 3, 4, 6], [2, 3, 5, 6], [3, 4, 5, 6]] Well, I did time it now, and it turns out this is considerably slower than naively using itertools.combination in a generator expression with a filter, much like you already do: def comb_naive(lst, r, excludes): return (comb for comb in itertools.combinations(lst, r) if not any(e.issubset(comb) for e in excludes)) Calculating the combinations in Python is just slower than using the library (which is probably implemented in C) and filtering the results afterwards. Depending on the amount of combinations that can be excluded, this might be faster in some cases, but to be honest, I have my doubts. You could get better results if you can use itertools.combinations for subproblems, as in Kasramvd's answer, but for multiple, non-disjunct exclude sets that's more di…
has comment: http://stackoverflow.com/comment/84310376
upvote count: 4
answers question: http://stackoverflow.com/q/48616694

http://stackoverflow.com/q/48510488
has title: KeyError not caught
duplicate of: http://stackoverflow.com/q/6470428
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84015977
type: Question
has body: I am a little confused by an error I have. I have some code that should retrieve a json file from a database and search it for a substring, representing a code. As I understand it, my query will have a corresponding code and then everything goes well, or my query will not have a corresponding code, and then my code will trigger a KeyError. I have written a try/except block catching this (expected) KeyError, but the error is not caught. What am I missing here? Note: I just started dabbling with multiprocessing, is this related to that? Here is the concerned code: request_counter = 0 while request_counter &lt; 3: try: if ' - reduced' in metabolite: metabolite = 'reduced ' + metabolite[:-10] cts_output = requests.get( 'http://cts.fiehnlab.ucdavis.edu/' 'service/convert/Chemical%20Name/' 'KEGG/' + metabolite) kegg_id = str(json.loads(cts_output.text)[0]['result'][0]) metabolite_to_KEGG[bigg_id][kegg_id] = metabolite request_counter = 3 except KeyError and IndexError: if request_counter == 2: metabolite_no_KEGG[bigg_id].append(metabolite) request_counter = request_counter + 1 This block is within a couple for loops. Traceback: Traceback (most recent call last): File "/Users/dcoukos/anaconda/lib/python3.6/multiprocessing/pool.py", line 119, in worker result = (True, func(*args, **kwds)) File "GetKeggs.py", line 131, in getBrendaKeggs kegg_id = str(json.loads(cts_output.text)[0]['result'][0]) KeyError: 'result' """ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "GetKeggs.py", line 223, in brenda_keggs.update(bk1.get()) File "/Users/dcoukos/anaconda/lib/python3.6/multiprocessing/pool.py", line 644, in get raise self._value KeyError: 'result'
score: 0
tagged with: exception
has comment: http://stackoverflow.com/comment/84015999
tagged with: python
linked to: http://stackoverflow.com/q/6470428

http://stackoverflow.com/comment/84603740
type: Comment
comment on: http://stackoverflow.com/q/48626492
score: 0
type: QuestionComment
has text: If running a pythin file in the terminal please use the comnand "Python Run current file in terminal". Also Please ensure you have configured the Python interpreter, check the following documentation. https://code.visualstudio.com/docs/python/environments.

http://stackoverflow.com/comment/84166902
type: Comment
score: 0
type: AnswerComment
has text: yes, but you'd have to write your own `fillna` function.
comment on: http://stackoverflow.com/a/48585082

http://stackoverflow.com/comment/84217241
has text: For example it prints: command\xc5\xabcor
type: QuestionComment
comment on: http://stackoverflow.com/q/48610410
score: 0
type: Comment

http://stackoverflow.com/comment/84315241
type: AnswerComment
comment on: http://stackoverflow.com/a/48649672
score: 0
type: Comment
has text: Simply use `try`/`except` construction to check presence of select node

http://stackoverflow.com/q/48582506
tagged with: cluster-analysis
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/56676944
upvote count: 0
tagged with: memory-management
answer count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/84161447
tagged with: memory
has comment: http://stackoverflow.com/comment/84163613
has comment: http://stackoverflow.com/comment/84161522
has body: I have 1 million sentences. I am using Affinity Propagation algorithm to cluster similar sentence together. I am facing issue in processing such large data and getting Memory Error. Error: --------------------------------------------------------------------------- MemoryError Traceback (most recent call last) in () 72 # ] 73 ---> 74 clusters = get_clusters(sentences) 75 #print(clusters) 76 in get_clusters(sentences) 18 def get_clusters(sentences): 19 tf_idf_matrix = vectorizer.fit_transform(sentences) ---> 20 similarity_matrix = (tf_idf_matrix * tf_idf_matrix.T).A 21 affinity_propagation = AffinityPropagation(affinity="precomputed", damping=0.5) 22 affinity_propagation.fit(similarity_matrix) ~/.local/lib/python3.5/site-packages/scipy/sparse/base.py in getattr(self, attr) 562 def getattr(self, attr): 563 if attr == 'A': --> 564 return self.toarray() 565 elif attr == 'T': 566 return self.transpose() ~/.local/lib/python3.5/site-packages/scipy/sparse/compressed.py in toarray(self, order, out) 962 def toarray(self, order=None, out=None): 963 """See the docstring for spmatrix.toarray.""" --> 964 return self.tocoo(copy=False).toarray(order=order, out=out) 965 966 ############################################################## ~/.local/lib/python3.5/site-packages/scipy/sparse/coo.py in toarray(self, order, out) 250 def toarray(self, order=None, out=None): 251 """See the docstring for spmatrix.toarray.""" --> 252 B = self._process_toarray_args(order, out) 253 fortran = int(B.flags.f_contiguous) 254 if not fortran and not B.flags.c_contiguous: ~/.local/lib/python3.5/site-packages/scipy/sparse/base.py in _process_toarray_args(self, order, out) 1037 return out 1038 else: -> 1039 return np.zeros(self.shape, dtype=self.dtype, order=order) 1040 1041 def numpy_ufunc(self, func, method, pos, inputs, **kwargs): MemoryError: Code: import nltk, string from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import AffinityPropagation import pandas as pd from coll…
has title: MemoryError in sentence clustering in Python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48590700
type: UnansweredQuestion

http://stackoverflow.com/q/48585988
tagged with: python
has title: Django : Unable to run server
has comment: http://stackoverflow.com/comment/84176589
has comment: http://stackoverflow.com/comment/84173026
type: AnsweredQuestion
score: 0
has body: I am new to Django and this is the first project Im working on. I have an error while executing the runserver command. Im working with Python 3.6.4. I havent found a solution in previous posts which were already very few. This is the error I get : File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 2: invalid continuation byte PS : Please dont ask me to uninstall all and reinstall because I did it several times in vain.
answer count: 1
has comment: http://stackoverflow.com/comment/84169121
has comment: http://stackoverflow.com/comment/84177628
has comment: http://stackoverflow.com/comment/84169364
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48609914
has answer: http://stackoverflow.com/a/48609914
has comment: http://stackoverflow.com/comment/84189593
duplicate of: http://stackoverflow.com/q/23109244
tagged with: django

python
tags question: http://stackoverflow.com/q/48622638
tags question: http://stackoverflow.com/q/48555454
tags question: http://stackoverflow.com/q/48491143
tags question: http://stackoverflow.com/q/48641121
tags question: http://stackoverflow.com/q/48590884
tags question: http://stackoverflow.com/q/48574420
tags question: http://stackoverflow.com/q/48520816
tags question: http://stackoverflow.com/q/48622281
tags question: http://stackoverflow.com/q/48604058
tags question: http://stackoverflow.com/q/48632229
tags question: http://stackoverflow.com/q/48613671
tags question: http://stackoverflow.com/q/48605270
tags question: http://stackoverflow.com/q/48564743
tags question: http://stackoverflow.com/q/48503812
tags question: http://stackoverflow.com/q/48567617
tags question: http://stackoverflow.com/q/48572494
tags question: http://stackoverflow.com/q/48519049
tags question: http://stackoverflow.com/q/48579428
tags question: http://stackoverflow.com/q/48564122
tags question: http://stackoverflow.com/q/48612105
tags question: http://stackoverflow.com/q/48609625
tags question: http://stackoverflow.com/q/48517928
tags question: http://stackoverflow.com/q/48635046
tags question: http://stackoverflow.com/q/48541074
tags question: http://stackoverflow.com/q/48546347
tags question: http://stackoverflow.com/q/48630957
tags question: http://stackoverflow.com/q/48637960
tags question: http://stackoverflow.com/q/48642110
tags question: http://stackoverflow.com/q/48570320
tags question: http://stackoverflow.com/q/48603119
tags question: http://stackoverflow.com/q/48551460
tags question: http://stackoverflow.com/q/48536650
tags question: http://stackoverflow.com/q/48640698
tags question: http://stackoverflow.com/q/48513472
tags question: http://stackoverflow.com/q/48515539
tags question: http://stackoverflow.com/q/48618063
tags question: http://stackoverflow.com/q/48549766
tags question: http://stackoverflow.com/q/48593786
tags question: http://stackoverflow.com/q/48561644
tags question: http://stackoverflow.com/q/48616380
tags question: http://stackoverflow.com/q/48538945
tags question: http://stackoverflow.com/q/48602176
tags question: http://stackoverflow.com/q/48572965
tags question: http://stackoverflow.com/q/48632881
tags question: http://stackoverflow.com/q/48625618
tags question: http://stackoverflow.com/q/48553854
tags question: http://stackoverflow.com/q/48505727
tags question: http://stackoverflow.com/q/48615037
tags question: http://stackoverflow.com/q/48553179
tags question: http://stackoverflow.com/q/48628778
tags question: http://stackoverflow.com/q/48608297
tags question: http://stackoverflow.com/q/48519001
tags question: http://stackoverflow.com/q/48600583
tags question: http://stackoverflow.com/q/48489702
tags question: http://stackoverflow.com/q/48591664
tags question: http://stackoverflow.com/q/48518804
tags question: http://stackoverflow.com/q/48520103
tags question: http://stackoverflow.com/q/48554289
tags question: http://stackoverflow.com/q/48508036
tags question: http://stackoverflow.com/q/48489780
tags question: http://stackoverflow.com/q/48579190
tags question: http://stackoverflow.com/q/48601660
tags question: http://stackoverflow.com/q/48603190
tags question: http://stackoverflow.com/q/48551635
tags question: http://stackoverflow.com/q/48551574
tags question: http://stackoverflow.com/q/48556110
tags question: http://stackoverflow.com/q/48643192
tags question: http://stackoverflow.com/q/48554943
tags question: http://stackoverflow.com/q/48645730
tags question: http://stackoverflow.com/q/48500283
tags question: http://stackoverflow.com/q/48513714
tags question: http://stackoverflow.com/q/48552041
tags question: http://stackoverflow.com/q/48586647
tags question: http://stackoverflow.com/q/48501276
tags question: http://stackoverflow.com/q/48537039
tags question: http://stackoverflow.com/q/48576462
tags question: http://stackoverflow.com/q/48611167
tags question: http://stackoverflow.com/q/48589348
tags question: http://stackoverflow.com/q/48643360
tags question: http://stackoverflow.com/q/48497777

http://stackoverflow.com/comment/84145291
score: 0
comment on: http://stackoverflow.com/q/48574132
has text: insert code in the question
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48642335
type: Question
upvote count: 2
has body: I am using Google MAPS API in python: https://github.com/googlemaps/google-maps-services-python To get the information about a place I am using result = gmaps.places("restaurant",location=(lat,lng),radius = r) Now on changing the radius r to different values( I have tried for as low as 1) I always get 20 results. This is not possible, because you cannot have 20 restaurants in 1 m. Any fix for this? Thanks for help!
tagged with: google-places-api
tagged with: google-maps
type: UnansweredQuestion
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48642536
favorite count: 0
has title: Google Maps Places API radius parameter not working
score: 1
downvote count: 1

http://stackoverflow.com/comment/117184965
score: 0
comment on: http://stackoverflow.com/q/48630885
has text: @nttrung143 maybe [this](https://stackoverflow.com/q/66280861/1207193) might help
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48497201
possible better answer: http://stackoverflow.com/a/48497445
type: Question
score: -2
has comment: http://stackoverflow.com/comment/83987391
answer count: 4
has title: How to append list which is inside a dict?
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/48497445
downvote count: 2
tagged with: python
tagged with: dictionary
has body: I have a dictionary with entries like '0/RP0': ['NCS1K4-CNTLR']. For each entry I have to add another string to the value. For example, appending 'OPERATIONAL' results in '0/RP0': ['NCS1K4-CNTLR','OPERATIONAL']. I need to do this for the complete dictionary and have a list of values to append. I have two dictionaries below, new_dict = {'0/RP0': ['NCS1K4-CNTLR'], '0/PM1': ['NCS1K4-2KW-AC'], '0/PM0': ['NCS1K4-2KW-AC'], '0/FT2': ['NCS1K4-FAN'], '0/FT0': ['NCS1K4-FAN'], '0/FT1': ['NCS1K4-FAN']} new_dict_1= {'0/RP0': ['OPERATIONAL'], '0/PM1': ['OPERATIONAL'], '0/PM0': ['FAILED'], '0/FT2': ['OPERATIONAL'], '0/FT0': ['OPERATIONAL'], '0/FT1': ['OPERATIONAL']} I want output like below, {'0/RP0': ['NCS1K4-CNTLR','OPERATIONAL'], '0/PM1': ['NCS1K4-2KW-AC','OPERATIONAL'], '0/PM0': ['NCS1K4-2KW-AC','OPERATIONAL'], '0/FT2': ['NCS1K4-FAN','OPERATIONAL'], '0/FT0': ['NCS1K4-FAN','FAILED'], '0/FT1': ['NCS1K4-FAN','OPERATIONAL']}
has answer: http://stackoverflow.com/a/48497966
has answer: http://stackoverflow.com/a/48497353
accepted answer: http://stackoverflow.com/a/48497873
favorite count: 0
has comment: http://stackoverflow.com/comment/83987537
has comment: http://stackoverflow.com/comment/83987499
tagged with: list
has answer: http://stackoverflow.com/a/48497873

http://stackoverflow.com/q/48620963
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48622521
has comment: http://stackoverflow.com/comment/84242635
has answer: http://stackoverflow.com/a/48621821
type: UnansweredQuestion
tagged with: python
score: -1
has body: Importing Fraction from fractions to give a fractional representation of a real number, but giving responses quite complicated which seems very simple by the paper-pen method. Fractions(.2) giving answer 3602879701896397/18014398509481984, which is 0.20000000000000001110223024625157, almost .2, but I want it to be simply 1/5. I know there's limit() for this use, but what I simply required is smallest numerator and denominator which gives the exact real number bcoz I am dealing with a lot of numbers in a big range so i cant use same limit() argument for all.
linked to: http://stackoverflow.com/q/588004
has title: Fraction of a real number in python giving complicated answer
has comment: http://stackoverflow.com/comment/84244634
tagged with: fractions
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/128385155
downvote count: 2
has comment: http://stackoverflow.com/comment/84244250

http://stackoverflow.com/comment/83980109
comment on: http://stackoverflow.com/q/48493270
type: Comment
type: QuestionComment
has text: Okay. What does parse mean?
score: 0

http://stackoverflow.com/q/48534868
has body: Based on the tutorials of 'EVE-SQLAlchemy' I am able to setup a fully functional REST API which can setup a database based on a schema definition which used SQL alchemys database Models to generate the REST API schema. I am able to do CRUD operations on the resources. It's all good! Now, how do I add custom routes which can run queries or manipulate the database etc. Say I want to add additional functionalities and it is not straighforward resource queries and involves multiple SQL actions. How to achieve that? Sorry for not being very specific. Any general idea in that direction will be appreciated like some sort of guide or tutorial which can help understand the eve framework better. I want to stick to EVE's features while I add additional routes to it. Don't want to re-invent everything.
has answer: http://stackoverflow.com/a/48549047
accepted answer: http://stackoverflow.com/a/48549047
tagged with: flask-sqlalchemy
has title: How to write custom routes for python eve-sqlalchemy?
favorite count: 0
type: Question
score: 1
tagged with: python
tagged with: sqlalchemy
type: AnsweredQuestion
downvote count: 0
tagged with: eve
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/84105705
has text: One possible explanation is that you are running different versions of python in terminal and in pycharm.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48554693
score: 1

http://stackoverflow.com/q/48601660
tagged with: django-views
has title: ModuleNotFoundError: No module named 'myapp.views.hello'; 'myapp.views' is not a package
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84200028
has comment: http://stackoverflow.com/comment/84200177
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm using django 2.0.2 to develop a simple web app. I'm not sure what's wrong with my code. I'm getting the error ModuleNotFoundError: No module named 'myapp.views.hello'; 'myapp.views' is not a package Here is my code for views.py from django.shortcuts import render def hello(request): return render(request,'myapp/templates/hello.html',{}) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('myapp.views.hello'), name='hello'), ] Throwing the same error even when I did from myapp.views import * What is wrong with my code? Here's the tree structure DjProject/ ├── db.sqlite3 ├── DjProject │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── settings.cpython-36.pyc │ │ ├── urls.cpython-36.pyc │ │ └── wsgi.cpython-36.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── myapp ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── __init__.py │ └── __pycache__ ├── models.py ├── __pycache__ │ ├── admin.cpython-36.pyc │ ├── __init__.cpython-36.pyc │ ├── models.cpython-36.pyc │ └── views.cpython-36.pyc ├── templates │ └── hello.html ├── tests.py └── views.py 7 directories, 22 files
tagged with: django
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48601984
has comment: http://stackoverflow.com/comment/84200391
accepted answer: http://stackoverflow.com/a/48601984
tagged with: model-view-controller
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/84211857
comment on: http://stackoverflow.com/q/48607171
type: QuestionComment
score: 1
has text: There are definitely ways to do this. However your example shows no signs of work to solve the actual question, and smells like a homework problem you want solved for you. Please post the code of what you have done so far and ask for help where you go stuck.
type: Comment

http://stackoverflow.com/a/48554691
downvote count: 0
answers question: http://stackoverflow.com/q/48525455
score: 3
accepted answer of: http://stackoverflow.com/q/48525455
type: Answer
has comment: http://stackoverflow.com/comment/84114014
has comment: http://stackoverflow.com/comment/84135636
has body: https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-parallel-state.html I was just exploring this, and based off the example in the link above, the resulting array from the parallel task is ordered by the branch configuration order. The input to the step function is [ 3, 2 ] and the first defined branch of the parallel task adds the two numbers, and the second subtracts the two numbers. The output from the Parallel task is [ 5, 1 ], i.e. [ 3+2, 3-2 ], therefore ordering the results by branch configuration order.
upvote count: 3
type: AcceptedAnswer

key-bindings
tags question: http://stackoverflow.com/q/48578865
tag name: key-bindings
type: Tag

http://stackoverflow.com/a/48624532
downvote count: 0
has comment: http://stackoverflow.com/comment/84286946
score: 1
upvote count: 1
type: Answer
has body: I don't know if this is what you need. But if you want, you could use a function which tries to click until it succeeds or a timeout is reached. That way, you only need to call it and wait. import timeit from selenium import webdriver def safe_click(wd_elem, max_time=10): """ wd_elem should be a WebElement object, so it has the .click() method max_time defaults to 10 [seconds], and it's how long will the script try to click before it stops """ start = timeit.default_timer() while timeit.default_timer() - start &lt;= max_time: try: wd_elem.click() return except: pass print 'Max time reached; stopped trying' wd = webdriver.Chrome() wd.get('https://stackoverflow.com/questions/48624119/general-explicit-wait-selenium-python') elem_to_click = wd.find_element_by_xpath('//*[@id="question-header"]/h1/a') safe_click(elem_to_click) # Clicks it safe_click(None) # After 10 seconds, it gives up If you applied it, your code would be: safe_click(driver.find_element_by_xpath("x") # Leaving max_time equal to 10 seconds safe_click(driver.find_element_by_xpath("y", max_time=5) # Explicitly setting max_time to 5 seconds safe_click(driver.find_element_by_xpath("z", max_time=9999) # Explicitly setting max_time to 9999 seconds
answers question: http://stackoverflow.com/q/48624119

http://stackoverflow.com/comment/128385155
score: 0
has text: You will need to provide the input as a string (i.e. `Fraction('.2')`), as float values themselves suffer from the "brokenness" as pointed out by others, while `str` does not - [the documentation](https://docs.python.org/3/library/fractions.html) pointed this out and has various examples demonstrating this issue.
comment on: http://stackoverflow.com/q/48620963
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48507182
tagged with: python
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/366422
has answer: http://stackoverflow.com/a/48507235
possible better answer: http://stackoverflow.com/a/48507235
has comment: http://stackoverflow.com/comment/84008989
answer count: 2
has comment: http://stackoverflow.com/comment/84008936
upvote count: 2
duplicate of: http://stackoverflow.com/q/366422
linked to: http://stackoverflow.com/q/13087344
has body: I am trying to get new random name every time I call class. I am defining it as def namemethod(): return ''.join(random.choice(string.lowercase) for x in range(5)) class Test(object): def __init__(self, name=namemethod()): self.name = name And I am calling Test class via for loop to get new name but I keep getting same name, isn't it suppose to call init method and get new random name? for i in range(5): person = Test() print person.name Why person = Test() not calling namemethod everytime?
downvote count: 1
has title: python get new random name for every call of class
has comment: http://stackoverflow.com/comment/84008870
has answer: http://stackoverflow.com/a/48507208
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84009390
accepted answer: http://stackoverflow.com/a/48507208
tagged with: python-2.7
score: 1

http://stackoverflow.com/comment/84092570
score: 1
comment on: http://stackoverflow.com/q/48547753
type: Comment
type: QuestionComment
has text: Since `C` is created as a 2d array, the problem assignment is implicitly `C[1,:]=0`. That is you are trying to assign 0 to the 2nd row of `C`. Pay close attention to the wording of that error message. Why are you starting with shapes like (1,N) instead of (N,)? And remember that Python indexing starts with 0, not 1.

grpc
tags question: http://stackoverflow.com/q/48531943
type: Tag
tag name: grpc

http://stackoverflow.com/q/48583455
downvote count: 3
has comment: http://stackoverflow.com/comment/84165465
has answer: http://stackoverflow.com/a/48584569
linked to: http://stackoverflow.com/q/14705920
has answer: http://stackoverflow.com/a/48583886
possible better answer: http://stackoverflow.com/a/48583886
accepted answer: http://stackoverflow.com/a/48584569
has comment: http://stackoverflow.com/comment/84165219
type: Question
has comment: http://stackoverflow.com/comment/84165383
has title: How can I call a method from the C API where the number of arguments is known only at runtime?
answer count: 2
upvote count: 5
has comment: http://stackoverflow.com/comment/84165617
has comment: http://stackoverflow.com/comment/84165096
has comment: http://stackoverflow.com/comment/84165419
has comment: http://stackoverflow.com/comment/84165357
has body: I'm using the Python C API to call a method. At present I am using PyObject_CallMethodObjArgs to do this. This is a variadic function: PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL) This is absolutely fine when the number of arguments is known at compile time. However, I have a scenario where the number of arguments is not known until runtime, they are supplied as an array. In essence my issue is precisely the same as in this question: How can I pass an array as parameters to a vararg function? The accepted answer there tells me that there is no solution to my problem. Is there are way around this hurdle. If I cannot solve the problem using PyObject_CallMethodObjArgs is there an alternative function in the Python C API that can meet my needs? For instance, PyObject_Call accepts parameters as a Python sequence object. Is it possible to use this function, or one with a similar interface?
has comment: http://stackoverflow.com/comment/84165746
has comment: http://stackoverflow.com/comment/84165651
tagged with: python
has comment: http://stackoverflow.com/comment/84165594
has comment: http://stackoverflow.com/comment/84165533
favorite count: 0
has comment: http://stackoverflow.com/comment/84165727
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84165311
has comment: http://stackoverflow.com/comment/84165690

http://stackoverflow.com/a/48541455
answers question: http://stackoverflow.com/q/48541077
has body: In line 88 of your script you're trying to use attribute errno of RuntimeError instance but this exception class has no such attribute. Read documentation of exceptions before trying to handle them. Atrribute errno is defined only in OSError and classes inheriting from it. So apparently line 88 is part of try...except clause and in that line you're trying to use e.errno. You can't do that if the exception doesn't belong to OSError exceptions family.
has comment: http://stackoverflow.com/comment/84081931
has comment: http://stackoverflow.com/comment/84080569
type: Answer
has comment: http://stackoverflow.com/comment/84080905
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/84080775
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48541077
type: AcceptedAnswer

http://stackoverflow.com/a/48647444
answers question: http://stackoverflow.com/q/48645148
upvote count: 3
type: AcceptedAnswer
has body: Just don't try. Configuration files are used to provide configuration options, not executable code. Instead config.ini [db] driver = some_format table_nm = some_table and config = configparser.ConfigParser() config.read("config.ini") connection_sting = (sqlContext.read .format(config.get("db", "driver") .load(config.get("db", "table_nm"))) And in case when you need executable code use proper modules, not configuration.
accepted answer of: http://stackoverflow.com/q/48645148
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/q/48645730
tagged with: python
score: 2
tagged with: data-structures
has answer: http://stackoverflow.com/a/48645888
has answer: http://stackoverflow.com/a/48646047
possible better answer: http://stackoverflow.com/a/48645913
answer count: 4
has comment: http://stackoverflow.com/comment/84288980
tagged with: object
tagged with: list
has body: I have a list of objects with attributes qt, cons and consper and have to merge all the objects that have the same consper value. What is the best way to do that? The list is already sorted by consper. Example: With a list of objects of the class house: class house(): def __init__(self, qt, cons, consper): self.qt = qt self.cons = cons self.consper = consper Turn this list: l = [ house(2, 20, 10), house(3, 31, 10), house(6, 70, 11), house(2, 40, 20), house(1, 25, 25)] Into this list: l_new = [ house(5, 51, 10), house(6, 70, 11), house(2, 40, 20), house(1, 25, 25)] By adding the first two objects (because their attribute consper is equivalent)
linked to: http://stackoverflow.com/q/773
downvote count: 0
has comment: http://stackoverflow.com/comment/84288921
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48645913
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/48646197
has title: How to check for duplicate attributes in object list and merge them
accepted answer: http://stackoverflow.com/a/48646047

http://stackoverflow.com/q/48592296
has title: How does tensorflow ignore undefined flags
score: 8
type: AnsweredQuestion
tagged with: gunicorn
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48632331
has answer: http://stackoverflow.com/a/56272109
possible better answer: http://stackoverflow.com/a/56272109
tagged with: flask
tagged with: tensorflow
upvote count: 8
favorite count: 0
type: Question
has body: I'm wrapping my tensorflow model in a simple flask server and I'm adding gunicorn wsgi for the flask server. When I ran the gunicorn and tried to send a request to call my train function that has been import to the flask server, I got an error from command line arguments parsing: absl.flags._exceptions.UnrecognizedFlagError: Unknown command line flag 'b' I know this flags is passed when gunicorn bind the address arguments, because I have no flags named as 'b' for tensorflow. So my question is how does tensorflow ignore these undefined flags that the tf.app.run() function will not complain? FYI, Here is my server structure: wsgi.py: from simple_server import app if __name__ == "__main__": app.run() simple_server.py: from my_tf_model import my_train @app.route('/call_train', methods=['POST']) def call_train(): if request.method == 'POST': training_data = request.json my_train(training_data, param2) return('Trained!') my_tf_model.py: tf.app.flags.DEFINE_integer('model_version',1, 'version number of the model.') tf.app.flags.DEFINE_string('work_dir', '', 'Working directory.') FLAGS = tf.app.flags.FLAGS def my_train(param1, param2): # Train Algorithm export_path_base = FlAGS.work_dir # Exporting model code def main(argv): my_train(param1, param2) if __name__ == "__main__": tf.app.run() Update: I'm using tensorflow 1.5.x and python 3.6.0, the command that I used for gunicorn is: gunicorn -b 0.0.0.0:5000 -t 30 wsgi:app
accepted answer: http://stackoverflow.com/a/48632331
tagged with: python

http://stackoverflow.com/comment/83983676
comment on: http://stackoverflow.com/a/48494858
type: AnswerComment
has text: Hard to say without seeing your code., but I think all you need is `return values` in the `for` loop when you find them (instead of `break`), and at the end `else: return 'none found'`
score: 0
type: Comment

http://stackoverflow.com/comment/114151388
has text: @mkoistinen: Sure? But that's a problem with hashing in general, and kind of irrelevant to this answer. Hash randomization is intended to remove the ability to craft colliding hashes; disabling it allows you to find colliding strings just as easily as you found colliding `int`s. `hash` of an `int` is going to potentially collide whether or not you disable it.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48513133

http://stackoverflow.com/comment/84260662
has text: @AntiMatter is correct. Take a look at the [is-a vs has-a](https://stackoverflow.com/questions/2218937/has-a-is-a-terminology-in-object-oriented-language) distinction
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48621457

http://stackoverflow.com/comment/83979559
comment on: http://stackoverflow.com/q/48493129
score: 0
type: Comment
has text: If your mapping is injective but not bijective, then the reverse mapping is not defined for some "possible" values. So you are actually dealing with bijections right?
type: QuestionComment

excel
tags question: http://stackoverflow.com/q/48607116
tags question: http://stackoverflow.com/q/48597899
tags question: http://stackoverflow.com/q/48559356
tags question: http://stackoverflow.com/q/48551668
tags question: http://stackoverflow.com/q/48529664
tags question: http://stackoverflow.com/q/48554603
tags question: http://stackoverflow.com/q/48618586
tags question: http://stackoverflow.com/q/48574398
tag name: excel
tags question: http://stackoverflow.com/q/48527304
tags question: http://stackoverflow.com/q/48607583
tags question: http://stackoverflow.com/q/48569170
type: Tag
tags question: http://stackoverflow.com/q/48488660
tags question: http://stackoverflow.com/q/48537430
tags question: http://stackoverflow.com/q/48634071
tags question: http://stackoverflow.com/q/48519337
tags question: http://stackoverflow.com/q/48538244
tags question: http://stackoverflow.com/q/48589186
tags question: http://stackoverflow.com/q/48550960
tags question: http://stackoverflow.com/q/48513093
tags question: http://stackoverflow.com/q/48556211
tags question: http://stackoverflow.com/q/48587295
tags question: http://stackoverflow.com/q/48505116
tags question: http://stackoverflow.com/q/48512180
tags question: http://stackoverflow.com/q/48503568
tags question: http://stackoverflow.com/q/48638888
tags question: http://stackoverflow.com/q/48554923
tags question: http://stackoverflow.com/q/48593644
tags question: http://stackoverflow.com/q/48571326
tags question: http://stackoverflow.com/q/48575102
tags question: http://stackoverflow.com/q/48613158
tags question: http://stackoverflow.com/q/48558714
tags question: http://stackoverflow.com/q/48552061
tags question: http://stackoverflow.com/q/48544859
tags question: http://stackoverflow.com/q/48566406

sqlalchemy
tags question: http://stackoverflow.com/q/48492833
tags question: http://stackoverflow.com/q/48563367
tags question: http://stackoverflow.com/q/48590161
tags question: http://stackoverflow.com/q/48534125
tags question: http://stackoverflow.com/q/48534868
tags question: http://stackoverflow.com/q/48550653
tags question: http://stackoverflow.com/q/48491894
tags question: http://stackoverflow.com/q/48508088
tags question: http://stackoverflow.com/q/48559319
tags question: http://stackoverflow.com/q/48537626
tags question: http://stackoverflow.com/q/48612092
tags question: http://stackoverflow.com/q/48625776
tags question: http://stackoverflow.com/q/48586840
tags question: http://stackoverflow.com/q/48539765
tags question: http://stackoverflow.com/q/48615728
tags question: http://stackoverflow.com/q/48621588
tags question: http://stackoverflow.com/q/48511460
tags question: http://stackoverflow.com/q/48628493
tags question: http://stackoverflow.com/q/48519633
tags question: http://stackoverflow.com/q/48630925
tags question: http://stackoverflow.com/q/48621715
tags question: http://stackoverflow.com/q/48627425
tags question: http://stackoverflow.com/q/48616573
tags question: http://stackoverflow.com/q/48491178
tags question: http://stackoverflow.com/q/48589644
tags question: http://stackoverflow.com/q/48536340
tags question: http://stackoverflow.com/q/48633194
tags question: http://stackoverflow.com/q/48542822
tags question: http://stackoverflow.com/q/48642889
tags question: http://stackoverflow.com/q/48625715
tags question: http://stackoverflow.com/q/48625403
tags question: http://stackoverflow.com/q/48516379
tags question: http://stackoverflow.com/q/48519688
tags question: http://stackoverflow.com/q/48516893
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/48523469
tags question: http://stackoverflow.com/q/48592639
tags question: http://stackoverflow.com/q/48601123
type: Tag
tags question: http://stackoverflow.com/q/48609070
tags question: http://stackoverflow.com/q/48525626

http://stackoverflow.com/q/48614529
score: 1
has title: How to use the iterator 'make_initializable_iterator' of tensorflow within a 'input_fn'?
has answer: http://stackoverflow.com/a/57141944
tagged with: tensorflow
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: tensorflow-datasets
favorite count: 0
has body: I want to train my mode with a tf.estimator.Estimator and load my data by Dataset API.Because my data,for example 'mnist', is a array(tensor),so I try to load it with 'tf.data.Dataset.from_tensor_slices'.But I don't how to initialize 'make_initializable_iterator' within a 'input_fn'. If I can use 'make_one_shot_iterator' to train successfully, but it load slowly before training. And 《Higher-Level APIs in TensorFlow》is a good example to 'make_initializable_iterator' within a 'input_fn',but it needs to return a 'iterator_initializer_hook' to other function from 'input_fn' . I want to know is there any other better or more elegant way? def input_fn(): mnist_data = input_data.read_data_sets('mnist_data', one_hot=False) images = mnist_data.train.images.reshape([-1, 28, 28, 1]) labels = np.asarray(mnist_data.train.labels, dtype=np.int64) # Build dataset iterator dataset = tf.data.Dataset.from_tensor_slices((images, labels)) dataset = dataset.repeat(None) # Infinite iterations dataset = dataset.shuffle(buffer_size=10000) dataset = dataset.batch(100) iterator = dataset.make_one_shot_iterator() next_example = iterator.get_next() # Set runhook to initialize iterator return next_example
tagged with: tensorflow-estimator
has answer: http://stackoverflow.com/a/48628009

http://stackoverflow.com/q/48643160
has answer: http://stackoverflow.com/a/48644641
tagged with: python
accepted answer: http://stackoverflow.com/a/48644641
has comment: http://stackoverflow.com/comment/84285039
has comment: http://stackoverflow.com/comment/84285688
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84283196
has comment: http://stackoverflow.com/comment/84282888
tagged with: python-import
has title: Python 2.x vs 3.x imports, depending on where script is called/imported from
has body: This is likely the ~1000th question on import differences between Python 2.x and 3.x, but for my specific problem/case I am still stuck after reading most of them. Consider this simple example: Directory structure: main.py src/ thermo.py constants.py __init__.py # empty main.py: import src.thermo as thermo thermo.calc_thermo() src/thermo.py: from constants import cp def calc_thermo(): print(2*cp) if __name__ == '__main__': # Just for testing `thermo.py` calc_thermo() src/constants.py: cp = 1234. Now, there are two ways in which I want to use thermo.py; calling it directly from the src/ subdirectory (for debugging/unit-testing/.. of this specific file), or as part of the entire program by importing it into main.py. With the example above this all works in Python 2.7, in Python3.x I can call thermo.py from the src/ directory, but importing thermo from main.py fails on the import of constants. There are many similar questions here on SO, most suggesting to fix this with relative imports, i.e. changing thermo.py from: from constants import cp to from .constants import cp Now it works if I call main.py, but I lose the ability to call thermo.py directly from the src/ directory! How can this best be solved, i.e. creating the possibility to both import thermo.py from its parent directory (main.py), but also to keep the possibility to call thermo.py directly from src/?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/q/48582925
downvote count: 1
tagged with: scipy
has title: Fastest pairwise distance implementation python/c++
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84183107
has comment: http://stackoverflow.com/comment/84162171
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84163039
has answer: http://stackoverflow.com/a/77294112
has body: I am looking for the fastest implementation of pairwise distance between two sets of vectors (two 2D arrays) in c++/python. What have I done? I ran the code from here on my server. In python, I found that the pairwise distance function from scikit learn and cdist from scipy.special.distance have fastest pairwise distance implementation. Question: Calculating pairwise distance is the major bottleneck of my program. Thus, I wanted to know if one compute pairwise distance faster if coded purely in C++ (given that a most of the underlying code in scikit-learn, scipy is in C++ )?
tagged with: pairwise
tagged with: python
tagged with: c++
upvote count: 2
score: 1
answer count: 1
tagged with: scikit-learn

http://stackoverflow.com/q/48502286
has answer: http://stackoverflow.com/a/48502694
has title: Python access variable by two different files
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/48502459
tagged with: global-variables
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83998282
type: UnansweredQuestion
has body: Is it possible to read a variable from script a.py with a independently executed script b.py Example: a.py #!/usr/bin/env python3 import time i = 0 def run(): global i print(i) i = i+1 def get_i(): return i def main(): pass if __name__ == "__main__": while True: run() time.sleep(5) print("Stopped") b.py #!/usr/bin/env python3 import a print(a.get_i()) If b.py is executed it will print 0 but I want it to print the current state of i as set in a.py, so i has to be greater than 0. I tried already with an extra c.py where i is saved as global variable an then c.py is imported in a.py and b.py but it is the same behaviour: b.py prints the initial value of i and not the value which is set in a.py Notice: a.py is started before b.py and is still running because of the while loop and then b.py is executed.
tagged with: python
has comment: http://stackoverflow.com/comment/83998028
has comment: http://stackoverflow.com/comment/83998608
has comment: http://stackoverflow.com/comment/83998164

http://stackoverflow.com/a/48497712
has comment: http://stackoverflow.com/comment/83991442
type: Answer
has comment: http://stackoverflow.com/comment/83991645
has body: I think better is avoid loops, because slow. So for check columns by array use Series.isin: mask1 = c[0].isin(b) print (mask1 ) 0 True 1 False 2 True 3 False Name: 0, dtype: bool d1 = np.where(mask1, 'Great', 'sad') print (d1) ['Great' 'sad' 'Great' 'sad'] And for check all values use DataFrame.isin with any for check if at least one True per row in boolean DataFrame: mask2 = c.isin(b).any(axis=1) print (mask2) 0 True 1 True 2 True 3 True dtype: bool e1 = np.where(mask2, 'hola', 'False') print (e1) ['hola' 'hola' 'hola' 'hola'] Detail: print (c.isin(b)) 0 1 2 0 True True True 1 False False True 2 True False True 3 False False True If want check b in c use numpy.in1d with flatening values of DataFrame to 1d array by numpy.ravel: mask3 = np.in1d(b, c.values.ravel()) print (mask3) [ True False True True]
score: 2
has comment: http://stackoverflow.com/comment/83991248
has comment: http://stackoverflow.com/comment/83991512
upvote count: 2
has comment: http://stackoverflow.com/comment/83989805
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48497656
downvote count: 0
has comment: http://stackoverflow.com/comment/83991170
answers question: http://stackoverflow.com/q/48497656

http://stackoverflow.com/a/48568846
score: 0
has comment: http://stackoverflow.com/comment/84138767
has comment: http://stackoverflow.com/comment/84134312
answers question: http://stackoverflow.com/q/48568635
type: Answer
has body: I have no clue, but let's see :) import time import math n = 1000000 x = 5 def timeit(f): t_0 = time.perf_counter() for _ in range(n): f() t_1 = time.perf_counter() print((t_1 - t_0)/ n) def fun1(): round(10 * math.log(x) + 5) def fun2(): round(10 * math.log(x)) + 5 def fun3(): 10 * round(math.log(x)) + 5 [timeit(_) for _ in [fun1, fun2, fun3]] On my computer the last one is slightly faster than the others.
has comment: http://stackoverflow.com/comment/84134163
has comment: http://stackoverflow.com/comment/84137022
has comment: http://stackoverflow.com/comment/84134251

http://stackoverflow.com/a/48546106
type: Answer
has comment: http://stackoverflow.com/comment/84088439
score: 0
has comment: http://stackoverflow.com/comment/84092096
answers question: http://stackoverflow.com/q/48545726
has comment: http://stackoverflow.com/comment/84091900
has body: First step is, if you say the csv uses two commas instead of one, you should pass delimiter=',,' to np.loadtxt. Second, if you need to customize the parsing of each column, as Aaron said on his comment, you can pass convertersto customize the way the data will be stored. Example, if you want that column 2 gives a zero when it finds and empty string, you do import numpy as np data = np.loadtxt(name, delimiter=',,', converters = {2: lambda x: 0 if x == "" else float(x)} unpack=True, usecols=(0,1,6,7)) I didn't test the code, but I checked directly from documentation to think how could you do it. If that code doesn't work, it should be something like that anyway. Hope it helps.
has comment: http://stackoverflow.com/comment/84088655
has comment: http://stackoverflow.com/comment/84093563
has comment: http://stackoverflow.com/comment/84087902

http://stackoverflow.com/q/48525768
has answer: http://stackoverflow.com/a/48525838
accepted answer: http://stackoverflow.com/a/48525838
tagged with: python
score: 4
answer count: 4
has answer: http://stackoverflow.com/a/48529326
has title: How can I port this "one-line for loop" from Python to JavaScript?
type: Question
has comment: http://stackoverflow.com/comment/84046416
upvote count: 5
has body: I'm not sure about the terminology used (I think it's called "lambda" or something like that), so I cannot do a proper search. The following line in Python: a, b, c, d, e = [SomeFunc(x) for x in arr] How can I do the same in Javascript? I have this to begin with: let [a, b, c, d, e] = arr; But I still need to call SomeFunc on every element in arr.
downvote count: 1
has comment: http://stackoverflow.com/comment/84046468
tagged with: javascript
has comment: http://stackoverflow.com/comment/84047011
has answer: http://stackoverflow.com/a/48525857
favorite count: 0
linked to: http://stackoverflow.com/q/19851002
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48525835
has comment: http://stackoverflow.com/comment/84046495
has answer: http://stackoverflow.com/a/48525835

http://stackoverflow.com/q/48594447
answer count: 1
has answer: http://stackoverflow.com/a/48594685
linked to: http://stackoverflow.com/q/43971138
linked to: http://stackoverflow.com/q/17835302
type: Question
has body: For normal plots, matplotlib can use data, = plt.plot([], []) for i in range(n): data.set_data(i, i) and i can continuously update the plot. However I have a grid map which uses imshow instead of plot. plt.figure(1) cmap = colors.ListedColormap(['white', 'black']) bounds = [-0.5,0.5,1.5] norm = colors.BoundaryNorm(bounds, cmap.N) plt.show(block=False) for i in range(n): plt.imshow(data, cmap=cmap, norm=norm) plt.draw() imshow does not seem to have update method since it takes in the whole data. Is there a way I can plot a gridmap shown here with plt? Or is there a way I can update grid map using imshow?
duplicate of: http://stackoverflow.com/q/17835302
tagged with: python
tagged with: plot
type: AnsweredQuestion
score: 0
has title: How to update grid map in matplotlib
accepted answer: http://stackoverflow.com/a/48594685
linked to: http://stackoverflow.com/q/23042482
tagged with: matplotlib

http://stackoverflow.com/comment/84227760
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48605025
has text: still return Django default handler 'Server Error (500)'

http://stackoverflow.com/comment/84250034
has text: This works and is a really simple solution but I'm getting this as the output: 2016-10-17T15:00:40.739. Any reason there's a T in there?
type: Comment
comment on: http://stackoverflow.com/a/48625957
score: 0
type: AnswerComment

http://stackoverflow.com/a/48635963
has comment: http://stackoverflow.com/comment/84269070
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: If you want to work only with then list, create method you must have in it. Please check below example of my code. please check this link for more information http://www.django-rest-framework.org/api-guide/viewsets/ class UserViewSet(viewsets.ViewSet): def list(self, request): queryset = crm_models.EmployeeLeaveApp.objects.all() serializer = serializers.EmployeeVisitSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = crm_models.EmployeeLeaveApp.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = serializers.EmployeeVisitSerializer(user) return Response(serializer.data) def list(self, request): pass def create(self, request): pass def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass
answers question: http://stackoverflow.com/q/48635936

http://stackoverflow.com/a/48503746
accepted answer of: http://stackoverflow.com/q/48503703
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48503703
type: Answer
has body: I guess you're using python 2. Try this: float(correct)/total

http://stackoverflow.com/comment/107601001
type: QuestionComment
has text: It's a bug in PyCharm
type: Comment
comment on: http://stackoverflow.com/q/48619709
score: 1

http://stackoverflow.com/comment/83975248
has text: Do you have some other examples please?
comment on: http://stackoverflow.com/q/48488723
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84215811
type: AnswerComment
has text: I see what you did there ! I am still a rookie in Python, therefor I didn't really know about "Generators". I will try to learn more about those ! Thank You ! :-)
score: 0
comment on: http://stackoverflow.com/a/48609637
type: Comment

http://stackoverflow.com/comment/84231873
type: Comment
has text: I see I see. Thanks so much!!
type: AnswerComment
comment on: http://stackoverflow.com/a/48617302
score: 1

http://stackoverflow.com/comment/84135209
comment on: http://stackoverflow.com/q/48567676
type: Comment
has text: ...so, this is an effective duplicate of [NamedTemporaryFile appears empty even after data is written](https://stackoverflow.com/questions/46004774/python-namedtemporaryfile-appears-empty-even-after-data-is-written)
type: QuestionComment
score: 0

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

dataframe
tags question: http://stackoverflow.com/q/48614841
tags question: http://stackoverflow.com/q/48567015
tags question: http://stackoverflow.com/q/48601406
tags question: http://stackoverflow.com/q/48518306
tags question: http://stackoverflow.com/q/48508215
tags question: http://stackoverflow.com/q/48570269
tags question: http://stackoverflow.com/q/48562236
tags question: http://stackoverflow.com/q/48492451
tags question: http://stackoverflow.com/q/48511484
tags question: http://stackoverflow.com/q/48519553
tags question: http://stackoverflow.com/q/48616866
tags question: http://stackoverflow.com/q/48579251
tags question: http://stackoverflow.com/q/48538788
tags question: http://stackoverflow.com/q/48556872
tags question: http://stackoverflow.com/q/48587799
tags question: http://stackoverflow.com/q/48516180
tags question: http://stackoverflow.com/q/48564368
tags question: http://stackoverflow.com/q/48585708
tags question: http://stackoverflow.com/q/48524552
tags question: http://stackoverflow.com/q/48593893
tags question: http://stackoverflow.com/q/48587595
tags question: http://stackoverflow.com/q/48539344
tags question: http://stackoverflow.com/q/48566266
tags question: http://stackoverflow.com/q/48521710
tags question: http://stackoverflow.com/q/48490276
tags question: http://stackoverflow.com/q/48547818
tags question: http://stackoverflow.com/q/48629779
tags question: http://stackoverflow.com/q/48542920
tags question: http://stackoverflow.com/q/48640509
tags question: http://stackoverflow.com/q/48519337
tags question: http://stackoverflow.com/q/48516205
tags question: http://stackoverflow.com/q/48519252
tags question: http://stackoverflow.com/q/48533058
tags question: http://stackoverflow.com/q/48522775
tags question: http://stackoverflow.com/q/48595073
tags question: http://stackoverflow.com/q/48510455
tags question: http://stackoverflow.com/q/48491190
tags question: http://stackoverflow.com/q/48632639
tags question: http://stackoverflow.com/q/48580506
tags question: http://stackoverflow.com/q/48634528
tags question: http://stackoverflow.com/q/48495584
tags question: http://stackoverflow.com/q/48570130
tags question: http://stackoverflow.com/q/48592876
tags question: http://stackoverflow.com/q/48596061
tags question: http://stackoverflow.com/q/48598215
tags question: http://stackoverflow.com/q/48594977
tags question: http://stackoverflow.com/q/48542056
tags question: http://stackoverflow.com/q/48563101
tags question: http://stackoverflow.com/q/48568712
tags question: http://stackoverflow.com/q/48580789
tags question: http://stackoverflow.com/q/48493370
tags question: http://stackoverflow.com/q/48633016
tags question: http://stackoverflow.com/q/48621735
tags question: http://stackoverflow.com/q/48600308
tags question: http://stackoverflow.com/q/48568239
tags question: http://stackoverflow.com/q/48497656
tags question: http://stackoverflow.com/q/48596035
tags question: http://stackoverflow.com/q/48597958
tags question: http://stackoverflow.com/q/48505818
tags question: http://stackoverflow.com/q/48570021
tags question: http://stackoverflow.com/q/48623078
tags question: http://stackoverflow.com/q/48580235
tags question: http://stackoverflow.com/q/48630060
tags question: http://stackoverflow.com/q/48605898
tags question: http://stackoverflow.com/q/48616470
tags question: http://stackoverflow.com/q/48613671
tags question: http://stackoverflow.com/q/48572970
tags question: http://stackoverflow.com/q/48535239
tags question: http://stackoverflow.com/q/48524362
tags question: http://stackoverflow.com/q/48512352
tags question: http://stackoverflow.com/q/48515037
tags question: http://stackoverflow.com/q/48553978
tags question: http://stackoverflow.com/q/48574444
tags question: http://stackoverflow.com/q/48585073
tags question: http://stackoverflow.com/q/48570481
tags question: http://stackoverflow.com/q/48605016
tags question: http://stackoverflow.com/q/48638220
tags question: http://stackoverflow.com/q/48559995
tags question: http://stackoverflow.com/q/48503953
tags question: http://stackoverflow.com/q/48500534

http://stackoverflow.com/comment/84192270
has text: This would be a much better answer if it included some more information about the complexity, being O(n²), and what that means for larger (not just "huge") lists. Agreed that for the given example this is perfectly fine and much simpler than using `set`, though.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48596876

http://stackoverflow.com/a/48516543
has comment: http://stackoverflow.com/comment/84029125
score: 0
has comment: http://stackoverflow.com/comment/84029199
answers question: http://stackoverflow.com/q/48514844
type: Answer
has body: The problem is in the queryset you have done! how can exist something that have startdate greater then datetime.now and enddate minor then datetime.now? try invert gte and lte! honor = HonorKegiatan.objects.filter( startdate__lte=datetime.datetime.now(), enddate__gte=datetime.datetime.now() ).values_list('honor',flat=True)

http://stackoverflow.com/comment/84091381
comment on: http://stackoverflow.com/q/48547743
type: Comment
has text: File a bug on https://developers.facebook.com/bugs because that page is wrong.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84080165
has text: @tim, a possible solution is out-of-core processing, so RAM is not a limiting factor. While your data is currently stored in dictionaries, you may have to refactor to have your data in one large array. In this situation, HDF5 is a very good choice and is supported well by python (h5py and pyTables libraries).
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48542185

http://stackoverflow.com/comment/84030173
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48517177
has text: Yes replace `('N')` with `('N', )` to fix that
type: Comment

http://stackoverflow.com/comment/84065123
type: Comment
comment on: http://stackoverflow.com/a/48534077
score: 0
type: AnswerComment
has text: @MichaelHolborn - You want `while` to continue indefinitely, so `while True` just repeats. Then every 10 seconds the `if` is satisfied. Just copied `time.time()` from your code :-D. But check the docs: https://docs.python.org/3/library/time.html. "Return the time in seconds since the epoch as a floating point number." Also added one more edit to the answer that reduces the looping (so as to not peg your CPU).

http://stackoverflow.com/a/48548516
has comment: http://stackoverflow.com/comment/84093479
score: 1
has comment: http://stackoverflow.com/comment/84093873
answers question: http://stackoverflow.com/q/48548372
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84093815
has comment: http://stackoverflow.com/comment/84094114
type: Answer
has body: Use csv.DictReader() and dictionary.setdefault(). Code: csvf = csv.DictReader(open("test.csv","r")) d = {} for row in csvf: for header, item in row.items(): d.setdefault(header, []).append(item) Output: {'firstName': ['alice', 'mark', 'bob', 'Chelsea', 'chester'], 'lastName': ['sparks', 'peters', 'stones', '', ''], 'skill': ['artist', 'sports', 'teacher', '', 'sports']} DictReader() returns an array of OrderedDictionarys in the forms of (header, row[i]), which is the perfect preface for your use case. All you needed was a Dcitionary with default item type list and append to the list as you iterate through each row.

http://stackoverflow.com/comment/83973135
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48489669
type: QuestionComment
has text: Can you provide the full code of your model ?

http://stackoverflow.com/comment/84085249
has text: I don't use to install libraries downloading the file, always apt-get. I will check and return.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48544877
type: Comment

http://stackoverflow.com/comment/84066570
has text: Hi sda11, I have tried many bash tools unsuccessfully. I will show what I have done, unsuccessfully with pandas.
score: 0
comment on: http://stackoverflow.com/q/48535282
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84284712
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48643925
score: 0
has text: I would keep the first and re-write the second as `return sum(len(t) > 6 for t in tokens) / nro_tokens`

http://stackoverflow.com/comment/84057243
type: QuestionComment
has text: @tristansokol I know. It uses the RetrieveCustomer from the V2 API to get user data for the ID... not the best implementation. and I will be fixing that.
comment on: http://stackoverflow.com/q/48529593
score: 0
type: Comment

rounding
tags question: http://stackoverflow.com/q/48572081
tags question: http://stackoverflow.com/q/48568635
tags question: http://stackoverflow.com/q/48638398
tag name: rounding
tags question: http://stackoverflow.com/q/48638805
type: Tag

xvfb
type: Tag
tag name: xvfb
tags question: http://stackoverflow.com/q/48577341

http://stackoverflow.com/comment/84286066
comment on: http://stackoverflow.com/q/48644605
score: 0
type: Comment
type: QuestionComment
has text: define label? hello -> labelhello? label, hello? label-hello? [(label, hello)]?

http://stackoverflow.com/q/48507546
has body: I am currently working on a churn management problem with a binary classification. I am getting an error when I am fitting the model. There seems to be something in the input/output that is throwing this off that I haven't been able to catch. Here is the code (df contains my data frame which I am creating vectors from): #Delete unimportant columns. del df['RowNumber'] del df['CustomerId'] del df['Surname'] Then, I have to convert two categorical variables: #Converting and creating dummy variables for categorical variables df["Gender"] = df["Gender"].astype('category') df["Geography"] = df["Geography"].astype('category') df['Gender'] = pd.get_dummies(df['Gender']) df['Geography'] = pd.get_dummies(df['Geography']) y = df.iloc[:, -1] #Label variable X = df.iloc[:, :10] #Features Splitting dataset into test and training: # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2) Next, I am scaling the variables: from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) print(X_train.shape) #(8000, 10) print(X_test.shape) #(2000, 10) print(y_train.shape)#(8000,) print(y_test.shape)#(2000,) Building Network: model = models.Sequential() model.add(layers.Dense(32, activation='relu', input_shape=(8000,))) model.add(layers.Dense(1, activation='sigmoid')) # Compiling Neural Network model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) #Fitting our model model.fit(X_train, y_train, batch_size = 10, epochs = 10) # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred &gt; 0.5) # Creating the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) The specific error code that I am getting is: ValueError: Error when checking input: expected dense_47_input to have shape (…
has answer: http://stackoverflow.com/a/48507789
accepted answer: http://stackoverflow.com/a/48507789
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
type: Question
has title: Input and output dimension error in Keras
has comment: http://stackoverflow.com/comment/84010975
upvote count: 2
tagged with: machine-learning
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/84090782
type: Comment
type: QuestionComment
score: 2
has text: It is better show u the df1 and df2 and your expected output
comment on: http://stackoverflow.com/q/48546871

http://stackoverflow.com/comment/84180872
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48591757
has text: You're trying to test the next character. If the current character is the last character, there is no next character, what do you expect to happen?

http://stackoverflow.com/q/48550689
type: Question
upvote count: 2
tagged with: python-3.x
tagged with: homebrew
has title: pip not working after installing python3 on Mac
tagged with: pip
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/84097985
has body: I installed python3 from the official website and then installed jupyter notebook. While trying to run jupyter notebook, I was getting a "command not found" error. I found this github issue and followed the instructions to delete python3 and reinstall using Homebrew instead (I've used Homebrew before). When trying python3 -m pip install --upgrade pip i get a "No module named pip" error. My /usr/local/bin/ file shows pip, pip2, pip2.7, pip3, pip3.6. I have a feeling my pip is not associated with the python3 that I installed using Homebrew. How can I fix this?
downvote count: 0
has comment: http://stackoverflow.com/comment/84097421
answer count: 1
has answer: http://stackoverflow.com/a/48550868
accepted answer: http://stackoverflow.com/a/48550868
favorite count: 0

http://stackoverflow.com/q/48543815
score: -1
has title: Eulers method- velocity and position as a function of time for runner
has body: Acceleration in a given point is given by a=5-0.004364*v^2 I want to store all the values of v and x and a in lists so that I later can plot them as a function of time. Keep in mind I'm a beginner. This is my code so far: x_val=0 x=[] x.append(x_val) v_val=0 v=[] v.append(v_val) a_val=5.0 a=[] a.append(a_val) h=0.1 while x_val &lt;=100: v_val += (a_val*h) x_val += (v_val*h) a_val=(5-0.004364*(v_val**2) a.append(a_val) v.append(v_val) x.append(x_val) I'm getting a syntax error on "a.append(a_val)": invalid syntax What am I doing wrong here? Please help
upvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48543898
downvote count: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/a/48544304
has comment: http://stackoverflow.com/comment/84084399
has comment: http://stackoverflow.com/comment/84084535
has comment: http://stackoverflow.com/comment/84084151
has comment: http://stackoverflow.com/comment/84087158
has comment: http://stackoverflow.com/comment/84084473
type: Answer
has body: Items from queryset in ListView are available as object_list in the template, so you need to do something like: {% for product in object_list %} {{ product.name }} Cooked with chicken and mutton cumin spices £ {{ product.price }} {% endfor %} You can find details in the ListView documentation. Note a method called get_context_data - it returns a dictionary of variables and values, that will be passed to templates. You can always find why it works in this way in the source code.
answers question: http://stackoverflow.com/q/48544128
has comment: http://stackoverflow.com/comment/84084212
upvote count: 4
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/84084754

http://stackoverflow.com/q/48530626
linked to: http://stackoverflow.com/q/6791198
downvote count: 0
has comment: http://stackoverflow.com/comment/84057081
tagged with: python
tagged with: montecarlo
has comment: http://stackoverflow.com/comment/84057189
linked to: http://stackoverflow.com/q/291978
has title: Function not defined after declaration in python3
has comment: http://stackoverflow.com/comment/84057195
has comment: http://stackoverflow.com/comment/84056842
has comment: http://stackoverflow.com/comment/84057266
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84057233
upvote count: 1
has body: Using python 3: I have three functions: montePi, isInCircle and main. I need to have the isInCircle called by montePi. The function will work, it just says that isInCircle is not defined. How can I define it? import random import math def montePi(numDarts): inCircle = 0 def isInCircle(x, y, r): r = 1 d = math.sqrt(x**2 + y**2) if d &lt;= r: return True else: return False for i in range(numDarts): x = random.random() y = random.random() d = math.sqrt(x**2 + y**2) if d &lt;= 1: inCircle = inCircle +1 pi = inCircle / numDarts * 4 return pi def main(): print(montePi(100)) print(montePi(1000)) print(montePi(10000)) print(montePi(100000)) main()
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48530821
has comment: http://stackoverflow.com/comment/84056847
type: UnansweredQuestion

http://stackoverflow.com/comment/84067335
comment on: http://stackoverflow.com/a/48536000
score: 0
type: AnswerComment
has text: Have you made a simple estimation of the memory you need?
type: Comment

http://stackoverflow.com/a/48513483
accepted answer of: http://stackoverflow.com/q/48513263
has comment: http://stackoverflow.com/comment/84022302
has comment: http://stackoverflow.com/comment/84021803
type: Answer
has body: Your query needs to be like this: param = { "query": { "bool": { "filter": { "geo_distance": { "distance": distance, "distance_type": "plane", "location": { "lat": lat, "lon": lon } } }, "must": [ { "match": { "start_time": start_time } }, { "match": { "end_time": end_time } } ] } } }
answers question: http://stackoverflow.com/q/48513263
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48604370
downvote count: 0
tagged with: concatenation
answer count: 3
possible better answer: http://stackoverflow.com/a/48604437
has comment: http://stackoverflow.com/comment/84205369
upvote count: 8
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48604437
has title: Concatenate matrices/vectors in Python like in MATLAB?
has comment: http://stackoverflow.com/comment/84205477
tagged with: python
tagged with: linear-algebra
has answer: http://stackoverflow.com/a/48604520
accepted answer: http://stackoverflow.com/a/48604520
has answer: http://stackoverflow.com/a/48604511
has body: Let A, x, y and z be some vectors or matrices of appropriate size. Then in MATLAB one can build a "super matrix" B out of them very easily: A = [1 2;3 4]; x = [4;5]; y = [1 2]; z = 4; B = [A x;y z]; The output is: &gt;&gt; B B = 1 2 4 3 4 5 1 2 4 What is the best way to achieve the same effect in NumPy?
tagged with: matlab
score: 8
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/comment/84108833
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48556290
has text: @dangonfast: I've added a delegation example.

http://stackoverflow.com/q/48572552
type: Question
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48573203
has answer: http://stackoverflow.com/a/48572688
tagged with: search
has body: Regarding calculation of the list mid-point: why is there i = (first +last) //2 and last is initialized to len(a_list) - 1? From my quick tests, this algorithm without -1 works correctly. def binary_search(a_list, item): """Performs iterative binary search to find the position of an integer in a given, sorted, list. a_list -- sorted list of integers item -- integer you are searching for the position of """ first = 0 last = len(a_list) - 1 while first &lt;= last: i = (first + last) / 2 if a_list[i] == item: return '{item} found at position {i}'.format(item=item, i=i) elif a_list[i] &gt; item: last = i - 1 elif a_list[i] &lt; item: first = i + 1 else: return '{item} not found in the list'.format(item=item)
score: 0
answer count: 2
has title: Binary search: weird middle point calculation

http://stackoverflow.com/comment/83996700
has text: Yeah I just realised. It's not necessary to know the number of timesteps. Anyways, your solution seems better than mine. Still I'm surprised, that it is necessary to rebuild the model instead of changing a single attribute.
type: Comment
comment on: http://stackoverflow.com/a/48501518
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84109620
has text: I am eventually trying to go for an image that is saved locally. The api reference states that locally saved images need to be converted to binary and then uploaded in the manner that I stated before. I am sorry if I didnt state that before. I was just trying the conversion for a url image before trying to convert a locally saved image.
comment on: http://stackoverflow.com/a/48556699
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48563851
upvote count: 5
type: Answer
has body: You can use a list comprehension and tuple unpacking. a = 1 b = 2 c = 3 a, b, c = [i * 2 for i in [a, b, c]] print(a, b, c) # 2 4 6
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/84127560
answers question: http://stackoverflow.com/q/48563600

http://stackoverflow.com/comment/84262858
has text: This appears to be the best answer. I'd like to clarify though, these lambdas would not actually be evaluated at all until I would call mapper['Big Sequence'], correct?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48630825
type: AnswerComment

http://stackoverflow.com/q/48643220
has comment: http://stackoverflow.com/comment/84288581
favorite count: 0
type: Question
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/48648883
tagged with: bioinformatics
downvote count: 0
tagged with: blast
has title: Finding the best reciprocal hit in a single BLAST file using python
has body: I have a BLAST outfmt 6 output file in standard format, I want to find a way to loop through the file, select each hit, find its reciprocal hit and decipher which is the best hit to store. For example: d = {} for line in input_file: term = line.split('\t') qseqid = term[0] sseqid = term[1] hit = qseqid, sseqid recip_hit = sseqid, qseqid for line in input_file: if recip_hit in line: compare both lines done Example input (tab delimited): Seq1 Seq2 80 1000 10 3 1 1000 100 1100 0.0 500 Seq2 Seq1 95 1000 10 3 100 1100 1 1000 1e-100 500 Can anyone provide any insight how to efficiently tackle this problem? Many thanks in advance
has comment: http://stackoverflow.com/comment/84287924
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48648883
has comment: http://stackoverflow.com/comment/84287214
has comment: http://stackoverflow.com/comment/84285906
answer count: 1
has comment: http://stackoverflow.com/comment/84287148
tagged with: python

http://stackoverflow.com/comment/84266124
comment on: http://stackoverflow.com/q/48634579
type: Comment
type: QuestionComment
score: 3
has text: You print your contents _many times_. Each loop iteration prints all previously collected tokens. Move `print(tokens)` out of the loop by unindenting it.

http://stackoverflow.com/a/48634124
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48633949
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48633949
score: 2
type: AcceptedAnswer
has body: What you could do to save a lot of time is convert UserCity to lower case so you don't have to check every possible combination of cease. This can easily be done as Joran Beasley said by: while UserCity.lower() != "cease": and for the other if statement it can be done by: if UserCity.lower() != "cease":

http://stackoverflow.com/a/48601633
score: 12
upvote count: 12
answers question: http://stackoverflow.com/q/48601175
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48601175
has body: First of all, there is no problem of supplying a hex color string to color argument of a seaborn barplot, e.g. sns.barplot("A", "B", data=df, color="#4C72B0") works fine. But it colorizes all barplots in the same color. Hence you would want to use a palette. If you want to use the colors of an existing palette it is probably useful to start with exactly that palette and repeat it the number of times desired. col = np.repeat(np.array(sns.color_palette("deep")),2,axis=0) sns.barplot(..., palette=col) Here we repeat it twice. Complete example: import numpy as np import seaborn as sns import pandas as pd import matplotlib.pyplot as plt palette = np.repeat(np.array(sns.color_palette("deep")),2,axis=0) n = 6 df = pd.DataFrame({"A":np.arange(n), "B":np.random.rand(n)}) sns.barplot("A", "B", data=df, palette=palette) plt.show() In case you don't want to use an existing palette, you may also use your custom list of hex color strings to create one, palette = sns.color_palette(["#4c72b0","#4c72b0","#55a868","#55a868","#c44e52","#c44e52"]) This would result in the same plot as above. (Note that seaborn by default desaturates the colors. The colors of the bars are hence not exactly the colors from the palette; to change this behaviour one needs to set saturation=1 in the barplot call.)
type: Answer

http://stackoverflow.com/q/48539140
linked to: http://stackoverflow.com/q/9535954
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48539445
score: 0
has comment: http://stackoverflow.com/comment/84073781
tagged with: list
answer count: 2
tagged with: email
accepted answer: http://stackoverflow.com/a/48551641
has title: python adding spaces in email body between lists of lists
has answer: http://stackoverflow.com/a/48551641
type: Question
has comment: http://stackoverflow.com/comment/84073378
has comment: http://stackoverflow.com/comment/84073415
tagged with: python
possible better answer: http://stackoverflow.com/a/48539445
has body: Assuming I have the following list: ListofLists = [2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13] I want to add the list of lists to the body of a email, something like that: body = "Here are the informations" + ListofLists I would like to seperate the two lists and print the lists each in a seperate line, so it looks like a table, how could I do that? What I want as an Output is the following: Number 1 Number 2 Number 3 Number 4 Number 5 2 3 4 5 6 8 9 10 11 11

http://stackoverflow.com/q/48496634
type: Question
has answer: http://stackoverflow.com/a/48497557
tagged with: nginx
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: multithreading
answer count: 1
has comment: http://stackoverflow.com/comment/83986352
tagged with: python
tagged with: flask
has title: Degraded performance using python's 'threading' on a Nginx server comparing to a local machine
score: 0
has body: I've built a Flask application, that computes some paths in a graph. Usually, it's a very greedy task and it takes a lot of time to finish calculations. While I was busy with configuring algorithm, I didn't really pay attention to the server side implementations. We've set up an Nginx server, that servers that whole thing. Here's main Flask route: @app.route('/paths', methods=['POST']) def paths(): form = SampleForm(request.form) if form.validate_on_submit(): point_a = form.point_a.data point_b = form.point_b.data start = form.start.data.strftime('%Y%m%d') end = form.end.data.strftime('%Y%m%d') hops = form.hops.data rendering_time, collections = make_collection(point_a, point_b, start, end, hops) return render_template( 'result.html', searching_time=rendering_time, collections=collections) else: logger.warning('Bad form: {}'.format(form.errors)) return render_template('index.html', form=form) The whole calculation thing lies under make_collection method. So, whenever user sends request to the server.com/path, he will have to wait, until the method completes calculations and returns something. This is not a pleasing solution, sometimes Nginx just goes timeout. The next version of this was with a simple idea of delegating labor work to some thread and just returning an empty page to the user. Later on we can just update page contents with the latest searhing results. @app.route('/paths', methods=['POST']) def paths(): form = SampleForm(request.form) if form.validate_on_submit(): point_a = form.point_a.data point_b= form.point_b.data start = form.start.data.strftime('%Y%m%d') end = form.end.data.strftime('%Y%m%d') hops = form.hops.data finder = threading.Thread( target=make_collection, kwargs={ 'point_a': point_a, 'point_b': point_b, 'start': start, 'end': end, 'hops': hops}) finder.start() rendering_time, collections = 0, [] return render_template( 'result.html', searching_time=rendering_time collections=collections) else: logger.warning('Bad form: {}'.format(form.err…
has comment: http://stackoverflow.com/comment/83986461

http://stackoverflow.com/a/48498753
type: Answer
answers question: http://stackoverflow.com/q/48494796
has body: Your Code is correct, You are blacklisted. you should use the techniques for preventing this, like How to prevent getting blacklisted while scraping Amazon
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/a/48538519
score: 0
has body: This code solved my problem, I used new instead of create @api.onchange('fixed_amount') def automate_creation(self): terms = self.line_ids.browse([]) self.number_of_slices = (self.how_much/self.fixed_amount) days = 30 i = 0 while i&lt;self.number_of_slices: terms+=terms.new({'value': 'fixed', 'value_amount':self.fixed_amount, 'days':days, 'option':'day_after_invoice_date', 'payment_id':self._origin.id}) self.line_ids = terms
type: Answer
answers question: http://stackoverflow.com/q/48519768

http://stackoverflow.com/a/48516678
answers question: http://stackoverflow.com/q/48516211
has body: I decided to just make the text sit on top of a transparent overlay as seen below: overlay_image = np.copy(image_in) cv2.rectangle(img=overlay_image, pt1=(center[0] + 50, center[1] - 50), pt2=(center[0] + 350, center[1] + 50), color=[0, 0, 0], thickness=-1) cv2.putText(img=overlay_image, text=traffic_light_state, org=(center[0] + 50, center[1] + 10), fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=1, color=[255, 255, 255], thickness=1) cv2.addWeighted(src1=overlay_image, alpha=0.5, src2=image_in, beta=0.5, gamma=0, dst=image_in)
score: 0
type: Answer

http://stackoverflow.com/q/48571555
type: Question
has comment: http://stackoverflow.com/comment/84139872
has comment: http://stackoverflow.com/comment/84139849
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84139893
has title: Find duplicate lines
downvote count: 3
has comment: http://stackoverflow.com/comment/84139935
tagged with: python
accepted answer: http://stackoverflow.com/a/48571595
linked to: http://stackoverflow.com/q/19764655
has comment: http://stackoverflow.com/comment/84139863
has answer: http://stackoverflow.com/a/48571595
tagged with: uniq
duplicate of: http://stackoverflow.com/q/19764655
score: -2
answer count: 1
has body: considering this file: cat 1.txt 1 Red 1 Red 2 Red 2 Green 2 Green 4 Blu 5 Black 5 Black 5 Yellow 5 Pink 11 Brown 15 Brown 16 White and this command cat file.txt | sort | uniq -c how could I do the same thing with python?
has comment: http://stackoverflow.com/comment/84140015
upvote count: 1
tagged with: sorting
favorite count: 0

http://stackoverflow.com/a/48530535
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: It's hard to tell what exactly are you doing wrong without seeing the input file itself, but what seems to be wrong here (besides the fact that your values in a file seem to be comma-separated and that you might have been better off using Python stdlib's csv module) is that you're encountering a string somewhere when iterating over the lines, and are trying to convert that to float which is a no go: &gt;&gt;&gt; float('spam') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: could not convert string to float: 'spam' One of the solutions would be to simply skip the strings you're encountering, and you can choose between two approaches there (LBYL (Look Before You Leap) vs EAFP (Easier to Ask for Forgiveness than Permission)), and, in a nutshell, I suggest you go with the latter since it's generally preferred due to the gap that exists between checking and using, which means that things can change out from under you, and oftentimes you'll have to handle the error in any case, even if you check first. Apart from that, instead of manually closing file-like objects later on (which you seem to have forgotten to do), I suggest using with statement as a context manager which automatically manages that for you. So, taking all that into account, something along the following lines should do the trick (disclaimer: not thoroughly tested): import csv data = [] filename = input('Enter the name of the data file: ') with open(filename) as f: reader = csv.reader(f, delimiter=',', skipinitialspace=True) for line in reader: try: date, (l, h, rf) = line[0], map(float, line[1:]) m, d, y = map(int, date.split('/')) except ValueError as e: print('Skipping line: %s [because of: %s]' % (line, e)) continue data.append([d, m, y, l, h, rf]) Hopefully this is enough to get you back on track ;-)
type: Answer
accepted answer of: http://stackoverflow.com/q/48528775
answers question: http://stackoverflow.com/q/48528775

http://stackoverflow.com/comment/84015807
score: 0
type: Comment
type: AnswerComment
has text: Thanks wim, I get it at first time, that setting `MyLogger` is issue, but I cant change it easily, I have plan to change that, but before that, I have make my test running. Is there any way to do this ?
comment on: http://stackoverflow.com/a/48510145

http://stackoverflow.com/q/48490647
has body: I tried to make a cron job on crontab which runs a python script on AWS ec2. My python script includes a module that is only available for python3. Using the following command I changed the ec2 default python interpreter from python2.7 to python3.4 Source /home/ec-2user/venv/python34/bin/activate and then using pip install, I installed the required module for python3.4. So now the default interpreter is python3.4 and when I run the script on ec2-user directory using the following command: python test.py the program runs without any problem (so I am sure the module is installed correctly). But when I assign python file to a cronjob * * * * * python test.py It does not work. Checking the mail, the error is: “No module found named “xxxxx” “ But as I said it worked fine outside of the cron. I was wondering if you can help me with this problem. I appreciate your time and information.
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/48490984
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
tagged with: amazon-ec2
upvote count: 1
downvote count: 1
has title: Cron does not execute a python script that needs a python3 module in AWS-ec2
has answer: http://stackoverflow.com/a/67450182
score: 0
tagged with: cron

http://stackoverflow.com/q/48504761
type: AnsweredQuestion
has body: I want to get the column names so that I can add to the new data frame. In [241]: cursor.description Out[241]: (('a', None, None, None, None, None, None), ('b', None, None, None, None, None, None), ('c', None, None, None, None, None, None), ('d', None, None, None, None, None, None)) In [242]: rows Out[242]: [('Atlanta', 'Georgia', 1.25, 6), ('Tallahassee', 'Florida', 2.6, 3), ('Sacramento', 'California', 1.7, 5)] I used quite complicated and dull method: frame = DataFrame(rows, columns = list(cursor.description[i][0] for i in range(len(cursor.description)))) Is there a short cut to call the column names? Is it possible to achieve this by using zip()?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48504843
score: 1
has answer: http://stackoverflow.com/a/48504843
type: Question
has comment: http://stackoverflow.com/comment/84006254
upvote count: 2
has title: What is the shortcut for lists indexing in Python3.5?
answer count: 1
tagged with: python
downvote count: 1
favorite count: 0
tagged with: indexing

http://stackoverflow.com/comment/84160115
score: 1
type: Comment
type: QuestionComment
has text: You can define your `dict = defaultdict(list)` instead of `dict = {}`
comment on: http://stackoverflow.com/q/48581767

http://stackoverflow.com/a/48567035
has comment: http://stackoverflow.com/comment/84131780
has comment: http://stackoverflow.com/comment/84130519
has comment: http://stackoverflow.com/comment/84130217
has body: Random numbers are being generated pseudo-random way (check out this for more information), the problem here is that everytime you call np.random.uniform(low=0, high=1, size=len(px)) it creates a brand new number. In order to obtain the same pseudo-random number just use random.seed(number) (that number must be the same for all py calls, but different from the other variables) every time you want to obtain the same number as before and then call the function I mentioned above. Thus, you'll obtain the same value for py. EDIT Due to the comments below, I've realized (thanks to @roganjosh) another way to approach the solution is to use a map to store some randomly determined values for specific variables: First of all, I've created a new map: seeds = {"py": random.uniform(0,1)} and whenever you want to obtain again py value you have to call seeds using: seeds.get("py") (where you can change py for other values). I've also created a function so you can add keys with their numerical values as much as you want: def raandomseed(key): seeds.update({key:random.uniform(0,1)}) For further information about pseudo-random functions check out the Python wiki here
has comment: http://stackoverflow.com/comment/84132366
score: 0
has comment: http://stackoverflow.com/comment/84131804
has comment: http://stackoverflow.com/comment/84130388
has comment: http://stackoverflow.com/comment/84131364
has comment: http://stackoverflow.com/comment/84131759
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84131700
answers question: http://stackoverflow.com/q/48566704
has comment: http://stackoverflow.com/comment/84131510
has comment: http://stackoverflow.com/comment/84131776
type: Answer
has comment: http://stackoverflow.com/comment/84131173

http://stackoverflow.com/q/48617065
tagged with: dictionary
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48617108
has comment: http://stackoverflow.com/comment/84874874
answer count: 1
has title: In python how do I convert string to dictionary to retrieve a particular value
type: Question
has comment: http://stackoverflow.com/comment/84230872
accepted answer: http://stackoverflow.com/a/48617108
has body: One function returns below String s : s = 'Power On Enabled: On\nsignalStrength: -050\nip address: 192.168.75.123\n' I want to read the value of ip address in above string s. Used below code : /* Code */ s = 'Power On Enabled: On\nsignalStrength: -050\nip address: 192.168.75.123\n' ipdict = {} newstr = s.replace("\n",",") newdict = ipdict.update(newstr) ip = newdict.get('ip address') print ip Got below Error : "dictionary update sequence element #0 has length 1; 2 is required"
tagged with: python

http://stackoverflow.com/comment/84131158
comment on: http://stackoverflow.com/q/48567396
score: 1
type: Comment
type: QuestionComment
has text: But 1. that's not the right syntax for any of Python's string formatting; and 2. that's also not actually inside a string template, you're trying to run it as code. Maybe [read the docs](https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting)?

http://stackoverflow.com/comment/84011259
has text: My version now handles infinity and NaN properly (I added that before I saw you answered too). Yours doesn't; `== float('nan')` will of course always fail.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48507872
score: 0

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

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/48575021
tags question: http://stackoverflow.com/q/48593268
tags question: http://stackoverflow.com/q/48632585
tags question: http://stackoverflow.com/q/48621750
tags question: http://stackoverflow.com/q/48589123
tags question: http://stackoverflow.com/q/48613557
tags question: http://stackoverflow.com/q/48539701
tags question: http://stackoverflow.com/q/48552580
tags question: http://stackoverflow.com/q/48530448
tags question: http://stackoverflow.com/q/48508938
tags question: http://stackoverflow.com/q/48550533
tags question: http://stackoverflow.com/q/48625029
tags question: http://stackoverflow.com/q/48488519
tags question: http://stackoverflow.com/q/48531445
tags question: http://stackoverflow.com/q/48491525
tags question: http://stackoverflow.com/q/48550696
tags question: http://stackoverflow.com/q/48496886
tags question: http://stackoverflow.com/q/48644212
tags question: http://stackoverflow.com/q/48550740
tags question: http://stackoverflow.com/q/48501848
tags question: http://stackoverflow.com/q/48506592
tags question: http://stackoverflow.com/q/48569525
tag name: json
tags question: http://stackoverflow.com/q/48552370
tags question: http://stackoverflow.com/q/48504771
tags question: http://stackoverflow.com/q/48588049
tags question: http://stackoverflow.com/q/48510665
tags question: http://stackoverflow.com/q/48641301
tags question: http://stackoverflow.com/q/48575709
tags question: http://stackoverflow.com/q/48491046
tags question: http://stackoverflow.com/q/48614867
tags question: http://stackoverflow.com/q/48507771
tags question: http://stackoverflow.com/q/48581558
tags question: http://stackoverflow.com/q/48583567
tags question: http://stackoverflow.com/q/48535166
tags question: http://stackoverflow.com/q/48524894
tags question: http://stackoverflow.com/q/48519014
tags question: http://stackoverflow.com/q/48626405
tags question: http://stackoverflow.com/q/48564742
tags question: http://stackoverflow.com/q/48597252
tags question: http://stackoverflow.com/q/48607000
tags question: http://stackoverflow.com/q/48604563
tags question: http://stackoverflow.com/q/48620892
tags question: http://stackoverflow.com/q/48493135
tags question: http://stackoverflow.com/q/48504721
tags question: http://stackoverflow.com/q/48513371
tags question: http://stackoverflow.com/q/48500005
tags question: http://stackoverflow.com/q/48592060
tags question: http://stackoverflow.com/q/48491178
tags question: http://stackoverflow.com/q/48631253
tags question: http://stackoverflow.com/q/48613592
tags question: http://stackoverflow.com/q/48568555
tags question: http://stackoverflow.com/q/48539039
tags question: http://stackoverflow.com/q/48584932
tags question: http://stackoverflow.com/q/48531897
tags question: http://stackoverflow.com/q/48538663
tags question: http://stackoverflow.com/q/48524613
tags question: http://stackoverflow.com/q/48508942
tags question: http://stackoverflow.com/q/48624641
tags question: http://stackoverflow.com/q/48500373
tags question: http://stackoverflow.com/q/48535997
tags question: http://stackoverflow.com/q/48568390
tags question: http://stackoverflow.com/q/48636070
tags question: http://stackoverflow.com/q/48531876
tags question: http://stackoverflow.com/q/48614158
tags question: http://stackoverflow.com/q/48519661
tags question: http://stackoverflow.com/q/48590884
tags question: http://stackoverflow.com/q/48604058
tags question: http://stackoverflow.com/q/48586647
type: Tag
tags question: http://stackoverflow.com/q/48526603
tags question: http://stackoverflow.com/q/48508617
tags question: http://stackoverflow.com/q/48593007
tags question: http://stackoverflow.com/q/48542089
tags question: http://stackoverflow.com/q/48604921
tags question: http://stackoverflow.com/q/48529256
tags question: http://stackoverflow.com/q/48492639
tags question: http://stackoverflow.com/q/48614221
tags question: http://stackoverflow.com/q/48528109
tags question: http://stackoverflow.com/q/48506558

http://stackoverflow.com/comment/84265386
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48634152
has text: @DYZ it works without it
type: Comment

http://stackoverflow.com/comment/84151895
score: 0
type: Comment
type: AnswerComment
has text: pip gets installed with python then why it is not working here why it is giving me this error
comment on: http://stackoverflow.com/a/48577656

http://stackoverflow.com/comment/84157186
type: QuestionComment
has text: which centos are you using? I don't see problem with ls
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48579428

http://stackoverflow.com/a/48613703
type: Answer
accepted answer of: http://stackoverflow.com/q/48612634
has body: In principle using zdir="y" seems the correct approach. That would however mean to supply the y argument as last one in the call, from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from numpy import arange, sin, pi x = arange(0.0, 10, 0.04) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for y in list(range(0,8))[::-1]: z = sin(2*x*pi*y) ax.plot(x, z ,y, zdir="y") plt.xlabel(' x', fontsize = 12, color = 'black') plt.ylabel(' y', fontsize = 12, color = 'black') ax.set_ylim(0,9) ax.set_zlim(-1,1) plt.show()
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48612634
upvote count: 3
score: 3

http://stackoverflow.com/comment/84052492
score: 0
has text: def fizz_buzz(n): n=[] for nums in n: if nums%5==0 and nums%3==0: print("fizz buzz") elif nums%3==0: print("fizz") elif nums%5==0: print("buzz") elif nums%3!=0 and nums%5!=0: print(nums) else: print("invalid arguement")
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48528144

http://stackoverflow.com/a/48585867
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: If you want a column vector use x2 = x[:, np.newaxis] x2.shape # (4, 1)
answers question: http://stackoverflow.com/q/48585827

http://stackoverflow.com/q/48493129
has comment: http://stackoverflow.com/comment/83979509
has comment: http://stackoverflow.com/comment/83979653
has comment: http://stackoverflow.com/comment/83979594
has comment: http://stackoverflow.com/comment/84175894
has comment: http://stackoverflow.com/comment/83979631
has comment: http://stackoverflow.com/comment/83979863
upvote count: 3
has body: I often deal with mappings which are injective. In programming terminology, this can be expressed as a dictionary where all values are unique as well as, of course, all keys. Is there a memory-efficient data structure for injective mappings with all the time-complexity properties you expect from dictionaries? For example: d = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} d.get(2) = 'b' # this works with a normal dictionary d.get('b', reverse=True) = 2 # but this is not possible All the solutions in Two way/reverse map seem to require using or combining two sets of mappings, focusing on making it easier to perform operations on a two-way map. This is fine for small dictionaries that fit neatly in memory, but not good for large dictionaries. The requirement is there should be no additional memory overhead storing the injective two-way map versus a regular dictionary storing only one-way mappings. I understand dictionaries use a hash table, which use an associative array data type. By definition, associative arrays implement key -> value mappings with unique keys. Is it possible, theoretically or in practice, to produce a smart injective mapping which allows reverse lookup? If it is not possible, I would appreciate an explanation why such a construct is difficult, or impossible, to implement with the same efficiency as dictionaries. Update Following the discussion with @rpy (see comments below), any information on how to set up a python dictionary-like object using a perfect reversible hash function would be useful. But, of course, a working implementation would be ideal (I have already tried perfection).
has comment: http://stackoverflow.com/comment/83979583
has comment: http://stackoverflow.com/comment/83979706
answer count: 1
downvote count: 3
linked to: http://stackoverflow.com/q/1456373
favorite count: 0
type: Question
tagged with: perfect-hash
has comment: http://stackoverflow.com/comment/83980285
tagged with: hash
has comment: http://stackoverflow.com/comment/83979719
tagged with: injective-function
has title: Injective two-way mappings
has comment: http://stackoverflow.com/comment/83979730
has answer: http://stackoverflow.com/a/48559348
has comment: http://stackoverflow.com/comment/83979559
tagged with: python
accepted answer: http://stackoverflow.com/a/48559348
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84174867
has comment: http://stackoverflow.com/comment/84175743
linked to: http://stackoverflow.com/q/4273466
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/1456373
has comment: http://stackoverflow.com/comment/83979520
score: 0
has comment: http://stackoverflow.com/comment/83979608

http://stackoverflow.com/comment/84287068
type: Comment
type: QuestionComment
has text: @eyllanesc,do you have an example on that? Something like this ? http://pyqt.sourceforge.net/Docs/PyQt5/qml.html#a-simple-example
comment on: http://stackoverflow.com/q/48644511
score: 0

http://stackoverflow.com/a/48630303
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48630089
has comment: http://stackoverflow.com/comment/121846807
type: AcceptedAnswer
downvote count: 0
has body: You'll need to pivot with a surrogate column. Here's a solution using cumsum + set_index + unstack. v = df.set_index(['location', 'field', df.field.eq('firstName').cumsum()]).unstack(-2) v.index = v.index.droplevel(-1) v.columns = v.columns.droplevel(0) field address1 address2 address3 dob email firstName \ location location1 F G H C D A location1 N O P K L I location2 V W X S T Q field lastName title location location1 B E location1 J M location2 R U
accepted answer of: http://stackoverflow.com/q/48630089

http://stackoverflow.com/comment/110061652
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48558428
type: AnswerComment
has text: Statistical Profiling approach of time series anomaly detection can be really helpful for real time anomaly detection. You can take a look at these articles as reference points: https://towardsdatascience.com/effective-approaches-for-time-series-anomaly-detection-9485b40077f1 https://www.aditya-bhattacharya.com/?p=72&page=4

http://stackoverflow.com/a/48562080
upvote count: 2
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48561909
type: Answer
has comment: http://stackoverflow.com/comment/84119820
has comment: http://stackoverflow.com/comment/84119752
has comment: http://stackoverflow.com/comment/139801551
has body: You want from keras.preprocessing import text tokenizer = text.Tokenizer(...) The reason is that keras/preprocessing/__init__.py doesn't import nor expose the text submodule

http://stackoverflow.com/q/48572258
has title: Connect to MongoDB with self-signed certificate from EVE
type: AnsweredQuestion
score: 0
tagged with: eve
tagged with: ssl
tagged with: python
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/48727022
accepted answer: http://stackoverflow.com/a/48727022
has body: MongoDB uses self-signed certificate. I want to setup service on EVE to work with it. I searched documentation and SO but found only information how to use self-signed cert to access EVE itself. What should I do to connect to MongoDB from EVE with self-signed certificate?
answer count: 1
has comment: http://stackoverflow.com/comment/84169453

http://stackoverflow.com/comment/84259442
type: Comment
type: QuestionComment
score: 0
has text: Hardcoding the values would defeat the purpose of the class (which will be accessing various urls and targetting different json keys). I could modify the code to test it, but it cannot stay that way and achieve what it was written to do.
comment on: http://stackoverflow.com/q/48629461

http://stackoverflow.com/a/48535690
accepted answer of: http://stackoverflow.com/q/48535599
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48535599
score: 5
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/84309157
has body: I think this is easily done with two comprehensions as: Code: have_2 = {(d['name'], d['age']) for d in list_two} extra = [d for d in list_one if (d['name'], d['age']) not in have_2] This first creates a set of tuples which we already have, then checks which dicts do not match any of these existing keys. Test Code: list_one = [{'name': 'alf', 'age': 25}, {'name': 'alf', 'age': 50}, {'name': 'cid', 'age': 30}] list_two = [{'name': 'alf', 'age': 25, 'hair_color': 'brown'}, {'name': 'cid', 'age': 30, 'hair_color': 'black'}] have_2 = {(d['name'], d['age']) for d in list_two} extra = [d for d in list_one if (d['name'], d['age']) not in have_2] print(extra) Results: [{'name': 'alf', 'age': 50}]

http://stackoverflow.com/comment/97807120
score: 0
has text: were you able to solve this issue ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48523629

http://stackoverflow.com/comment/84127229
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48565527
has text: I'm glad I could help, could you please accept this as an answer so the question doesn't seem to be unresolved?
type: Comment

pst
tag name: pst
tags question: http://stackoverflow.com/q/48583906
type: Tag

http://stackoverflow.com/q/48628302
has comment: http://stackoverflow.com/comment/84253609
has answer: http://stackoverflow.com/a/48628413
has title: How to find if a software is present with python
score: 0
has comment: http://stackoverflow.com/comment/84253767
answer count: 2
linked to: http://stackoverflow.com/q/3503879
has answer: http://stackoverflow.com/a/48628388
type: Question
has comment: http://stackoverflow.com/comment/84253964
linked to: http://stackoverflow.com/q/11210104
has body: I have a python code that call a gpg command with os.system() to decrypt some files as part of a larger file management pipeline. However, on my MacOS 10.11.6, I have a version of gpg2 that I use to decrypt files. So I’d like to add in the script some check of whether gpg or gpg2 are present on the machine. I tried to test a call for gpg and catch a possible OSError with: try: os.system("gpg --version") except OSError: print("gpg not found") But this doesn't work even if gpg is not present and the output of the os.system() call is: sh: gpg: command not found 32512 Any idea of how I can do this? (PS: I have no clue what the 32512 is...)
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/11210104

http://stackoverflow.com/q/48491412
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83975981
accepted answer: http://stackoverflow.com/a/48492694
has comment: http://stackoverflow.com/comment/83977098
has body: I have frozenset output that looks like this: The data below is just an example. Overall I want the data to be in this format: For doubles: Item Item Confidence For Triples: Item Item Item Confidence Doubles: [(frozenset({'GRO73461'}), frozenset({'ELE17451'}), 1.0), (frozenset({'ELE26917'}), frozenset({'GRO99222'}), 1.0), (frozenset({'SNA80192'}), frozenset({'ELE17451'}), 1.0), (frozenset({'DAI22896'}), frozenset({'ELE17451'}), 0.9), (frozenset({'GRO99222'}), frozenset({'ELE17451'}), 0.8125)] Triples: [(frozenset({'DAI22896'}), frozenset({'GRO73461', 'ELE17451'}), 0.8), (frozenset({'GRO73461'}), frozenset({'ELE17451', 'DAI22896'}), 0.8), (frozenset({'ELE17451'}), frozenset({'GRO73461', 'DAI22896'}), 0.3076923076923077)] I was just wondering if it was possible to retrieve the element such that the output is in this format: OUTPUT A FRO11987 FRO12685 0.4325 FRO11987 ELE11375 0.4225 FRO11987 GRO94758 0.4125 FRO11987 SNA80192 0.4025 FRO11987 FRO18919 0.4015 OUTPUT B FRO11987 FRO12685 DAI95741 0.4325 FRO11987 ELE11375 GRO73461 0.4225 FRO11987 GRO94758 ELE26917 0.4125 FRO11987 SNA80192 ELE28189 0.4025 FRO11987 FRO18919 GRO68850 0.4015 If not any alternatives to using a frozenset would be helpful. Thank you for reading
tagged with: frozenset
upvote count: 3
tagged with: set
has answer: http://stackoverflow.com/a/48492694
has comment: http://stackoverflow.com/comment/83977019
has comment: http://stackoverflow.com/comment/83978540
type: AnsweredQuestion
has title: Retrieving elements from Frozenset/Alternatives to Frozenset
tagged with: apriori
downvote count: 2
has comment: http://stackoverflow.com/comment/83978177
tagged with: python
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83975938
favorite count: 0
has comment: http://stackoverflow.com/comment/83976028
type: Question

http://stackoverflow.com/comment/84077483
comment on: http://stackoverflow.com/q/48540690
score: 0
type: Comment
has text: Possible duplicate of [Replace data in csv file using python](https://stackoverflow.com/questions/8905165/replace-data-in-csv-file-using-python)
type: QuestionComment

http://stackoverflow.com/q/48637178
type: Question
has comment: http://stackoverflow.com/comment/135495219
has title: Do Django templates allow for range() in for loops?
linked to: http://stackoverflow.com/q/1107737
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/76858783
linked to: http://stackoverflow.com/q/13897001
tagged with: python
score: 10
upvote count: 10
answer count: 4
has comment: http://stackoverflow.com/comment/135497092
tagged with: django-templates
tagged with: django-views
has body: I am trying to use a for loop in my template but I am getting an error. Here is the Jinja: {% for i in range(1,10) %} &lt;h2&gt;{{i}}&lt;/h2&gt; {% endfor %} Here is the error: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '(1,10)' from 'range(1,10)' I am a little confused. This indicates that there is something wrong with range or even that it doesn't exist, yet I have seen it suggested as a solution in other Stack Overflow posts such as this one: How to simulate while loop in Jinja2 Does range exist in Jinja/Django? If yes, why is this not working, and if no, what is the best alternative?
has answer: http://stackoverflow.com/a/70479189
has answer: http://stackoverflow.com/a/48655195
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/66272714
tagged with: jinja2
favorite count: 0

http://stackoverflow.com/q/48607339
downvote count: 1
possible better answer: http://stackoverflow.com/a/61328309
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48607515
has comment: http://stackoverflow.com/comment/108502606
type: AnsweredQuestion
tagged with: geography
upvote count: 8
has answer: http://stackoverflow.com/a/48607515
tagged with: nltk
has comment: http://stackoverflow.com/comment/108511480
tagged with: python
score: 7
has body: I use Python 3 (I also have Python 2 installed) and I want to extract countries or cities from a short text. For example, text = "I live in Spain" or text = "United States (New York), United Kingdom (London)". The answer for countries: Spain [United States, United Kingdom] I tried to install geography but I am unable to run pip install geography. I get this error: Collecting geography Could not find a version that satisfies the requirement geography (from versions: ) No matching distribution found for geography It looks like geography only works with Python 2. I also have geopandas, but I don't know how to extract the required info from text using geopandas.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/61328309
answer count: 2
has comment: http://stackoverflow.com/comment/108510555
has comment: http://stackoverflow.com/comment/108493106
has title: How to extract countries from a text?

http://stackoverflow.com/a/48554722
downvote count: 0
answers question: http://stackoverflow.com/q/48554683
type: Answer
has body: If you wish to run multiple http.server instances in parallel - you will need to define different port numbers for each. By default, port 8000 is used, but this can be overridden on the command line like so; python -m http.server 8001 This server will run on port 8001 instead of the default. Now all you have to do is run this command from whatever directories you want shared in this manner, with a different port for each one. One way to do this, is to use cmd.exe to navigate to the folder you wish to expose, then run the command from there. If you do not have python in your PATH, then using C:\Python\Python35\python.exe -m http.server 8002 for example should do the trick.
score: 4
accepted answer of: http://stackoverflow.com/q/48554683
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/84251154
has text: Please show some sample input which reproduces the error. `readlines()` is a bad idea because the newlines are retained.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48626933

http://stackoverflow.com/q/48642111
has body: I am using AWS and use AWS cloudwatch to view logs. While things should not break on AWS, they could. I just had such a case. Then I searched for Traceback and just got the lines Traceback (most recent call last): without the actual traceback. I have a working structured logging setup (see other question) and I would like to get tracebacks in a similar way. So instead of: Traceback (most recent call last): File "/home/math/Desktop/test.py", line 32, in &lt;module&gt; adf NameError: name 'adf' is not defined something like {"message": "Traceback (most recent call last):\n File \"/home/math/Desktop/test.py\", line 32, in &lt;module&gt;\n adf\n NameError: name 'adf' is not defined", "lineno": 35, "pathname": "/home/math/Desktop/test.py"} or even better also with the string in a JSON format. The only way to achieve this I can think of is a giant try-except block. Pokemon-style. Is there a better solution?
has answer: http://stackoverflow.com/a/56220819
upvote count: 18
favorite count: 0
tagged with: traceback
type: Question
has comment: http://stackoverflow.com/comment/84283276
has comment: http://stackoverflow.com/comment/84280935
linked to: http://stackoverflow.com/q/48170682
has title: Can I make Python output exceptions in one line / via logging?
accepted answer: http://stackoverflow.com/a/48643567
possible better answer: http://stackoverflow.com/a/52669611
score: 18
tagged with: python
has answer: http://stackoverflow.com/a/48643567
has answer: http://stackoverflow.com/a/52669611
tagged with: logging
downvote count: 0
tagged with: python-logging
linked to: http://stackoverflow.com/q/28180159
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84280826
answer count: 3

http://stackoverflow.com/q/48524099
downvote count: 2
tagged with: keyword
has comment: http://stackoverflow.com/comment/84043516
upvote count: 7
has comment: http://stackoverflow.com/comment/84043481
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84043026
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48524520
possible better answer: http://stackoverflow.com/a/48524520
has comment: http://stackoverflow.com/comment/84043030
has answer: http://stackoverflow.com/a/48524444
has comment: http://stackoverflow.com/comment/84043165
accepted answer: http://stackoverflow.com/a/48524444
linked to: http://stackoverflow.com/q/214881
has comment: http://stackoverflow.com/comment/84043526
tagged with: python
has comment: http://stackoverflow.com/comment/84043150
has comment: http://stackoverflow.com/comment/84043676
has comment: http://stackoverflow.com/comment/84043073
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84043130
has body: I'd like to add a new keyword to Python and @EliBendersky's wonderful answer explains how to do this by changing the code and re-distributing the Python compiler. Is it possible to introduce a new keyword without changing the compiler code? Perhaps introduce it through a library? Edit: For example, I'd like to add a shorthand for regex matching by adding a keyword like matches that can be used like: "You can't take the sky from me" matches '.+sky.+' I can add new, custom behavior using AST transformations, but the above case will fail on a syntax error.
has comment: http://stackoverflow.com/comment/84042959
answer count: 2
score: 5
has title: Add new statements to Python without customizing the compiler
tagged with: syntax
has comment: http://stackoverflow.com/comment/84043054
has comment: http://stackoverflow.com/comment/84043575
has comment: http://stackoverflow.com/comment/84043793

http://stackoverflow.com/comment/84077250
score: 2
type: AnswerComment
has text: @Rawing, `csv` module is for "CSV File Reading and Writing". The question is about a "string formatted as csv line". The asker could have just used this to mean "comma delimited one line string". We don't even know if there are any files involved...
type: Comment
comment on: http://stackoverflow.com/a/48540812

http://stackoverflow.com/comment/84267102
type: Comment
type: QuestionComment
has text: Do you have to select that one row by value or by index?
score: 1
comment on: http://stackoverflow.com/q/48635148

http://stackoverflow.com/comment/83990657
has text: With `()`. Without them you are trying to slice a method which makes no sense.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48498519
score: 0

http://stackoverflow.com/comment/83973108
comment on: http://stackoverflow.com/q/48490026
type: QuestionComment
has text: If the `request.method` is not `'POST'`, then the function will return `None`.
type: Comment
score: 0

http://stackoverflow.com/a/53142990
accepted answer of: http://stackoverflow.com/q/48509766
type: Answer
answers question: http://stackoverflow.com/q/48509766
score: 8
type: AcceptedAnswer
downvote count: 0
has body: I solved this by running the following imports in the following order: import matplotlib.pyplot as plt import mpl_toolkits from mpl_toolkits.mplot3d import Axes3D Note: This only worked for me on python3. So first, I had to install python3 and pip3. Then I did "pip3 install matplotlib" in Terminal. If you already have matplotlib then try "pip3 install --upgrade matplotlib"
has comment: http://stackoverflow.com/comment/126276130
upvote count: 8

http://stackoverflow.com/a/48560992
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48560703
upvote count: 1
has comment: http://stackoverflow.com/comment/84119453
has body: In ElementTree model, text node that comes after (following sibling of) an element is stored as tail of that element, not text of the parent element. So besides section.text, you also need to look into section.tail : &gt;&gt;&gt; section in abstract: ... print section.text.strip() ... if section.tail: ... print section.tail.strip() ... Abstract Amphinomids, more commonly known as fireworms, are a basal lineage of marine annelids characterized by the presence of defensive dorsal calcareous chaetae, which break off upon contact. It has long been hypothesized that amphinomids are venomous and use the chaetae to inject a toxic substance. However, studies investigating fireworm venom from a morphological or molecular perspective are scarce and no venom gland has been identified to date, nor any toxin characterized at the molecular level. To investigate this question, we analyzed the transcriptomes of three species of fireworms— Eurythoe complanata , Hermodice carunculata , and Paramphinome jeffreysii —following a venomics approach to identify putative venom compounds. Our venomics pipeline involved de novo transcriptome assembly, open reading frame, and signal sequence prediction, followed by three different homology search strategies: BLAST, HMMER sequence, and HMMER domain. Following this pipeline, we identified 34 clusters of orthologous genes, representing 13 known toxin classes that have been repeatedly recruited into animal venoms. Specifically, the three species share a similar toxin profile with C-type lectins, peptidases, metalloproteinases, spider toxins, and CAP proteins found among the most highly expressed toxin homologs. Despite their great diversity, the putative toxins identified are predominantly involved in three major biological processes: hemostasis, inflammatory response, and allergic reactions, all of which are commonly disrupted after fireworm stings. Although the putative fireworm toxins identified here need to be further validated, our results st…
type: Answer
answers question: http://stackoverflow.com/q/48560703

http://stackoverflow.com/comment/84211547
has text: There is only one problem, that is I am unable to use my local file as it is taking only URI of an image and local files don't have any URI.
type: QuestionComment
comment on: http://stackoverflow.com/q/48607548
type: Comment
score: 0

http://stackoverflow.com/q/48591473
has title: Getting the boundary of a rectangle using the convex hull (in python)
answer count: 1
tagged with: python
tagged with: scipy
has comment: http://stackoverflow.com/comment/84181143
type: Question
has comment: http://stackoverflow.com/comment/84181371
tagged with: delaunay
accepted answer: http://stackoverflow.com/a/48592328
upvote count: 2
has body: I am trying to get the boundary of a rectangle using scipy.ConvexHull(), and it's failing to do so. u=np.linspace(0, 4, 8) v=np.linspace(5, 10, 8) u,v=np.meshgrid(u,v) u=u.flatten() v=v.flatten() points2D=np.vstack([u,v]).T hull = ConvexHull(points2D) convex_hull_plot_2d(hull) boundaryList = hull.vertices print boundaryList gives only the four corners:[ 0 7 63 56] Perturbing the points a bit using the option qhull_options="QJ Pp" as follows: hull = ConvexHull(points2D, qhull_options="QJ Pp") gives more points: [62 56 40 8 0 2 6 7 15 23 47 55 63], but still not the full boundary set. Can someone tell me a proper fix for this?
has answer: http://stackoverflow.com/a/48592328
downvote count: 0
tagged with: convex-hull
favorite count: 0
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84181402

http://stackoverflow.com/comment/84123120
has text: Why not convert your Bayer BGGR8 to something OpenCV can read with `ffmpeg`using something like `ffmpeg -f rawvideo -pixel_format bayer_bggr8 -video_size 1024x768 -i YourFile.yuv -c:v libx264 output.avi`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48555402
score: 1

http://stackoverflow.com/comment/84094249
comment on: http://stackoverflow.com/q/48548787
has text: please check where you have defined forms.py and how? Django login using form view in details https://medium.freecodecamp.org/user-authentication-in-django-bae3a387f77d
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84080521
score: 0
type: Comment
has text: :D What you mean "then you can call method_a() inside method_b to get url_list" ? method_a() return type is not url. So, how can I get this global url value ? Do you mean I should run method_a() first then run the actual method_b which I'm trying to test /
type: QuestionComment
comment on: http://stackoverflow.com/q/48541863

http://stackoverflow.com/comment/84108482
type: AnswerComment
score: 0
type: Comment
has text: @MihirSharma , welcome. You can [accept the answer](https://stackoverflow.com/help/accepted-answer) if it solved your problem
comment on: http://stackoverflow.com/a/48548893

http://stackoverflow.com/q/48568062
has body: Disclaimer: I think question is not related to the keras directly and is more about general behavior of generators in python I am trying to build a custom data generator for Keras. I do this since build-in image data generators support only the classification tasks while I am trying to solve a regression task with images as inputs. First of all, I upload a text file which contains img path and target variable Y into the dataframes, then I shuffle them: train, test = AnnoParser.get_data(input_path) train = train.sample(frac=1).reset_index(drop=True) AnnoParser just parses text file and returns Pandas Dataframes. Then I define my data generator: def get_data_generator(array, resized_width, resized_height, mode): while True: if mode == 'train': array = array.sample(frac=1).reset_index(drop=True) augment = True for img_path, img_hype in array: try: img = data_augment(img_path,resized_width, resized_height, augment) yield np.copy(img), np.copy(img_hype) Since I am using while True loop I expect it to be infinite. As you see I also reshuffle input array each time to ensure that the sample is random. DataAugment function takes img path as input, loads the image from this path and resizes it to specified sizes, returning the image itself (cv2 is used). Finally I create a generator instance and use it later: data_gen_train = DataGenerator.get_data_generator(train, 224, 224, "train") Now, as far as I understand under the hood each time I will be calling next(data_gen_train) generator will shuffle the original train array and draw next value from the execution result. Hence as I understand my generator supposed to be able to infinitely draw images from the population of all image pathes I have in my original dataset. But seems like the generator still often throws the StopIteration exception. I am not sure why. Can anyone explain? UPDATE As requested, also below you can find how use the generator to fit model. As you see I first fetch a bunch of images into array so that I can…
favorite count: 0
type: Question
tagged with: numpy
has title: Keras - custom infinite data generator with shuffle
tagged with: python
has comment: http://stackoverflow.com/comment/84174118
has comment: http://stackoverflow.com/comment/84152327
tagged with: generator
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48635001
upvote count: 1
accepted answer: http://stackoverflow.com/a/48635001
tagged with: keras

http://stackoverflow.com/q/48492234
has comment: http://stackoverflow.com/comment/83977847
has comment: http://stackoverflow.com/comment/83977758
tagged with: generator
has comment: http://stackoverflow.com/comment/83977941
score: 0
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83977980
duplicate of: http://stackoverflow.com/q/12423614
downvote count: 1
has comment: http://stackoverflow.com/comment/83978013
duplicate of: http://stackoverflow.com/q/2295290
has comment: http://stackoverflow.com/comment/83977939
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/12423614
has title: Using list expansion for a set of lambda functions produces different results than the equivalent without list expansion
type: UnansweredQuestion
has body: I'm using list expansion to create a set of lambda functions. Each lambda function returns a generator with an initial value. The API I am using requires that I pass it a 0-parameter function handle that returns a generator object. Hence the odd form of lambda: generator. I get unexpected results, shown below. Can anyone explain why I only see the generator seeded with 200 when using list expansion? All code is copy/paste runnable. Case 1: Using list expansion def mygen(val): for i in range(3): yield val + i generators = [lambda: mygen(start) for start in [100, 200]] g = generators[0]() # generators[1]() produces the same result for _ in range(3): print(next(g)) Result: 200 201 202 Expected Result: 100 201 202 Case 2: Without list expansion def mygen(val): for i in range(3): yield val + i g0 = lambda: mygen(100) g1 = lambda: mygen(200) g = g0() for _ in range(3): print(next(g)) Result (as expected) 100 101 102
has comment: http://stackoverflow.com/comment/83977891
tagged with: python
tagged with: lambda
duplicate of: http://stackoverflow.com/q/19693782

http://stackoverflow.com/q/48541033
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/48541991
type: AnsweredQuestion
score: 0
has title: How to Scrape a popup page using python and selenium and beautiful soup
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/84078699
type: Question
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/48541991
has body: I'm trying to scrape off info from a pop up page. It has names of the NGOs in a table format and on clicking on each name gives way to a pop up page. In my code below, I'm extracting the onclick attribute for each NGO and storing it in a variable. I want to use this variable to make a post request to get the pop up page. (I've also tried accessing it using selenium. It didn't work. How should I get my code to open these pop up links for scraping data off them? HTML behind the page Name Code portion is below html = requests.get("http://ngodarpan.gov.in/index.php/home/statewise_ngo/31/35/1") soup = BeautifulSoup(html.text, 'lxml') first_div = soup.find ('div', class_ = "ibox-content") get_tr = first_div.find_all('a', onclick=True) for ngoinfo in get_tr: try: if re.match('show_ngo_info',ngoinfo['onclick']): k = ngoinfo['onclick'] p = re.sub("\D", "", k) except:pass

http://stackoverflow.com/q/48642928
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84284804
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84284742
tagged with: python-3.x
type: UnansweredQuestion
has title: Python3 Django project use the Python2 library
has comment: http://stackoverflow.com/comment/84282360
tagged with: python
has body: I have a project with Python 3.5.4, but I want to use a Python library called pyghmi, but the library only supports the Python 2.x. How can I solve this issue?
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84282940
has comment: http://stackoverflow.com/comment/84287348
has answer: http://stackoverflow.com/a/48645467
score: 1

http://stackoverflow.com/comment/83978177
score: 0
comment on: http://stackoverflow.com/q/48491412
type: Comment
type: QuestionComment
has text: `as` was meant to be a variable name for your list of `a` values for `Output A` (what you've now named `doubles`

http://stackoverflow.com/q/48519308
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84074916
type: Question
has title: QIdentityProxyModel doesn't change text color?
type: UnansweredQuestion
tagged with: qidentityproxymodel
tagged with: python
has body: I want to change the text color. I have a SqlRelationalTableModel and as I have found out the proper way is to use QIdentityProxyModel. I have set up the proxy, assigned it to the model and table view, but it doesn't work. Any suggestions? &lt;...&gt; myproxy = MyProxy() myproxy.setSourceModel(orders_model) tableView.setModel(myproxy) &lt;...&gt; class MyProxy(QtCore.QIdentityProxyModel): def data(self, index, role): if role == QtCore.Qt.TextColorRole: return QtCore.QVariant(QtGui.QColor(QtCore.Qt.gray)) elif role == QtCore.Qt.DisplayRole: return QtCore.QIdentityProxyModel.data(self, index, role)
score: 0
has comment: http://stackoverflow.com/comment/84048195
answer count: 0

http://stackoverflow.com/a/48505091
answers question: http://stackoverflow.com/q/48505009
score: 3
upvote count: 3
downvote count: 0
type: Answer
has body: Try this: B = [x for x in A if x[1] &lt;= 30]

http://stackoverflow.com/comment/84179819
type: Comment
score: 0
type: AnswerComment
has text: Try replacing the last line in `deleteLine` with `return "break"`.
comment on: http://stackoverflow.com/a/48590941

http://stackoverflow.com/q/48524326
answer count: 1
tagged with: cython
has title: Writing a python wrapper for c++ code
type: Question
tagged with: numpy
type: UnansweredQuestion
has body: I modified a C++ code (Kraskov_v1.C) and I now wish to call it from Python. I am able to convert the C++ code (Kraskov_v1.C) into a .so file and integrate it into my python library. However when I try and import the library, it throws up an error. The error says "undefined symbol: _Z8mir_xnynPPdiiiiS_S_S_" mir_xn_yn is a function (written in another c++ file namely miutils) that my Kraskov_v1 code calls. I included the header file include "miutils.h" in my file containing Kraskov_v1. Here is the setup.py file I wrote to build and install this package. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy.distutils.misc_util setup(name='Kraskov_v1', version='0.1.0', ext_modules=[Extension('_Kraskov_v1',sources = ["Kraskov_v1.i","Kraskov_v1.C"], include_dirs = ['src']) ]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Can someone tell me whats wrong? I am new to python and c++ and would appreciate some help.
tagged with: python
has answer: http://stackoverflow.com/a/48525427
has comment: http://stackoverflow.com/comment/84043485
tagged with: c++
score: 0

http://stackoverflow.com/comment/84104900
type: Comment
comment on: http://stackoverflow.com/a/48553786
type: AnswerComment
has text: I was also using Anaconda Python on Linux (I only have 2.7.x in the distribution version)
score: 0

http://stackoverflow.com/a/48556513
type: Answer
has body: Hi Jet Blue for better understanding go with the python wiki PerformanceTips import statements can be executed just about anywhere. It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances. Consider the following two snippets of code (originally from Greg McFarlane, I believe - I found it unattributed in a comp.lang.python python-list@python.org posting and later attributed to him in another source): def doit1(): import string ###### import statement inside function string.lower('Python') for num in range(100000): doit1() or: import string ###### import statement outside function def doit2(): string.lower('Python') for num in range(100000): doit2() doit2 will run much faster than doit1, even though the reference to the string module is global in doit2. Here's a Python interpreter session run using Python 2.3 and the new timeit module, which shows how much faster the second is than the first: def doit1(): import string string.lower('Python') import string def doit2(): string.lower('Python') import timeit t = timeit.Timer(setup='from __main__ import doit1', stmt='doit1()') t.timeit() 11.479144930839539 t = timeit.Timer(setup='from __main__ import doit2', stmt='doit2()') t.timeit() 4.6661689281463623 String methods were introduced to the language in Python 2.0. These provide a version that avoids the import completely and runs even faster: def doit3(): 'Python'.lower() for num in range(100000): doit3() Here's the proof from timeit: def doit3(): 'Python'.lower() t = timeit.Timer(setup='from main import doit3', stmt='doit3()') t.timeit() 2.5606080293655396 The above example is obviously a bit contrived, but the general principle holds. Note that putting an import in a function can speed up the initial loading of the module, especiall…
score: 0
answers question: http://stackoverflow.com/q/48556192

http://stackoverflow.com/a/48510260
answers question: http://stackoverflow.com/q/48510110
accepted answer of: http://stackoverflow.com/q/48510110
type: Answer
score: 0
type: AcceptedAnswer
has body: You can use a variable inside the backticks. You should also put the classify_image.py call inside the if, so you only do it when the file has been successfully uploaded. And use forward slashes in the pathname rather than backslashes, or double the backslashes. In double quotes and backticks, backslash is an escape prefix, resulting in incorrect parsing of the pathname. &lt;?PHP if(!empty($_FILES['uploaded_file'])) { $path = "uploads/"; $path = $path . basename( $_FILES['uploaded_file']['name']); if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) { echo "The file ". basename( $_FILES['uploaded_file']['name']). " has been uploaded"; $python = `python classify_image.py --image_file C:/xampp/htdocs/$path`; echo $python; } else{ echo "There was an error uploading the file, please try again!"; } } ?&gt;

http://stackoverflow.com/a/48590409
answers question: http://stackoverflow.com/q/48570596
has body: I am using the following function to calculate the mean and variance of each currency. The 3 outliers would have easily been noticed had I been using it --- I am now. def updateMeanVar(x,k,mu,vr): ''' Purpose: Update the estimates for the mean and variance (recursive algorithm) Inputs: x -- new value (x_k) x_1,x_2,... k -- counter (index) for new value 1,2, mu -- previously estimated mean (x_k not included) vr -- previously estimated variance (x_k not included) Otputs: mu -- updated mean (with x_k included) vr -- updated variance (with x_k included) Refs. Donald E. Knuth. Seminumerical Algorithms, volume 2 of The Art of Computer Programming, chapter 4.2.2, page 232. Addison-Wesley, Boston, third edition, 1998. ''' delta = x - mu mu += delta/k vr += delta*(x - mu) return mu,vr Here is part of the output, for the European Central Bank (ECB) currency exchange rates, including today's estimates. Processing ECB exchange rates ... Saving data ... ECB working days: 4889 strt date: 1999-01-04 stop date: 2018-02-02 Exchange rates stored in: Sweden (SEK/EUR): E:/Data/ECB_ExchangeRates/Sweden/Rates.txt (mean= 9.235,std= 0.496) Denmark (DKK/EUR): E:/Data/ECB_ExchangeRates/Denmark/Rates.txt (mean= 7.448,std= 0.011) Norway (NOK/EUR): E:/Data/ECB_ExchangeRates/Norway/Rates.txt (mean= 8.238,std= 0.565) All rates stored in: E:/Data/ECB_ExchangeRates/AllRates.txt E:/Data/ECB_ExchangeRates/AllRates.csv and the summary plot.
type: Answer
score: 0

http://stackoverflow.com/comment/84163333
type: Comment
type: AnswerComment
has text: This is bad advice. Don't do this: `print("Restaurant name:", self.name, ", Cuisine type:", self.type)`, it's so easy to make mistakes (like you have, there is an extra space before the comma). In python 3.6 you should be using f-strings (or `.format` for setting up a string template).
comment on: http://stackoverflow.com/a/48583435
score: 1

http://stackoverflow.com/comment/84273009
score: 0
type: Comment
type: QuestionComment
has text: out of ideas now - pls check if there are any warning whatsoever, when executing `svn --help` in cmd or `f = subprocess.check_output(['svn.exe', '--help'])` in pythonshell
comment on: http://stackoverflow.com/q/48623047

http://stackoverflow.com/a/48549789
type: Answer
answers question: http://stackoverflow.com/q/48549711
score: 0
has body: list(input(...)) makes a list of each individual character in the input, which is probably not what you wanted. Try this instead: ratio = input('ratio numbers: ').split()

http://stackoverflow.com/a/52773848
score: 52
upvote count: 52
type: Answer
has comment: http://stackoverflow.com/comment/96889747
has body: This was caused by a Python version issue for me. I had the absl package installed on my Python 2.x, but my Python 3.x didn't have it. So I just made sure that both Pythons on my machine had the package installed: pip install absl-py pip3 install absl-py
downvote count: 0
answers question: http://stackoverflow.com/q/48490260

http://stackoverflow.com/comment/84019800
type: AnswerComment
type: Comment
has text: Thank you, this is a really interesting and wonderful idea. It appears that this still stores two separate objects in order to get the mapping of text to mapping integer, which is similar to the beginning two dataframes, but it's a nice comment on something that I was not aware of.
comment on: http://stackoverflow.com/a/48499133
score: 0

http://stackoverflow.com/comment/84061786
score: 1
type: Comment
type: QuestionComment
has text: So when I run the command the output is displayed in the terminal, but if I want to print to text file I couldn’t get it
comment on: http://stackoverflow.com/q/48507879

http://stackoverflow.com/a/48533673
type: AcceptedAnswer
has body: Tuples only need , commas, they don't need () parenthesis, except when they do! So for example in: x = 1, 2, 3 y = (1, 2, 3) And: x = 1, y = (1,) In both cases x and y are identical. But in your case: s.enter(5, 1, do_something, argument=(sc,)) s.enter(5, 1, do_something, argument=sc,) Are, as you found out, not the same. Why? Well in the second case argument=sc, the , is interpreted to be part of the ,'s of the parameter list, so it is not considered as indicating a tuple(). And in this case, you need the (sc,) to build a tuple()
answers question: http://stackoverflow.com/q/48532757
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84062953
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48532757

http://stackoverflow.com/q/48592528
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48593069
type: Question
has title: locate conditional column value based on row max
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
tagged with: sorting
has body: This is a simple version of a much larger df_data 1000 x 150 Date A B C D A' B' C' D' 31/01/2017 47 15 45 40 10 7 12 8 28/02/2017 22 34 28 13 3 2 26 4 31/03/2017 25 12 13 47 1 5 6 59 Basic problem is need row sort of columns A,B,C,D and use max/min criteria to locate corresponding row values in columns A',B',C',D' Need following pls. (1) Find the n highest values and n lowest values for each date (row). Let's assume n=2 here. (2) Conditional on min/max value from (1) use relevant column header to find the corresponding value in the same row for a different column from A',B,C',D' (in the same df or different df with exact same index of dates) Assume there is a 1-1 mapping between A,B,C,D and A',B',C',D') Desired result: 31/01/2017: max1 = 10, max2 =12 ; min1 = 7, min2 = 8 28/02/2017: max1 = 2, max2 =26 ; min1 = 4, min2 = 3 31/03/2017: max1 = 59, max2 = 1 ; min1 = 5, min2 = 6 I can find the max for e.g using df_data "A","B","C","D".apply(lambda row: np.max(row),axis=1) But how do I use iloc function within .apply or some other way to find the col header(index) of that max value? (I tried .argsort in numpy array but couldn't get anywhere) Also how do I find the top n and bottom n values in each row (where n &gt; 1) - using rank or sort? I tried following to sort the rows (descending) df_data.values.sort df_data = df_data.iloc[:,::-1] This seems to work but my end goal is to find the values in columns A',B',C',D' Sorry if a bit long.
score: 0
tagged with: row
tagged with: pandas
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/48520968
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/48521174
tagged with: python
type: Question
tagged with: seaborn
has answer: http://stackoverflow.com/a/48521174
answer count: 1
has title: Fix x-axis scale seaborn factorplot
has body: I'm attempting to make a figure that shows two plots, with each plot separated based on a set of categorical data. However, although I can make the graph, I cant figure out how to get the x-axis to be properly spaced. I want the x-axis to start before the first value (want axis to start at 60 [first value = 63]) and end after the last (want axis to end at 95 [last value = 92.1]), with xticks going up in 5's. Any help is much appreciated! Thanks in advance! import pandas as pd import matplotlib.pyplot as plt import matplotlib.axes import seaborn as sns Temperature = [63.0,63.3,63.6,63.9,64.2,64.5,64.8,65.2,65.5,65.8,66.1,66.4,66.7,67.0,67.3,67.7,68.0,68.3,68.6,68.9,69.2,69.5,69.9,70.2,70.5,70.8,71.1,71.4,71.8,72.1,72.4,72.7,73.0,73.4,73.7,74.0,74.3,74.6,74.9,75.2,75.6,75.9,76.2,76.5,76.9,77.2,77.5,77.8,78.1,78.5,78.8,79.1,79.4,79.7,80.1,80.4,80.7,81.0,81.3,81.6,81.9,82.3,82.6,82.9,83.2,83.5,83.8,84.1,84.4,84.8,85.1,85.4,85.7,86.0,86.3,86.6,86.9,87.2,87.5,87.8,88.1,88.4,88.7,89.0,89.3,89.6,89.8,90.1,90.4,90.7,91.0,91.2,91.5,91.8,92.1,63.0,63.3,63.6,63.9,64.2,64.5,64.8,65.2,65.5,65.8,66.1,66.4,66.7,67.0,67.3,67.7,68.0,68.3,68.6,68.9,69.2,69.5,69.9,70.2,70.5,70.8,71.1,71.4,71.8,72.1,72.4,72.7,73.0,73.4,73.7,74.0,74.3,74.6,74.9,75.2,75.6,75.9,76.2,76.5,76.9,77.2,77.5,77.8,78.1,78.5,78.8,79.1,79.4,79.7,80.1,80.4,80.7,81.0,81.3,81.6,81.9,82.3,82.6,82.9,83.2,83.5,83.8,84.1,84.4,84.8,85.1,85.4,85.7,86.0,86.3,86.6,86.9,87.2,87.5,87.8,88.1,88.4,88.7,89.0,89.3,89.6,89.8,90.1,90.4,90.7,91.0,91.2,91.5,91.8,92.1] Derivative = [0.0495,0.0507,0.0525,0.0548,0.0570,0.0579,0.0579,0.0574,0.0574,0.0576,0.0581,0.0587,0.0593,0.0592,0.0584,0.0580,0.0579,0.0580,0.0582,0.0588,0.0592,0.0594,0.0588,0.0581,0.0578,0.0579,0.0580,0.0579,0.0582,0.0581,0.0579,0.0574,0.0571,0.0563,0.0548,0.0538,0.0536,0.0540,0.0544,0.0551,0.0556,0.0551,0.0542,0.0535,0.0536,0.0542,0.0564,0.0623,0.0748,0.0982,0.1360,0.1897,0.2550,0.3228,0.3807,0.4177,0.4248,0.3966,0.3365,0.2558,0.1713,0.0971,0.0438,0.0140,0.0034,0.0028,…
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/84471524
score: 0
comment on: http://stackoverflow.com/q/48597577
has text: @CodeNoob, what does "ulimit -a" show?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83986359
has text: I am creating a class inherited from model.Model and using foreign key from existing User. I can see data in form still form.is_valid() returns false.
type: Comment
comment on: http://stackoverflow.com/q/48488932
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84111403
comment on: http://stackoverflow.com/q/48557613
score: 0
type: Comment
type: QuestionComment
has text: Show the relevant imports. What is `Image`? What type of data does it contain? Do you really need to convert to `float`? If you do, why not do it in one step with a `dtype` argument to `asarray`?

http://stackoverflow.com/q/48569577
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48569626
tagged with: python
has body: Can we test visual behavior of interaction with element? For example, I have a button on the page, which visually activates in a few moments after being clicked. Like a short responce animation after clicking one of these Angular buttons. Is it possible to check it, preferably with Selenium (for Python)? Is there any way to perform visual testing in Selenium?
has answer: http://stackoverflow.com/a/48569626
accepted answer: http://stackoverflow.com/a/48584901
has answer: http://stackoverflow.com/a/48643104
score: -1
has answer: http://stackoverflow.com/a/48584901
tagged with: automated-tests
upvote count: 2
type: AnsweredQuestion
answer count: 3
tagged with: selenium
has title: Is there any way to test visual behavior of interaction with element?
downvote count: 3
linked to: http://stackoverflow.com/q/11495535

http://stackoverflow.com/comment/84091446
comment on: http://stackoverflow.com/q/48546675
has text: symbol = 3MINDIA browser.get(url) browser.find_element_by_xpath('//*[@id="dataType"]/option[contains(text(), "Security wise price volume data" )]')\ . click() browser.find_element_by_class_name('reporttitle1').send_keys(symbol) browser.find_element_by_xpath('//*[@id="series"]/option[contains(text(), "EQ")]').click() browser.find_element_by_xpath('//*[@id="dateRange"]/option[contains(text(), "3 months")]').click() browser.find_element_by_class_name('getdata-button').click()
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48636484
accepted answer of: http://stackoverflow.com/q/48632520
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48632520
has comment: http://stackoverflow.com/comment/84295963
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: Your error is claiming that cms.page does not have a 'path' field, which could mean the model may not have the schema that you expect it to.

http://stackoverflow.com/a/48576543
has body: Use: df['C'] = (df['A']==True) &amp; (df['B']==False) Or better as pointed @Yakym Pirozhenko in comment is invert B column by ~: df['C'] = df['A'] &amp; ~df['B'] Sample: df = pd.DataFrame({'A':[True, False, True, True], 'B':[True, False, False, True]}) print (df) A B 0 True True 1 False False 2 True False 3 True True df['C'] = df['A'] &amp; ~df['B'] print (df) A B C 0 True True False 1 False False False 2 True False True 3 True True False
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48576417
score: 0
accepted answer of: http://stackoverflow.com/q/48576417

http://stackoverflow.com/q/48596277
has title: How to display the updated score in Kivy Python?
tagged with: python
tagged with: kivy
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/48596759
has body: I want to display the updated score value but only the initial value is displayed. The score variable in the MainClass() is linked to the kivy file, but the score is not updating. It is always showing 0 whereas it should add 1 whenever the player wins the game. Any solution will be very helpful. Thank You. main.py ...some code... class MainClass(Widget): score = NumericProperty(1) score = 0 pattern_maker(score) # This is the function to make the pattern. once_pattern_shown = False won_lost = "" checked = False def update(self, dt): global button_clicked, pattern_in_count, pattern, check_ans_clicked start_obj = Start() if start_pattern_show and not self.once_pattern_shown: for i in range(0, self.score+1): if pattern[i] == 'r': beep1.play() self.once_pattern_shown = True elif pattern[i] == 'g': beep2.play() self.once_pattern_shown = True elif pattern[i] == 'b': beep3.play() self.once_pattern_shown = True elif pattern[i] == 'y': beep4.play() self.once_pattern_shown = True if start_pattern_in and check_ans_clicked and pattern_in_count &lt;= self.score+1: if button_clicked == pattern: self.won_lost = "won" else: self.won_lost = "lost" elif start_pattern_in and check_ans_clicked and pattern_in_count &gt; self.score+1: print "No more button clicks are allowed." elif start_pattern_in and check_ans_clicked: print "Misfunction." if button_clicked == pattern and not self.checked: self.score += 1 # I want this score to be displayed. self.checked = True class Test2App(App): def build(self): game = MainClass() Clock.schedule_interval(game.update, 2) # call 'update' func every 1.0s. return game if __name__ == '__main__': Test2App().run() test2.kv ...some code... &lt;MainClass&gt;: canvas: Color: rgb: 0, 55, 55 Rectangle: pos: self.pos size: root.width, root.height Label: pos: 10, root.height-70 font_size: 25 text: "SCORE: " + str(root.score) ...some more code...
type: Question
tagged with: kivy-language
has answer: http://stackoverflow.com/a/48596418
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/48498615
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48757387
type: Question
type: UnansweredQuestion
score: -2
has body: I am trying to use OpenCV for some work on video analysis. I wanted to import the video file into an Azure ML experiment. When I try to load it from local , I did not find a supporting format ( there is a zip option though , not sure if that would help).If there any way I can work with a video ( without use of MS provided API ) in a Python notebook on a Azure ML work space ? Azure Doc link Plain text (.txt) Comma-separated values (CSV) with a header (.csv) or without (.nh.csv) Tab-separated values (TSV) with a header (.tsv) or without (.nh.tsv) Excel file Azure table Hive table SQL database table OData values SVMLight data (.svmlight) (see the SVMLight definition for format information) Attribute Relation File Format (ARFF) data (.arff) (see the ARFF definition for format information) Zip file (.zip) R object or workspace file (.RData)
tagged with: python
tagged with: opencv
downvote count: 3
tagged with: azure
upvote count: 1
has title: Azure ML - how to import video into Python notebooks?

http://stackoverflow.com/a/48492713
has comment: http://stackoverflow.com/comment/83998338
answers question: http://stackoverflow.com/q/48491217
type: Answer
has comment: http://stackoverflow.com/comment/83978591
has comment: http://stackoverflow.com/comment/83997389
score: 1
has body: OpenCV has a tutorial dealing with removing a grid from an image: "Extract horizontal and vertical lines by using morphological operations", OpenCV documentation. Source: Extract horizontal and vertical lines by using morphological operations
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48600929
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/89232081
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89164506
upvote count: 1
has comment: http://stackoverflow.com/comment/89231924
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-slim
accepted answer: http://stackoverflow.com/a/48747898
has body: I'd like to extend this script such that it is able to evaluate the top-k accuracies per class. I hope it boils down to adding a metric to the following code snippet: # Define the metrics: names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ 'Accuracy': slim.metrics.streaming_accuracy(predictions, labels), 'Recall_5': slim.metrics.streaming_recall_at_k( logits, labels, 5), }) I already followed this comment to add the confusion matrix, which allows me to calculate the top1 in-class accuracies. However, I'm not sure how to get the top-k values as I can't find an appropriate slim metric. To clarify: I'm not looking for the average top-k accuracy, but the per class values. I'm able to implement the required calculations using basic tensors, but I'm new to the slim interface and don't know how to do it using the above script.
linked to: http://stackoverflow.com/q/44799516
has title: How to calculate top-k in-class accuracies using TensorFlow Slim metrics
has answer: http://stackoverflow.com/a/48747898
tagged with: neural-network
has comment: http://stackoverflow.com/comment/89231852
tagged with: python
has comment: http://stackoverflow.com/comment/89266789
type: AnsweredQuestion

http://stackoverflow.com/q/48488939
answer count: 1
tagged with: python
tagged with: integration
has body: I've been trying to plot a graph of the 1d, horizontal diffraction pattern and have written the following code: import math import cmath import numpy as np import matplotlib.pyplot as plt lamda=0.2 k=(2*math.pi)/lamda z=0.005 def expfunc(x,xp): return cmath.exp(1j*k*((x-xp)**2)/(2*z)) def X(xp1,xp2,x,xp,expfunc,N): h=(xp2-xp1)/N y=0.0 for i in np.arange(1, N/2 +1): #summing odd order y terms y+=4*expfunc(x,xp) xp+=2*h xp=xp1+2*h for i in np.arange(0, N/2): #summing even order y terms y+=2*expfunc(x,xp) xp+=2*h integral= (h/3)*(y+expfunc(x, xp1)+expfunc(x, xp2)) integral= (integral.real)**2 return integral NumPoints = 90000 xmin = 0 xmax =20 dx = (xmax - xmin) / (NumPoints - 1) xvals = [0.0] * NumPoints yvals = np.zeros(NumPoints) for i in range(NumPoints): xvals[i] = xmin + i * dx yvals[i] = X(xmin,xmax,xvals[i],0.1,expfunc,200) plt.plot(xvals,yvals) plt.show() The graph is meant to be a sinc function, however the graph I get is all over the place when I vary the parameters N, the number of intervals, and z, the distance from the screen. I fail to see what is wrong with my code Thanks
score: 0
has title: Code produces inaccurate graph for fresnel diffraction
has answer: http://stackoverflow.com/a/48489114
type: Question
tagged with: graph
type: UnansweredQuestion

http://stackoverflow.com/a/48580207
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48577398
type: Answer
has body: import pythoncom import win32com.client pythoncom.CoInitialize() h = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1') h.SetAutoLogonPolicy(0) # log in automatically h.Open('POST', url, True) h.SetRequestHeaders(Your_Headers) h.Send("{"Id":"8974552","Action":"Analysis"}")

http://stackoverflow.com/a/48520491
answers question: http://stackoverflow.com/q/48520369
downvote count: 0
has body: I don't see any trouble in your code, you get 6 because you are calling input, but if you call calculator with that result: In [2]: input(2,2,2) Out[2]: 6 In [3]: calculator(6) 36
upvote count: 1
score: 1
type: Answer

masked-array
tags question: http://stackoverflow.com/q/48531571
tag name: masked-array
type: Tag

http://stackoverflow.com/comment/84173420
type: AnswerComment
has text: I found other questions with a similar topic. Maybe they help you https://stackoverflow.com/questions/3674409/how-to-split-partition-a-dataset-into-training-and-test-datasets-for-e-g-cros https://stackoverflow.com/questions/39622639/how-to-break-numpy-array-into-smaller-chunks-batches-then-iterate-through-them https://stackoverflow.com/questions/48535829/how-do-i-find-the-euclidean-distances-between-rows-of-my-test-and-train-set-effi
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48536000

http://stackoverflow.com/comment/84185155
score: 0
type: Comment
type: QuestionComment
has text: @MarkRansom thanks for correcting me, I've deleted my comment to avoid spreading misinformation. TimHamilton You might want to update your question with the changes for readability.
comment on: http://stackoverflow.com/q/48593614

http://stackoverflow.com/comment/84145489
comment on: http://stackoverflow.com/q/48565703
type: QuestionComment
score: 0
has text: @three_pineapples I apologise for my poor exolanation, I was trying to shorten the code so I does not take much spase, but it wasn’t a good idea. The error is still showing, though it is a ‘Type error’ now I have updated the code, I hope it is a bit clearer now.
type: Comment

http://stackoverflow.com/comment/84149318
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48552899
has text: i see, it make sense. thank you so much for the help and ideas.
score: 0

http://stackoverflow.com/q/48521208
tagged with: nltk
has comment: http://stackoverflow.com/comment/84037704
has comment: http://stackoverflow.com/comment/84037102
accepted answer: http://stackoverflow.com/a/48521532
has comment: http://stackoverflow.com/comment/84037032
has title: NLTK | Sentiment Classifier | Issues with Install
has comment: http://stackoverflow.com/comment/84037644
has body: I am having trouble installing the sentiment_classifier. What I have currently done: pip install sentiment_classifier python setup.py install Downloaded sentiment_classifier-0.5.tar.gz Placed the package into my directory Error in shell: pip install sentiment_classifier: Requirement already satisfied: sentiment_classifier in c:\users\ac\anaconda3\lib\site-packages Requirement already satisfied: numpy in c:\users\ac\anaconda3\lib\site-packages (from sentiment_classifier) Requirement already satisfied: nltk in c:\users\ac\anaconda3\lib\site-packages (from sentiment_classifier) Requirement already satisfied: argparse in c:\users\ac\anaconda3\lib\site-packages (from sentiment_classifie ) python setup.py install - C:\Users\AC\Anaconda3\python.exe: can't open file 'setup.py': [Errno 2] No such file or directory When I call it in Jupyter Notebook: from senti_classifier import senti_classifier I get: FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\AC\Anaconda3\lib\site-packages\senti_classifier\data\SentiWn.p' Any help would be greatly appreciated. Docs I've been referring to: https://pypi.python.org/pypi/sentiment_classifier Sentiment Analysis using senti_classifier and NLTK https://github.com/kevincobain2000/sentiment_classifier http://pythonhosted.org/sentiment_classifier/ Any help would be greatly appreciated.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48521532
score: 0
tagged with: sentiment-analysis
has comment: http://stackoverflow.com/comment/84037021
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84036977
has comment: http://stackoverflow.com/comment/84037590
linked to: http://stackoverflow.com/q/41795476
type: Question
has comment: http://stackoverflow.com/comment/84037458
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84037300

http://stackoverflow.com/q/48528848
has answer: http://stackoverflow.com/a/48529000
has comment: http://stackoverflow.com/comment/84052841
downvote count: 7
has comment: http://stackoverflow.com/comment/84052827
has comment: http://stackoverflow.com/comment/84052835
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84053573
upvote count: 0
type: UnansweredQuestion
has body: For example print() or a random variable like draw(). Thank you for your time and help.
has comment: http://stackoverflow.com/comment/84052882
tagged with: python
score: -7
has comment: http://stackoverflow.com/comment/84052867
has title: In Python what does putting a variable or command next to a empty () do?
answer count: 1

http://stackoverflow.com/a/48570552
type: AcceptedAnswer
has body: Figured out the issue with one of my co-worker's help. The problem was that of those 15 pending tasks, the tasks that are at the lowest level demand a bit of CPU resources (10 cores). However, I wasn't passing any luigi resource parameter when I launched my workflow. So even though there were tasks to run, luigi wasn't considering any of those as run-eligible because of lack of resources. Passing a resource parameter of {"cpu_cores": 10} solved my issue. Could also be done via luigi's configuration file like the following: [resources] cpu_cores=10
answers question: http://stackoverflow.com/q/48567122
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48567122
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84001609
has text: Thanks, good suggestion! I did this and found that when I use 1 worker (that uses 8 cores), or 2 workers (using 8 or 4 cores each) this error doesn't occur. But it does come back when I set up 8 workers each with access to only 1 core. Using: `dask-worker tcp://localhost:8786 --nthreads 1`, and returns the exact same warning, but to the console of the worker, and gives the error: distributed.nanny - WARNING - Worker process 18843 was killed by unknown signal. I'll play around some more, maybe something on my machine is killing processes because I'm trying to use all my cores fully.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48501990
score: 0

http://stackoverflow.com/a/48543114
type: Answer
answers question: http://stackoverflow.com/q/48543042
downvote count: 0
has body: Given you have these two lists, we can construct a tuple as follows: our_submatrix = a[tuple(map(slice, ij_ul, ij_lr))] Here we iterate over the two iterables ij_ul and ij_lr concurrently, and we construct slice(..) objects (if you write i:j you actually construct such object behind the curtains). So what we do here is constructing a tuple of slices, and we can pass this to a to construct a view with the specified slices. For example: &gt;&gt;&gt; A = np.random.randn(5, 7) &gt;&gt;&gt; A array([[-0.41526531, 0.88895983, 1.25061578, -0.01930474, 0.90183725, 0.169831 , -0.67271614], [ 0.26148559, -1.24269541, 0.72472787, -2.75687495, -0.64511098, -1.5535446 , 0.74714421], [ 0.8423359 , 0.26620621, 0.26581058, -1.20667371, 0.60521744, 2.02856815, -0.43339106], [ 0.29617257, 1.86195973, -1.33591589, 0.97233933, -0.69254736, -0.31652783, 0.78613453], [-0.93928881, 0.26735583, -0.27057705, 0.78084479, -0.76763169, 0.12574734, -1.88236193]]) &gt;&gt;&gt; A[tuple(map(slice, ij_ul, ij_lr))] array([[-1.24269541, 0.72472787], [ 0.26620621, 0.26581058], [ 1.86195973, -1.33591589]])
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48543042
score: 1

http://stackoverflow.com/a/54586536
upvote count: 10
answers question: http://stackoverflow.com/q/48589633
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48589633
score: 10
type: Answer
has body: It it not possible to modify the DAG during its execution (without a lot more work). The dag = DAG(... is picked up in a loop by the scheduler. It will have task instance 'python_operator' in it. That task instance gets scheduled in a dag run, and executed by a worker or executor. Since DAG models in the Airflow DB are only updated by the scheduler these added dummy tasks will not be persisted to the DAG nor scheduled to run. They will be forgotten when the worker exits. Unless you copy all the code from the scheduler regarding persisting &amp; updating the model… but that will be undone the next time the scheduler visits the DAG file for parsing, which could be happening once a minute, once a second or faster depending how many other DAG files there are to parse. Airflow actually wants each DAG to approximately stay the same layout between runs. It also wants to reload/parse DAG files constantly. So though you could make a DAG file that on each run determines the tasks dynamically based on some external data (preferably cached in a file or pyc module, not network I/O like a DB lookup, you'll slow down the whole scheduling loop for all the DAGs) it's not a good plan as your graph and tree view will get all confusing, and your scheduler parsing will be more taxed by that lookup. You could make the callable run each task… def make_tasks(context): du1 = DummyOperator(task_id='dummy1', dag=dag) du2 = DummyOperator(task_id='dummy2', dag=dag) du3 = DummyOperator(task_id='dummy3', dag=dag) du1.execute(context) du2.execute(context) du3.execute(context) p = PythonOperator( provides_context=true, But that's sequential, and you have to work out how to use python to make them parallel (use futures?) and if any raise an exception the whole task fails. Also it is bound to one executor or worker so not using airflow's task distribution (kubernetes, mesos, celery). The other way to work with this is to add a fixed number of tasks (the maximal number), and use the callable(s) to sho…

http://stackoverflow.com/comment/84213510
comment on: http://stackoverflow.com/a/48608341
type: Comment
score: 0
type: AnswerComment
has text: what I was doing wrong here? You have also done the same thing but your line is the best fit but mine is not.

http://stackoverflow.com/comment/84018022
has text: its $sudo apt-get install python-mysqldb for python 2.7. For python3 $sudo apt-get install python3-mysqldb. Or pip equivalents but search with the word `mysqldb`. My typo to miss-out on the 'db' letters.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48511225
type: AnswerComment

http://stackoverflow.com/comment/84261313
has text: I think the `--pdb` option is what you are looking for: `pytest.main(['--pdb'])`. When provided, `pytest` will drop to the debugger when an unhandled error is raised in test body. You can also provide a custom debugger impl - this is what decent IDEs usually do (confirmed with PyCharm and Wing IDE). If yours does not, check what debugger it uses and configure the `pytest` invocation so the debugger is passed via `pdbcls` arg.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48618905
type: QuestionComment

http://stackoverflow.com/a/48541873
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84080047
has body: The python API has an element attribute that causes the desired element to be scrolled into view. I assume it would still work even though there is custom scrolling on the page. The first step is to get the locator of the element you want scrolled into view. It sounds like you have that. Let's call it [element]. Next, if you have verified it exists on the page, then do: coordinates = [element].location_once_scrolled_into_view Even thought you may not care about the coordinates, this command will cause the target to be scrolled into view. Selenium Python Element API.
type: Answer
accepted answer of: http://stackoverflow.com/q/48540994
answers question: http://stackoverflow.com/q/48540994

http://stackoverflow.com/comment/84191420
has text: @Nisrag I'm glad I could help, I'm fairly new to python as well, there aren't many questions I can answer, but I find helping others solve their problems to be a great learning experience :)
type: Comment
comment on: http://stackoverflow.com/a/48595999
score: 0
type: AnswerComment

http://stackoverflow.com/a/49181839
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48552918
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48552918
downvote count: 0
has body: I ended up solving my predicament by first reading the original JSON into a string. There, I would make the string go through a sanitizing method that would remove escape characters and would replace 'damaged' characters for their original special characters.

http://stackoverflow.com/a/48566288
type: AcceptedAnswer
has body: The logic is most likely angle from origo to point. This can be calculated easily with np.arctan2(X, Y). I don't know which colormap that is used in your example but you can probably find it here: https://matplotlib.org/examples/color/colormaps_reference.html Use the angles of the points to the c keyword in plt.scatter To get something similar to your example: plt.scatter(X,Y, c=np.arctan2(X, Y), cmap='rainbow', s=50, alpha=0.8)
answers question: http://stackoverflow.com/q/48565924
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48565924
downvote count: 0

http://stackoverflow.com/q/48585330
has answer: http://stackoverflow.com/a/48585535
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84167763
tagged with: nltk
score: -2
has body: I have some news headlines and I would like to extract the name of the company involved in the headline. Here is an example headlines = [ "Chicago Policemen's Annuity &amp; Benefit Fund hired Chicago Equity Partners to manage $50 million in active U.S. smidcap value equity.", "Belmont Contributory Retirement System is searching for at least one U.S. small-cap equity manager to run initially up to $5 million.", "Phoenix Employees' Deferred Compensation Board will begin a search for an investment consultant before the end of February." ] As you can see, the pattern here is that the company name of interest is the first chain of capitalized words. The second chain of capitalized words is the secondary company. In our example, I want to return two variables all related to extracting the consecutive capitalized letters. So, it would return "Chicago Policemen's Annuity &amp; Benefit Fund", "Belmont Contributory Retirement System", and "Phoenix Employees' Deferred Compensation Board" Is there a way to do this extraction with regular expressions in Python?
has comment: http://stackoverflow.com/comment/84167790
tagged with: python
tagged with: regex
has title: Python RgEx: Extract First Consecutive Capitalized Letters
has comment: http://stackoverflow.com/comment/84167596
has answer: http://stackoverflow.com/a/48586030
answer count: 3
has comment: http://stackoverflow.com/comment/84167448
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/84167609
has comment: http://stackoverflow.com/comment/84168063
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84167565
has answer: http://stackoverflow.com/a/48585604
has comment: http://stackoverflow.com/comment/84167460
linked to: http://stackoverflow.com/q/4113051

http://stackoverflow.com/comment/89232081
comment on: http://stackoverflow.com/q/48600929
type: Comment
type: QuestionComment
score: 0
has text: You can also have a look at [this question](https://stackoverflow.com/questions/44799516/tensorflow-is-there-a-metric-to-calculate-and-update-top-k-accuracy?rq=1).

http://stackoverflow.com/comment/84137224
score: 0
type: AnswerComment
type: Comment
has text: And adding of params is available?
comment on: http://stackoverflow.com/a/48529373

http://stackoverflow.com/q/48581090
has answer: http://stackoverflow.com/a/51677823
downvote count: 0
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/68956894
favorite count: 0
has answer: http://stackoverflow.com/a/51678318
has answer: http://stackoverflow.com/a/51678999
tagged with: selenium
answer count: 4
type: Question
upvote count: 4
tagged with: selenium-chromedriver
type: UnansweredQuestion
has body: Is there any possibility to run Python + Selenium script without entering the path of an exe file in every single script in Python line: driver = webdriver.Chrome(). The same question applies to "IE Driver", "Edge Driver" and "Gecko Driver". Can it be done by some general python class and should I create some additional file for it? Or is it a matter of Integrated Development Environment configuration? I would be grateful for your expert word.
has title: Python + Selenium: Path to driver

http://stackoverflow.com/comment/84171622
has text: @Caterpillaraoz, when doing a resampling you must decide what values do you want to pick from within each interval (5 minutes in your case) - first / last / min / max / mean / any random value...
comment on: http://stackoverflow.com/q/48583248
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84186776
score: 0
comment on: http://stackoverflow.com/a/48593747
type: AnswerComment
has text: Well said, @ShadowRanger
type: Comment

http://stackoverflow.com/a/48612851
accepted answer of: http://stackoverflow.com/q/48611376
answers question: http://stackoverflow.com/q/48611376
type: Answer
has comment: http://stackoverflow.com/comment/84222564
has comment: http://stackoverflow.com/comment/84222572
score: 1
has comment: http://stackoverflow.com/comment/84222444
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Just to show you an example of how one could achieve what you want. Let's assume that we have two inputs: input_1 = Input(shape=(2,)) input_2 = Input(shape=(3,)) Now - let's define the following function: def custom_multiply(list_): x, y = list_[0], list_[1] y = K.reshape(y, (-1, 1, 3)) # (1, 2, 3) -&gt; ((1), (2), (3)) x = K.reshape(x, (-1, 2, 1)) # (1, 2) -&gt; ((1, 2)) partial_result = K.batch_dot(x, y) return K.reshape(partial_result, (-1, 6)) Now - output = custom_multiply([input_1, input_2]) should do what you've expected. Called on a pair [(1, 2), (3, 4, 5)] should return (3, 4, 5, 6, 8, 10).

http://stackoverflow.com/comment/84243882
type: QuestionComment
comment on: http://stackoverflow.com/q/48623456
score: 0
has text: I'm eventually going to expand the code. As it stands, yes, but in the future I'll only cancel the loop when I've detected that multiple different sites have updated.
type: Comment

http://stackoverflow.com/q/48595792
score: -1
duplicate of: http://stackoverflow.com/q/25951968
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84194335
has answer: http://stackoverflow.com/a/48596079
downvote count: 2
has comment: http://stackoverflow.com/comment/84188498
answer count: 1
tagged with: selenium
upvote count: 1
has title: Selenium Multitab issue
accepted answer: http://stackoverflow.com/a/48596079
favorite count: 0
type: Question
has body: I have an issue in selenium. With my code I should be able to click on an image and wait 3 seconds. In this process it opens several tabs. I don't know how to close these tabs. This is my code: from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome(executable_path=".\chromedriver.exe") # links = ["http://activeation.com/4W79", "http://activeation.com/4W89", "http://activeation.com/36ky", "http://activeation.com/36X5", "http://activeation.com/38QK", "http://activeation.com/4VdE", "http://activeation.com/4Vwm", "http://activeation.com/4Vxi", "http://activeation.com/4VyU", "http://activeation.com/4Vza", "http://activeation.com/4W0T"] while True: for link in links: driver.get(link) time.sleep(6) element = driver.find_element_by_id("skip_bu2tton") actionchains = ActionChains(driver) actionchains.double_click(element).perform() time.sleep(3)
linked to: http://stackoverflow.com/q/25951968
tagged with: python

http://stackoverflow.com/comment/84058480
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48514422
score: 0
has text: Bring your code to the data, not the other way around. Can SQL and/or JavaScript (UDF) do the job for you?

http://stackoverflow.com/comment/84092658
type: QuestionComment
type: Comment
score: 0
has text: @Ancient can you provide the output from those commands (in a screenshot or some other link)?
comment on: http://stackoverflow.com/q/48544236

http://stackoverflow.com/a/48505865
type: Answer
answers question: http://stackoverflow.com/q/48505405
has comment: http://stackoverflow.com/comment/84010950
score: 0
has comment: http://stackoverflow.com/comment/84006980
has comment: http://stackoverflow.com/comment/84008452
has comment: http://stackoverflow.com/comment/84006851
has body: Any time a page transition occurs, or a new element is expected to appear, you should wait for it to exist in the DOM. If you don't, you'll get frequent timeouts. In your case, try the following... from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC browser=webdriver.Firefox() browser.get('https://runningstatus.in') i=0 element = WebDriverWait(browser, 10) select=Select(browser.find_element_by_id('godate')) select.select_by_index(i) browser.find_element_by_tag_name('input').send_keys('12801',Keys.RETURN) css = 'div.runningstatus-widget-content' x = WebDriverWait(browser, 30).until( EC.element_to_be_clickable(('css selector', css))) print x.text
has comment: http://stackoverflow.com/comment/84006460

http://stackoverflow.com/comment/84089230
type: Comment
type: QuestionComment
score: 0
has text: @Aaron I don't have solution yet.
comment on: http://stackoverflow.com/q/48546662

http://stackoverflow.com/comment/84042722
has text: You can also add a statement like `if ( message==null) message="omg message is null"`. Place it before the log statement.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48521184

http://stackoverflow.com/q/48572629
accepted answer: http://stackoverflow.com/a/48572715
has answer: http://stackoverflow.com/a/48572711
tagged with: setup.py
has comment: http://stackoverflow.com/comment/84142198
upvote count: 2
has answer: http://stackoverflow.com/a/48572952
linked to: http://stackoverflow.com/q/20309456
tagged with: makefile
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84154914
has comment: http://stackoverflow.com/comment/84142680
has comment: http://stackoverflow.com/comment/84144817
downvote count: 2
has answer: http://stackoverflow.com/a/48572715
has body: In C/C++ we write a makefile for a project installation/execution. How do we create a makefile or equivalent for a python project? If python is a scripting language and we don't need a makefile. How do we integrate a python project with multiple python files (.py files)? There is another thread with a similar question Call a function from another file in Python. But my question is different from the one asked in that thread. One solution of my question may be possible by calling a function from another file. But I wanted a better solution as described by the Simon.
has answer: http://stackoverflow.com/a/48572827
tagged with: unix
has comment: http://stackoverflow.com/comment/84142603
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48572711
tagged with: linux
has title: Substitute of the makefile for integrating mulitple python files for a python project

http://stackoverflow.com/comment/84021613
type: QuestionComment
comment on: http://stackoverflow.com/q/48513337
score: 0
has text: All of those commands on the README are for Mac/Linux. You would need to replace all the variable substitutions for Windows equivalents, which has nothing to do with Python
type: Comment

http://stackoverflow.com/comment/84117070
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48527321
score: 0
has text: @VivekKumar Thank you! It's a very useful remark.

http://stackoverflow.com/comment/84121890
score: 1
comment on: http://stackoverflow.com/a/48562980
type: Comment
has text: That's true enough, but I don't want to hear the word "clear" from someone who just did `0 .__ne__`. ;-)
type: AnswerComment

http://stackoverflow.com/q/48629695
has answer: http://stackoverflow.com/a/48630006
linked to: http://stackoverflow.com/q/22842289
has title: How to generate unique random numbers (that don't repeat)?
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48629803
has comment: http://stackoverflow.com/comment/125164818
has comment: http://stackoverflow.com/comment/84256364
has answer: http://stackoverflow.com/a/48629792
has comment: http://stackoverflow.com/comment/84256456
has comment: http://stackoverflow.com/comment/84256338
tagged with: python
has body: I'm trying to write a code that randomly chooses numbers and adds them to the list random_numbers, but if a random number was already generated, the code detects that and replaces the number with another, until every number is different. import random random_numbers = [] for x in range(11): This part generates a random integer and appends it to the list random_numbers: random_numbers.append('[q' + str(random.randint(1, 11)) + ']') This part is supposed to iterate over the list and check if the random number generated was already generated, and replace it: for item in range(len(random_numbers)): if random_numbers[x] == random_numbers[item]: random_numbers[x] = '[q' + str(random.randint(1, num_of_qs_in_file)) + ']' print(random_numbers) The output varies, but almost always the list has the same integer more than once. Can anybody help?
has comment: http://stackoverflow.com/comment/84256334
has comment: http://stackoverflow.com/comment/84256332
linked to: http://stackoverflow.com/q/196017
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84256704
tagged with: random
possible better answer: http://stackoverflow.com/a/48630006
answer count: 3
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84256549
has answer: http://stackoverflow.com/a/48629803
upvote count: 3

http://stackoverflow.com/comment/83990473
type: Comment
comment on: http://stackoverflow.com/q/48498087
type: QuestionComment
has text: you can't get there from here: you can't use subqueries with execute_values.
score: 1

http://stackoverflow.com/q/48621111
has comment: http://stackoverflow.com/comment/84238855
has answer: http://stackoverflow.com/a/48621495
type: UnansweredQuestion
tagged with: python
has title: How to fill array from index to another index in Python
has comment: http://stackoverflow.com/comment/84238697
has body: How to fill an array from on index let's say 3 to 5 in an array containing 10 element without a for loop? Input: [0,5,8,4,6,7,5,1,3,0] Output: [0,5,8,'replaced','replaced','replaced',5,1,3,0]
answer count: 3
has answer: http://stackoverflow.com/a/48621189
score: 0
has comment: http://stackoverflow.com/comment/84238785
tagged with: arrays
has answer: http://stackoverflow.com/a/48621380
type: Question

http://stackoverflow.com/comment/84076449
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48540442
type: QuestionComment
has text: If you are getting "data is not defined" error then this has nothing to do with reading a file. You need to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve).

http://stackoverflow.com/q/48534047
has title: Django urls help - not able to access view
favorite count: 0
accepted answer: http://stackoverflow.com/a/48550900
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/48550900
has body: Let me start by saying I'm new to Django and I realize this seems simple (and I'm hoping it is). I'm following a tutorial that is taking me through the basic set up of a simple Django site, and I've found myself stuck at a point where I'm simply calling on a new view the tutorial just had me add. (for those interested, the tutorial is here https://overiq.com/django/1.10/views-and-urlconfs-in-django/) So, I've got my server up and running, and I'm trying to access http://127.0.0.1:8000/blog/time/ When I try to access that view, I get the error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^blog ^time/$ [name='todays_time'] ^blog ^$ [name='blog_index'] ^admin/ The current path, blog/time/, didn't match any of these. Here is the layout of my Django project: My mysite's urls.py file looks like this: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^blog/', include('blog.urls')), url(r'^admin/', admin.site.urls), ] My blog package's urls.py file looks like this: from django.conf.urls import url from blog import views urlpatterns = [ url(r'^time/$', views.today_is, name='todays_time'), url(r'^$', views.index, name='blog_index'), ] my blog package's views.py looks like this: from django.http import HttpResponse import datetime def index(request): return HttpResponse("Hello Django!!!") def today_is(request): now = datetime.datetime.now() html = ''' &lt;html&gt; &lt;body&gt; Current date and time: {0} &lt;/body&gt; &lt;/html&gt; '''.format(now) return HttpResponse(html) I can successfully go to http://127.0.0.1:8000/blog and see the response from index() as "Hello Django!!!" in my browser. So with that I was expecting http://127.0.0.1:8000/blog/time/ to work just fine, but it doesn't, and attempting to view that is what yields the error I shared above. Can anyone point me in the right direction here? I'd appreciate it! Thanks, everyone! NOTE: I can provide more details, screen grabs,…
has comment: http://stackoverflow.com/comment/84063704
has comment: http://stackoverflow.com/comment/84070206
has answer: http://stackoverflow.com/a/53200336
tagged with: django
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/84064153
has answer: http://stackoverflow.com/a/48535970
type: AnsweredQuestion
tagged with: django-views
answer count: 3
downvote count: 0
tagged with: django-urls
possible better answer: http://stackoverflow.com/a/48535970

http://stackoverflow.com/comment/84095909
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48549256
has text: Can you post a link to the file, some lines from it, or an example of the "garbage" that pandas gives you?
score: 0

http://stackoverflow.com/a/48613281
answers question: http://stackoverflow.com/q/48503812
downvote count: 0
has body: You can use a context manager to automatically pep8ify the symbols from an imported module like: Example: with Pep8Importer(): import funky Code: class Pep8Importer(object): @staticmethod def _pep8ify(name): """PEP8ify name""" import re s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def __enter__(self): # get list of current modules in namespace self.orig_names = set(dir(sys.modules[__name__])) def __exit__(self, exc_type, exc_val, exc_tb): """ Pep8ify names in any new modules Diff list of current module names in namespace. pep8ify names at the first level in those modules Ignore any other new names under the assumption that they were imported/created with the name as desired. """ if exc_type is not None: return new_names = set(dir(sys.modules[__name__])) - self.orig_names for module_name in (n for n in new_names if not n.startswith('_')): module = sys.modules[module_name] for name in dir(module): pep8ified = self._pep8ify(name) if pep8ified != name and not name.startswith('_'): setattr(module, pep8ified, getattr(module, name)) print("In mModule: {}, added '{}' from '{}'".format( module_name, pep8ified, name)) Test Code: with Pep8Importer(): import funky print(funky.thisIsABase_function) print(funky.this_is_a_base_function) funky.py thisIsABase_function = 1 Results: In module: funky, added 'this_is_a_base_function' from 'thisIsABase_function' 1 1
upvote count: 6
score: 6
type: Answer

http://stackoverflow.com/q/48569965
has comment: http://stackoverflow.com/comment/84136745
accepted answer: http://stackoverflow.com/a/48570378
downvote count: 5
has comment: http://stackoverflow.com/comment/84136733
tagged with: python
tagged with: uid
has comment: http://stackoverflow.com/comment/84136930
has answer: http://stackoverflow.com/a/48570378
has comment: http://stackoverflow.com/comment/84136305
has title: Comparing two multi-dimensional array in python
score: -4
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/84136335
has comment: http://stackoverflow.com/comment/84136460
has comment: http://stackoverflow.com/comment/84136602
upvote count: 1
has body: My lists looks like this (those numbers are UIDS): sysusers = [['user1'],[7972], ['user2'],[2121], ['hacker'],[2132] ['hacker2'],[1232]] users = [['user1'],[7972], ['user2'],[2121]] I want to take the difference of those two lists and output it in a list similar to this: badusers = [hacker, hacker2]
has comment: http://stackoverflow.com/comment/84136758
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84136263
has comment: http://stackoverflow.com/comment/84136657
has comment: http://stackoverflow.com/comment/84136241
type: AnsweredQuestion

http://stackoverflow.com/comment/84174721
type: AnswerComment
has text: Selecting with tuple should work according to http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers. Strangely the list conversion indeed solves the issue though...
comment on: http://stackoverflow.com/a/48588623
type: Comment
score: 0

http://stackoverflow.com/comment/84147368
type: QuestionComment
comment on: http://stackoverflow.com/q/48575336
type: Comment
score: 0
has text: I don't see any difference between platform archiver and Python zipfile. What exactly doesn't work with the file?

http://stackoverflow.com/q/48611517
tagged with: python-3.x
tagged with: opencv
type: AnsweredQuestion
has title: Raspberry Pi 3 Python and OpenCV Face Recognition from Network Camera Stream
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/84223440
score: 1
accepted answer: http://stackoverflow.com/a/48675107
linked to: http://stackoverflow.com/q/35166111
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/84223212
has comment: http://stackoverflow.com/comment/84223245
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48675107
answer count: 1
has comment: http://stackoverflow.com/comment/84222561
has body: I'm attempting to stream video over a WiFi network using a raspberry pi model 3 and the camera module but have come across some inconsistencies from other examples I have found online. I'm attempting to achieve the results of the 3rd test performed in this video: https://www.youtube.com/watch?v=sYGdge3T30o I can see the data being streamed over the network and into the fifo264 file that is created, I also have a functioning python script that operates for a few minutes before the video feed can no longer be processed. The video that is displayed on the OS X machine eventually crashes. I'm not sure if my problem exists within how I'm generating and sending the video (From the Raspberry Pi side), or with how I'm consuming the video with python and processing it. I'm attempting to determine platform differences that can be contributing to my problems, this question focuses mkfifo and netcat permissions and possible differences between how these programs behave across platforms. This bash script is being used on OS X 10.12.6. I'm attempting to listen on port 777 for the feed that is being created and sent to this machine. #!/bin/bash if [ -p fifo264 ] then rm fifo264 fi mkfifo fifo264 nc -l -v 777 &gt; fifo264 When the above script is executed ./makeFifo.sh the pipe fifo264 is created in the working directory and it inherits the user permissions of the user. sudo ./makeFifo.sh results in ls -l as prw-r--r-- 1 root staff 0 Feb 4 12:12 fifo264 AND ./makeFifo.sh results in ls -l as prw-r--r-- 1 user staff 0 Feb 4 12:12 fifo264 I've also altered the bash script to supply a -m 0777 with mkfifo result mkfifo -m 0777 fifo264. The pipe is created with the appropriate permissions, but netcat fails to establish an open 777/tcp open multiling-http. I'm running nmap -sS -O localhost to test. Results are the same if I use the machines ip address. If I do not use the bash script to create a pipe and execute netcat to listen on port 777 from the command line, I can get netcat to creat…
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/84222690
favorite count: 0

http://stackoverflow.com/a/48564757
type: Answer
score: 0
has body: You can do this like this: with open(fname) as fh: unique_words = set(f.read().split()) To move that set into list use: unique_words = list(unique_words) and to sort that list: unique_words.sort()
answers question: http://stackoverflow.com/q/48564565

http://stackoverflow.com/q/48491984
has comment: http://stackoverflow.com/comment/83977148
has body: I am trying to graph a fuction using matplotlib in Jupyter notebooks in python. My code is below. I don't understand why I am getting the error message, which refers to the line with the formula in it y = ... Here is my code: d = [ ] e = [ ] for x in range(-4, 4, 1): y= -16(x**2)+20(x)+50 d.append(x) e.append(y) fig= plt.figure() axes=fig.add_subplot(111) axes.plot(d,e) plt.show()
answer count: 3
has answer: http://stackoverflow.com/a/48492046
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83977263
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48492013
has comment: http://stackoverflow.com/comment/83977150
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/32478298
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/83977146
has comment: http://stackoverflow.com/comment/83977187
has answer: http://stackoverflow.com/a/48492027
has title: Int object is not callable error

http://stackoverflow.com/comment/84024266
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48514930
score: 1
has text: why `alpha` and this much loops are using while `chr(), ord() and zip `are available in python ?

http://stackoverflow.com/q/48501222
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: libvirt
has title: libvirt-python 4.0.0 missing method
has comment: http://stackoverflow.com/comment/83997350
score: 1
has body: I need to listen for storage pool events using libvirt-python but the storagePoolEventRegisterAny method is not present when installing with pip (pip install 'libvirt-python==4.0.0') or even when building/installing from the repo I'm not an experienced python developer(~1 month) so maybe there's something that i miss about the way that libvirt-python is installed/configured ?! On Ubuntu 16.04 connection = libvirt.openReadOnly("qemu+tcp://&lt;ip&gt;/system") connection.storagePoolEventRegisterAny(...) plus the appropriate event loop
favorite count: 0
type: Question

http://stackoverflow.com/a/48597969
has comment: http://stackoverflow.com/comment/84192912
type: AcceptedAnswer
downvote count: 0
has body: Let pandas to parse dates, but then some days with months should be swapped: df['accepted_date'] = pd.to_datetime(df['accepted_date']) So better is use to_datetime with format and parameter errors='coerce', what return only matched datetimes with NaT for non matched. Last use combine_first for join all Series - NaT are replaced by values from another Series: df = pd.DataFrame({'accepted_date':['2017-01-02','07-08-2017','20-03-2017','2017-01-04']}) d1 = pd.to_datetime(df['accepted_date'], format='%d-%m-%Y', errors='coerce') d2 = pd.to_datetime(df['accepted_date'], format='%Y-%m-%d', errors='coerce') df['accepted_date1'] = d1.combine_first(d2) df['accepted_date2'] = pd.to_datetime(df['accepted_date']) print (df) accepted_date accepted_date1 accepted_date2 0 2017-01-02 2017-01-02 2017-01-02 1 07-08-2017 2017-08-07 2017-07-08 &lt;-swapped dd-mm 2 20-03-2017 2017-03-20 2017-03-20 3 2017-01-04 2017-01-04 2017-01-04 Detail: print (d1) 0 NaT 1 2017-08-07 2 2017-03-20 3 NaT Name: accepted_date, dtype: datetime64[ns] print (d2) 0 2017-01-02 1 NaT 2 NaT 3 2017-01-04 Name: accepted_date, dtype: datetime64[ns] EDIT: Another solution is use parameter dayfirst=True: df['accepted_date3'] = pd.to_datetime(df['accepted_date'], dayfirst=True) print (df) accepted_date accepted_date3 0 2017-01-02 2017-01-02 1 07-08-2017 2017-08-07 2 20-03-2017 2017-03-20 3 2017-01-04 2017-01-04
answers question: http://stackoverflow.com/q/48597947
has comment: http://stackoverflow.com/comment/84192928
accepted answer of: http://stackoverflow.com/q/48597947
type: Answer
score: 6
upvote count: 6

http://stackoverflow.com/a/48492788
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83978764
has comment: http://stackoverflow.com/comment/83978751
answers question: http://stackoverflow.com/q/48492727
has body: .jpg is not supported by default by tkinter. You can use .jpg files using PIL: try: # In order to be able to import tkinter for import tkinter as tk # either in python 2 or in python 3 except: import Tkinter as tk from PIL import Image, ImageTk if __name__ == '__main__': root = tk.Tk() label = tk.Label(root) img = Image.open(r"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg") label.img = ImageTk.PhotoImage(img) label['image'] = label.img label.pack() root.mainloop()
score: 10
has comment: http://stackoverflow.com/comment/83978721
upvote count: 10

http://stackoverflow.com/comment/84227446
type: Comment
has text: Yes I know, but it occurs in a strange place. Before I change the batch_size to placeholder, everything works well. But after changing, the error above occurs in some network-building codes, which worked well before.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48593585

http://stackoverflow.com/comment/92466559
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48526580
has text: Did you get any solution to this problem? I am facing the same issue and I can see the binary value when debugging but it gives EOFError when using pickle.loads

http://stackoverflow.com/q/48562887
type: Question
has answer: http://stackoverflow.com/a/48563710
score: 0
tagged with: spacy
type: UnansweredQuestion
answer count: 1
has body: I am now getting the undefined symbol: PyFPE_jbuf when trying import spacy on an Ubuntu 17.10. >>> import spacy Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/spacy/__init__.py", line 4, in <module> from .cli.info import info as cli_info File "/usr/local/lib/python2.7/dist-packages/spacy/cli/__init__.py", line 1, in <module> from .download import download File "/usr/local/lib/python2.7/dist-packages/spacy/cli/download.py", line 10, in <module> from .link import link File "/usr/local/lib/python2.7/dist-packages/spacy/cli/link.py", line 7, in <module> from ..compat import symlink_to, path2str File "/usr/local/lib/python2.7/dist-packages/spacy/compat.py", line 11, in <module> from thinc.neural.util import copy_array File "/usr/local/lib/python2.7/dist-packages/thinc/neural/__init__.py", line 1, in <module> from ._classes.model import Model File "/usr/local/lib/python2.7/dist-packages/thinc/neural/_classes/model.py", line 12, in <module> from ..train import Trainer File "/usr/local/lib/python2.7/dist-packages/thinc/neural/train.py", line 3, in <module> from .optimizers import Adam, SGD, linear_decay File "optimizers.pyx", line 13, in init thinc.neural.optimizers File "ops.pyx", line 18, in init thinc.neural.ops File "/usr/local/lib/python2.7/dist-packages/cytoolz/__init__.py", line 3, in <module> from .functoolz import * ImportError: /usr/local/lib/python2.7/dist-packages/cytoolz/functoolz.so: undefined symbol: PyFPE_jbuf This is in Python 2.7, while Python 3.6 works ok. I have (at least) the problem with spaCy 2.0.5 and 2.0.6. The PyFPE_jbuf error has been reported for a number of other projects, e.g., sklearn (https://bugs.launchpad.net/ubuntu/+source/scikit-learn/+bug/1716004), numpy (numpy undefined symbol: PyFPE_jbuf), and lxml (undefined symbol: PyFPE_jbuf error while using 'lxml' on ubuntu). Here the general suggestion seems to be a reinstall. My sklearn, numpy, and lxml imports work fine. I hav…
tagged with: python
linked to: http://stackoverflow.com/q/36190757
has title: undefined symbol PyFPE_jbuf with spaCy
linked to: http://stackoverflow.com/q/35852646

http://stackoverflow.com/comment/84233980
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48613602
has text: If you get a result of shape `(2100,)` instead of `(2100,256,256,3)`, it might fail to load images. Then your result will have the form `array([None, None, ..., None], dtype=object)`.

http://stackoverflow.com/q/48631113
has answer: http://stackoverflow.com/a/48631711
tagged with: arrays
type: Question
possible better answer: http://stackoverflow.com/a/48631711
tagged with: algorithm
has comment: http://stackoverflow.com/comment/84260553
has title: Improving algorithm to find local maxima of 1D numpy array
tagged with: python
accepted answer: http://stackoverflow.com/a/48632903
has answer: http://stackoverflow.com/a/48632903
tagged with: numpy
type: AnsweredQuestion
score: 0
has body: I am trying to find the local maxima of the function f(x) = (sin(x)/x)^2. For approximate solutions, I initialised two variables x and y and first plotted a graph to have a visual representation. x = np.linspace(-20.0, 20.0, num=int((20+20)/0.01)) y = np.power(np.sin(x)/x, 2) plt.plot(x, y, 'r.', markersize= 1) plt.show() This shows graph. I then tried to create an algorithm to find the Maxima: def returnMaxima(num, x, y): """ number, np.array, np.array -&gt; list num: number of maxima needed | x: x 1D array | y: y 1D array returns [[x1,y1], [x2,y2]...] in descending order of y """ allMaximaPoints = [] # stores all Maxima points reqMaximaPoints = [] # stores num Maxima points for i in range(y.size): # for first y value if i == 0: if y[i] &gt; y[i+1]: allMaximaPoints += [[x[i], y[i]], ] # for last y value elif i == y.size - 1: if y[i] &gt; y[i-1]: allMaximaPoints += [[x[i], y[i]], ] # for rest y values else: if y[i] &gt; y[i-1] and y[i] &gt; y[i+1]: allMaximaPoints += [[x[i], y[i]], ] # extract largest maximas from allMaximaPoints while num &gt; 0: reqMaximaPoints += [max(allMaximaPoints, key=lambda item:item[1]),] del allMaximaPoints[allMaximaPoints.index(max(allMaximaPoints, key=lambda item:item[1]))] num -= 1 return reqMaximaPoints When I tried returnMaxima(2, x, y) I get [[-4.4961240310077528, 0.04719010162459622], [4.4961240310077528, 0.04719010162459622]]. This is incorrect as it skipped the local maxima at x = 0. I suspect it is because the y[i-1] and y[i+1] values adjacent to the maxima at y[i] at x=0 is approximately equal to y[i] causing the code else: if y[i] &gt; y[i-1] and y[i] &gt; y[i+1]: allMaximaPoints += [[x[i], y[i]], ] to not account for that point. This is because when I changedx = np.linspace(-20.0, 20.0, num=int((20+20)/0.01)) to say x = np.linspace(-20.0, 20.0, num=int((20+20)/0.1)) i.e. larger steps in x, the local maxima at x=0 is correctly found. However, even if I changed the &gt; signs in the above code to &gt;=, that maxima at x=0 is sti…
answer count: 2

http://stackoverflow.com/q/48573178
tagged with: mouseevent
type: AnsweredQuestion
score: 0
has body: I need to draw a rectangle of fixed size in image when left mouse button is clicked, and change its location in the image by moving the mouse. I came up with this code, which basically draws rectangle in image, where mouse pointer is intersection point of diagonals of rectangle. import cv2 as cv import numpy as np #flags move_rectangle = False #color for rectangle BLUE = [255,0,0] def mouse(event,x,y,flags,params): global move_rectangle, BLUE #draw rectangle where x,y is rectangle center if event == cv.EVENT_LBUTTONDOWN: move_rectangle = True elif event == cv.EVENT_MOUSEMOVE: if move_rectangle: cv.rectangle(bg,(x-int(0.5*cols),y-int(0.5*rows)), (x+int(0.5*cols),y+int(0.5*rows)),BLUE, -1) elif event == cv.EVENT_LBUTTONUP: move_rectangle = False cv.rectangle(bg,(x-int(0.5*cols),y-int(0.5*rows)), (x+int(0.5*cols),y+int(0.5*rows)),BLUE, -1) if __name__ == '__main__': #loading images fg = cv.imread('sample.jpg') bg = cv.imread('beach.jpg') #grabing height and width of foreground image rows, cols = fg.shape[:2] cv.namedWindow('draw') cv.setMouseCallback('draw', mouse) while True: cv.imshow('draw', bg) k = cv.waitKey(1) #waiting for esc to exit if k == 27 &amp; 0xFF: break cv.destroyAllWindows() However, i can't figure out how to make it draw rectangle only in the position of mouse pointer. I need to get rid of that "shadow" behind front rectangle. Shadow How this can be done?
accepted answer: http://stackoverflow.com/a/48573909
answer count: 1
has answer: http://stackoverflow.com/a/48573909
tagged with: python-3.x
tagged with: opencv
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84144136
has title: Draw a fixed sized rectangle in image on click and change its location by moving the mouse

http://stackoverflow.com/comment/84147788
has text: @Ajax1234 you did it mate! the only reason I'm not selecting it as "the answer" is because, even when far better than my code, it's too complicated for my limited mind to understand as it is. If you would post it in like a fully fledged function with no "comprehensions" I would accept it. Thanks for the prompt response!
type: Comment
comment on: http://stackoverflow.com/a/48574600
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84191296
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48597199
type: AnswerComment
has text: The bottom `else` statement look like it should be aligned with the nested `if`, not the top-level one. It's out by a single space which you might not have noticed. Or maybe an error was introduced when you posted the code here?

http://stackoverflow.com/comment/137742159
has text: `ExpiresIn=0` is not required.
comment on: http://stackoverflow.com/a/64156936
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48635153
tagged with: python-3.x
has answer: http://stackoverflow.com/a/61350398
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84267068
tagged with: python
score: 1
downvote count: 0
answer count: 1
has body: I have a script that calls a subprocess (speedtest-cli). The script seems to randomly fail with the following error message:- ERROR: timed out ERROR: 'speedtest-cli --share' failed (exit code 1). Retrieving speedtest.net configuration... Cannot retrieve speedtest configuration Traceback (most recent call last): File "/home/steve/speedtest_dev.py", line 80, in &lt;module&gt; data[1] = data[1].strip("'") ##Finish date and time IndexError: list index out of range As far as I can tell it looks like there are two errors in here:- a) Speedtest-cli fails by timing out ERROR: timed out ERROR: 'speedtest-cli --share' failed (exit code 1). and b) The data strip then fails as one would expect because there is no data. Traceback (most recent call last): File "/home/steve/speedtest_dev.py", line 80, in &lt;module&gt; data[1] = data[1].strip("'") ##Finish date and time IndexError: list index out of range I would like to catch the 1st error if possible and re-run the subprocess after an interval (60 seconds?). I have tried creating a function:- def run_speedtest(): outfile = open(dataFile, "w+") subprocess.call(["/home/steve/speedtest-cli-extras/speedtest-csv", "--share"], stdout=outfile) outfile.close() and then using a try statement like:- try: run_speedtest() except: print("1st attempt failed") #for testing only time.sleep(60) run_speedtest() For some reason I only manage to run the first part of this and when that errors out the except statement doesn't seem to run. The script then does this:- #Separate Values from csv string with open(dataFile, "r+") as f: data = f.read() data = data.strip() data = data.replace("\t","|") f.seek(0) f.write(data) f.truncate f.close() #Open file and process with open(dataFile, "r") as g: data = g.read() data = data.split("|") writes to a database and sends an email when the one of the parameters is less than a defined value. It all works fine unless the initial run_speedtest() fails. Any help would be appreciated.
upvote count: 1
has title: Python - Re-run subprocess call when it fails
favorite count: 0
type: Question

http://stackoverflow.com/q/48557788
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48570355
has comment: http://stackoverflow.com/comment/84111558
tagged with: google-cloud-ml
has body: My jobs in gcloud ml-engine crash because the train file doesn't exist. In the screenshot you can see the error in the top line. At the bottom I check the contents of the directory and the file is clearly there. error screenshot source
tagged with: python
tagged with: google-cloud-platform
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/42799117
upvote count: 1
tagged with: keras
tagged with: tensorflow
has title: gcloud ml-engine IOError: file does not exist

http://stackoverflow.com/q/48595288
type: Question
tagged with: hierarchical-data
type: AnsweredQuestion
tagged with: multidimensional-array
has body: I have a hierarchical dataframe I created in pandas: import pandas as pd import numpy as np col_index = pd.MultiIndex.from_product([[0,1], ['a', 'b', 'c']]) df_outer = pd.DataFrame(index=range(4), columns=col_index) print(df_outer) 0 1 a b c a b c 0 NaN NaN NaN NaN NaN NaN 1 NaN NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN NaN NaN 3 NaN NaN NaN NaN NaN NaN I'm wondering if it's possible to populate each entry in this data frame with another data frame, for example: inner_names = ['w', 'x', 'y', 'z'] df_inner = pd.DataFrame(np.random.randn(4,4), index=inner_names, columns=inner_names) If this is a bad idea, what would be a better way to create some othe easily indexed data structure containing data frames I want to put in the lements of df_outer?
tagged with: pandas
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48595387
tagged with: python
has answer: http://stackoverflow.com/a/48595387
score: 2
upvote count: 2
answer count: 1
downvote count: 0
has title: Pandas dataframe of dataframes with hierarchical columns
favorite count: 0

http://stackoverflow.com/comment/84222650
type: AnswerComment
comment on: http://stackoverflow.com/a/48612731
has text: Yep, that's what I was looking for in two dimensions. If I can figure out how to extend it to arbitrary dimensions, I'll post it as a new answer.
type: Comment
score: 0

http://stackoverflow.com/comment/84179830
score: 0
type: QuestionComment
has text: thankyou! that worked
type: Comment
comment on: http://stackoverflow.com/q/48587963

http://stackoverflow.com/comment/84219128
score: 1
has text: Could you show the full model?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48611376

http://stackoverflow.com/comment/84296849
type: Comment
has text: Here's a link to the Word2Vec user guide that provides additional info: http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/word2vec.html#transforming-words-to-vectors
type: AnswerComment
comment on: http://stackoverflow.com/a/48647481
score: 0

http://stackoverflow.com/a/48493011
accepted answer of: http://stackoverflow.com/q/48492429
type: Answer
answers question: http://stackoverflow.com/q/48492429
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Python performs chained operations left to right: In [32]: mu=np.array([1,1]) In [33]: sigma= np.array([[3,0],[0,3]]) In [34]: mu@sigma@mu Out[34]: 6 is the same as doing two expressions: In [35]: temp=mu@sigma In [36]: temp.shape Out[36]: (2,) In [37]: temp@mu Out[37]: 6 In my comments (deleted) I claimed @ was just doing np.dot. That's not quite right. The documentation describes the handling of 1d arrays differently. But the resulting shapes are the same: In [38]: mu.dot(sigma).dot(mu) Out[38]: 6 In [39]: mu.dot(sigma).shape Out[39]: (2,) For 1d and 2d arrays, np.dot and @ should produce the same result. They differ in handling higher dimensional arrays. Historically numpy has used arrays, which can be 0d, 1d, and on up. np.dot was the original matrix multiplication method/function. np.matrix was added, largely as a convenience for wayward MATLAB programmers. It only allows 2d arrays (just as the old, 1990s MATLAB). And it overloads __mat__ (*) with def __mul__(self, other): if isinstance(other, (N.ndarray, list, tuple)) : # This promotes 1-D vectors to row vectors return N.dot(self, asmatrix(other)) if isscalar(other) or not hasattr(other, '__rmul__') : return N.dot(self, other) return NotImplemented Mu*sigma and Mu@sigma behave the same, though the calling tree is different In [48]: Mu@sigma@Mu ... ValueError: shapes (1,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0) Mu*sigma produces a (1,2) matrix, which cannot matrix multiply a (1,2), hence the need for a transpose: In [49]: Mu@sigma@Mu.T Out[49]: matrix([[6]]) Note that this is a (1,1) matrix. You have to use item if you want a scalar. (In MATLAB there isn't such a thing as a scalar. Everything has a shape/size.) @ is a relatively recent addition to Python and numpy. It was added to Python as an unimplemented operator. numpy (and possibly other packages) has implemented it. It makes chained expressions possible, though I don't have any problems with the chained dot in [38]. It is more useful when handling …
upvote count: 2

http://stackoverflow.com/comment/83986581
has text: This is one of those cases where it'd be great if `soup.select('span.title::text')` worked or one could directly do: `soup.xpath('//span[@class="title"]/text()')` or similar...
comment on: http://stackoverflow.com/a/48496613
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84138251
type: Comment
has text: `{[]}` is a set containing a list, which is invalid because lists are not hashable. Can you clarify how original input looks?
comment on: http://stackoverflow.com/q/48570795
score: 1
type: QuestionComment

http://stackoverflow.com/comment/84083741
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48544021
has text: sorry for type-o
score: 0

http://stackoverflow.com/a/48642017
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: Possible Approach: Loop over each list in short_list. Flatten every list in long_list that is not the same index as the current list, and convert it to a set. Create a collections.Counter() to store the counts for each element in short list that appears in the flattened list. Demo: from collections import Counter from itertools import chain short_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] long_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [9, 10, 11, 12, 13]] for i, short_lst in enumerate(short_list): to_check = set(chain.from_iterable(long_list[:i] + long_list[i+1:])) print(Counter(x for x in short_lst if x in to_check)) Output: Counter({2: 1, 3: 1}) Counter({4: 1, 5: 1, 6: 1}) Counter({9: 1}) Counter({10: 1})
answers question: http://stackoverflow.com/q/48641425

http://stackoverflow.com/comment/84070370
type: AnswerComment
has text: thks for answer, but i try and it not work. I update my qestion
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48537537

http://stackoverflow.com/q/48616556
has answer: http://stackoverflow.com/a/48660119
has title: delete an subarray from an numpy array or replace that subarray elements with 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84249633
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84249278
has comment: http://stackoverflow.com/comment/84252287
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48660279
has comment: http://stackoverflow.com/comment/84268517
has comment: http://stackoverflow.com/comment/84229911
has comment: http://stackoverflow.com/comment/84268556
has body: I have an array 'a' and i am creating a subarray with selecting certain row and columns, and calling it an array 'b'. How am i suppose to delete or replace those elements in 'a' which is same as elements in 'b'? def seat(): print("select your seat") import numpy as np a = np.arange(100).reshape(10, 10) print(a) l1=input("enter row number:") l1=int(l1) l=l1-1 n1=input("enter the from column number:") n1=int(n1) n=n1-1 p1=input("enter the to column number:") p1=int(p1) p=p1+1 b=a[l:, n:p] k=b.size print("you have booked "+str(k)+"tickets") for element in b.flat: print("your ticket numbers are:"+ str(element)) if a.size==0: print("there are no tickets left") return k;
tagged with: python

http://stackoverflow.com/q/48571471
upvote count: 2
has body: I have a Python script that checks my email every few seconds for new emails in a while loop. I connect to my email server using the imaplib library, in the following manner (the following code is at the top of the while loop): import imaplib mail = imaplib.IMAP4_SSL(IMAPSERVER) mail.login(userName, password) mail.select(theFolderName, True) return_code, mail_ids = mail.search(None, 'UnSeen') Can someone tell me what the following statements actually do? mail.close() mail.logout() According to the documentation they, respectively: "close currently selected mailbox" and "shutdown connection to server; returns server BYE response." But, what does it mean to "close" a mailbox and "shutdown" a connection? I mean, what is the point or benefit of these actions? Can you provide an example where these statements would in fact be necessary? I ask this question because I notice absolutely no difference in my script whether these two lines are added or removed. So, I'd like to better understand their purpose.
accepted answer: http://stackoverflow.com/a/48573994
tagged with: python
tagged with: imaplib
has answer: http://stackoverflow.com/a/48573994
type: AnsweredQuestion
score: 2
has title: What is the practical value of imaplib "close" & "logout"?
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/84144966
type: AnswerComment
score: 0
has text: I see--and then append that column back to the original data frame. Thank you, this is quite helpful. Am I correct to think that this would be considerably faster at scale than `apply`?
comment on: http://stackoverflow.com/a/48574059
type: Comment

http://stackoverflow.com/comment/84000600
type: Comment
type: QuestionComment
score: 0
has text: It depends on your goal. While PCA and co. can work, they are typically less good than other approaches described in academics. There is also more than one mthod to tackle PCA. Approximations could probably be done in less than cubic time. But that's stuff you have to research if you keep the PCA-pipeline. In general: checking out complexity of PCA / KNN is more or less the first step when observing scaling problems (and it tells you it's a problem of the chosen approach, not necessarily the implementation).
comment on: http://stackoverflow.com/q/48502667

http://stackoverflow.com/comment/84115544
has text: do not `break` out of the loop
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48557947

http://stackoverflow.com/a/48539339
score: 1
has comment: http://stackoverflow.com/comment/84075533
has comment: http://stackoverflow.com/comment/84074525
type: Answer
has comment: http://stackoverflow.com/comment/99101862
has body: Karate can be used to test any web-service that works over HTTP. Teams are currently using it for JSON, XML, GraphQL and SOAP. In my opinion technology does not matter, in fact Karate's syntax is 80% "language neutral" and 20% JS. Java is optional. And it fits into all CI tools because it generates JUnit formal XML reports and even HTML reports. If you are choosing not to use Karate because the server is implemented in Python or if the dev-team is supposedly more "comfortable" with Python, I personally do not agree with that decision. PyCharm (if you are referring to the IDE) is made by JetBrains, the makers of IntelliJ - which has excellent built-in support for Cucumber and hence Karate syntax also. I have not checked, but it is highly likely that PyCharm supports Cucumber syntax also. EDIT: I'll add a few more options, the stand-alone executable which works well in combo with Visual Studio Code for which dedicated plugins have started to appear. For a video of what the dev-experience looks like for someone who is coming from a JavaScript background, see this 10 minute lightning talk with demos.
has comment: http://stackoverflow.com/comment/84076495
has comment: http://stackoverflow.com/comment/84074690
downvote count: 0
answers question: http://stackoverflow.com/q/48535847
upvote count: 1

http://stackoverflow.com/comment/84295535
type: QuestionComment
type: Comment
score: 0
has text: By poor I mean ROC AUC = 0.5. It was a bug in 0.6 version of CatBoost, 0.6.1 shows AUC higher then 0.8 (don't remember exact value) and beats default sklearn GradientBoostingClassifier.
comment on: http://stackoverflow.com/q/48625720

http://stackoverflow.com/comment/84097233
has text: This is like pulling teeth. We can't read your mind or see your screen. Please post some sample data so we won't have to guess. Might take a look here. http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48550324

http://stackoverflow.com/a/48508237
answers question: http://stackoverflow.com/q/48508171
type: Answer
has comment: http://stackoverflow.com/comment/84011213
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84011230
has body: You can try something like this : temp = ("here is\n" "\t{}\n" "\t{}".format("foo","bar")) print(temp) Or like : # the \t have been replaced with # 4 spaces just as an example temp = '''here is {} {}'''.format print(temp('foo', 'bar')) vs. what you have: a = "here is\n" b = "\t{}\n" c = "\t{}".format("foo","bar") print( a + b + c)

numpy
tags question: http://stackoverflow.com/q/48603717
tags question: http://stackoverflow.com/q/48552101
tags question: http://stackoverflow.com/q/48560022
tags question: http://stackoverflow.com/q/48607884
tags question: http://stackoverflow.com/q/48591523
tags question: http://stackoverflow.com/q/48514464
tags question: http://stackoverflow.com/q/48511846
tags question: http://stackoverflow.com/q/48613681
tags question: http://stackoverflow.com/q/48502253
tags question: http://stackoverflow.com/q/48527369
tags question: http://stackoverflow.com/q/48600153
tags question: http://stackoverflow.com/q/48554344
tags question: http://stackoverflow.com/q/48531312
tags question: http://stackoverflow.com/q/48559589
tags question: http://stackoverflow.com/q/48563423
tags question: http://stackoverflow.com/q/48583961
tags question: http://stackoverflow.com/q/48633288
tags question: http://stackoverflow.com/q/48492429
tags question: http://stackoverflow.com/q/48528404
tags question: http://stackoverflow.com/q/48596035
tags question: http://stackoverflow.com/q/48540589
tags question: http://stackoverflow.com/q/48504867
tags question: http://stackoverflow.com/q/48531571
tags question: http://stackoverflow.com/q/48527153
tags question: http://stackoverflow.com/q/48541623
tags question: http://stackoverflow.com/q/48594888
tags question: http://stackoverflow.com/q/48607860
tags question: http://stackoverflow.com/q/48543042
tags question: http://stackoverflow.com/q/48489978
tags question: http://stackoverflow.com/q/48553446
tags question: http://stackoverflow.com/q/48488821
tags question: http://stackoverflow.com/q/48516265
tags question: http://stackoverflow.com/q/48559167
tags question: http://stackoverflow.com/q/48620923
tags question: http://stackoverflow.com/q/48547420
tags question: http://stackoverflow.com/q/48620208
tags question: http://stackoverflow.com/q/48622281
tags question: http://stackoverflow.com/q/48603119
tags question: http://stackoverflow.com/q/48551460
tags question: http://stackoverflow.com/q/48632881
tags question: http://stackoverflow.com/q/48565562
tags question: http://stackoverflow.com/q/48629989
tags question: http://stackoverflow.com/q/48527702
tags question: http://stackoverflow.com/q/48640495
tags question: http://stackoverflow.com/q/48591713
tags question: http://stackoverflow.com/q/48542742
tags question: http://stackoverflow.com/q/48592885
tags question: http://stackoverflow.com/q/48552996
tags question: http://stackoverflow.com/q/48574444
tags question: http://stackoverflow.com/q/48542185
tags question: http://stackoverflow.com/q/48561123
tags question: http://stackoverflow.com/q/48547709
tags question: http://stackoverflow.com/q/48511247
tags question: http://stackoverflow.com/q/48532544
tags question: http://stackoverflow.com/q/48643445
tags question: http://stackoverflow.com/q/48617874
tags question: http://stackoverflow.com/q/48547160
tags question: http://stackoverflow.com/q/48579891
tags question: http://stackoverflow.com/q/48534242
tags question: http://stackoverflow.com/q/48592731
tags question: http://stackoverflow.com/q/48530970
tags question: http://stackoverflow.com/q/48591451
tags question: http://stackoverflow.com/q/48585532
tags question: http://stackoverflow.com/q/48526151
tags question: http://stackoverflow.com/q/48614440
tags question: http://stackoverflow.com/q/48633151
tags question: http://stackoverflow.com/q/48530297
tags question: http://stackoverflow.com/q/48551298
tags question: http://stackoverflow.com/q/48523773
tags question: http://stackoverflow.com/q/48522126
tags question: http://stackoverflow.com/q/48535282
tags question: http://stackoverflow.com/q/48534128
tags question: http://stackoverflow.com/q/48511256
tags question: http://stackoverflow.com/q/48588810
tags question: http://stackoverflow.com/q/48604845
tags question: http://stackoverflow.com/q/48493533
tags question: http://stackoverflow.com/q/48609781
tags question: http://stackoverflow.com/q/48600521
tags question: http://stackoverflow.com/q/48489753
tags question: http://stackoverflow.com/q/48632372

http://stackoverflow.com/q/48613557
favorite count: 0
type: Question
has title: Python - Converting large CSV file to JSON
tagged with: http://stackoverflow.com/tag/csv
has body: I have a 4.5GB CSV file that I am trying to convert to JSON using Python 2.7. I have it working fine with a smaller 500mb file however I run out of memory on the bigger one. How do I turn what I have coded into something that reads a CSV file in chunks and write (append in chunks) to a JSON file? f = open('table-52007-changeset.csv', 'rb' ) reader = csv.DictReader(f) out = json.dumps( [ row for row in reader ] ) json_response = json.loads(out) jsonoutput = 'masterlist2.0.json' with open(jsonoutput, 'a') as f: for x in json_response: json.dump(x,f) f.write('\n')
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48613619
has answer: http://stackoverflow.com/a/48613619
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84223974

http://stackoverflow.com/q/48510411
tagged with: selenium
type: Question
type: UnansweredQuestion
has body: I am a beginner using python3 for windows. My problem is I am trying to scrape the title and votes (likes/dislikes) from a youtube playlist and can't seem to get my script to wait for the next page to load before taking the votes on the next page, and again until the playlist is over. Instead it merely takes the title, and votes from first page repeats this and clicks on the next page only once, after everything is copied. I googled and looked at other posts, figuring an explicit wait may need to be invoked, yet it still doesn't appear to work. Current script: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC browser = webdriver.Firefox() browser.get( 'https://www.youtube.com/watch?v=2bnMiScBRfQ&amp;list=PLx1Dr6w7DLoLfPixTug9c8xrTkGUsyhkQ&amp;index=') videosInPlaylist = [] for x in range(1, 4): wait = WebDriverWait(browser, 10) title = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'h1.title'))).text positiveVotes = wait.until(EC.visibility_of_element_located( (By.CSS_SELECTOR, 'ytd-toggle-button-renderer.style-text:nth-child(1) &gt; a:nth-child(1) &gt; yt-formatted-string:nth-child(2)'))).text negativeVotes = wait.until(EC.visibility_of_element_located( (By.CSS_SELECTOR, 'ytd-toggle-button-renderer.style-text:nth-child(2) &gt; a:nth-child(1) &gt; yt-formatted-string:nth-child(2)'))).text currentVideo = [title, positiveVotes, negativeVotes] nextVideo = wait.until(EC.element_to_be_clickable( (By.CSS_SELECTOR, 'ytd-playlist-panel-video-renderer.style-scope:nth-child(3) &gt; a:nth-child(1) &gt; div:nth-child(1) &gt; div:nth-child(3)'))) videosInPlaylist.append(currentVideo) nextVideo.click() print(videosInPlaylist) Please help.
tagged with: python
tagged with: youtube
has answer: http://stackoverflow.com/a/48515560
tagged with: selenium-webdriver
score: 0
has title: waiting for a page to load using selenium explicit wait python
answer count: 1

http://stackoverflow.com/a/48515140
answers question: http://stackoverflow.com/q/48514999
score: 0
has body: import csv with open("my-diff-2.csv","w+") as f: writes = csv.writer(f) writes.writerow(["account number", "name","street","city","state","postal code"]) #this is header for lines in "a","b": # here it should be list of list writes.writerow(lines) # writing the data in row-wise
type: Answer

http://stackoverflow.com/comment/84125675
has text: See my post and it will explain why the answer I have provided solves your problem.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48564391
type: Comment

http://stackoverflow.com/comment/84145597
has text: `AttributeError: 'NoneType' object has no attribute 'value'` means `word_search` variable is `None`. Because the variable is `None`, it won't have `value` attribute and because of that, it will throw this error. This is happening because you're reaching the end of your data structure without finding the value you're asking. In your while loop instead of using `while word_search.value != None` you have to use `while word_search != None`.
score: 0
comment on: http://stackoverflow.com/q/48574363
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84285359
type: AnswerComment
has text: Hi Luciano - unfortunately there are not 216 input features. There are three. The 36, corresponds to 36 rows of x-data, per one y data. That is why in the ideal_data, and displaced_data, there are only three columns - each is a descriptor for each x-data point.
comment on: http://stackoverflow.com/a/48644340
score: 0
type: Comment

http://stackoverflow.com/a/52453673
type: Answer
has body: Check your folder if any of the program named bokeh.py please rename it because it's picking bokeh.plotting from your program bokeh.py not from the library.
score: 20
accepted answer of: http://stackoverflow.com/q/48527785
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48527785
upvote count: 20

http://stackoverflow.com/comment/84192343
comment on: http://stackoverflow.com/q/48596726
has text: I just now saw the second part of your question... but why is `3` not also included?
type: Comment
type: QuestionComment
score: 0

merge
type: Tag
tags question: http://stackoverflow.com/q/48632639
tags question: http://stackoverflow.com/q/48639756
tags question: http://stackoverflow.com/q/48547948
tags question: http://stackoverflow.com/q/48585027
tags question: http://stackoverflow.com/q/48629632
tag name: merge
tags question: http://stackoverflow.com/q/48532442
tags question: http://stackoverflow.com/q/48497449
tags question: http://stackoverflow.com/q/48554588
tags question: http://stackoverflow.com/q/48552366

http://stackoverflow.com/a/48513997
score: 0
has body: bulk_create accepts batch_size parameter however I think whaat you really want to do is to return 200 response immediately and perform bulk creation in a background task eg. with celery
type: Answer
answers question: http://stackoverflow.com/q/48513797
has comment: http://stackoverflow.com/comment/84023999

http://stackoverflow.com/q/48620255
has title: Writing column names to file
tagged with: sqlite
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84237314
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/48620528
accepted answer: http://stackoverflow.com/a/48620528
has comment: http://stackoverflow.com/comment/84237829
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/7831371
has body: I have an SQLite DB file and I am parsing the data from each column in a table of the db to a .txt file. At the moment it is writing the column contents to the file but it won't pull the column names and write those. How can I go about it as I have tried to use this guide Is there a way to get a list of column names in sqlite? but i cannot seem to get it to work. Here is my code with an attempt at pulling the column names from the table. import sqlite3 from sqlite3 import Error # create a database connection to the SQLite database specified by the db_file def create_connection(db_file,detect_types=sqlite3.PARSE_DECLTYPES): try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return None # Query specific rows in the sms table def select_data(conn): cur = conn.cursor() cur.execute("SELECT _id, address, strftime('%d-%m-%Y', date / 1000, 'unixepoch'),read, type, body, seen FROM sms") print("Writing the contents of the sms table to an evidence file") print("\t") # Trying to pull out column names from db table def get_col_names(): conn = sqlite3.connect("mmssms.db") c = conn.cursor() c.execute("SELECT _id, address, strftime('%d-%m-%Y', date / 1000, 'unixepoch'),read, type, body, seen FROM sms") return [member[0] for member in c.description] # Write the data to a smsEvidence.txt file with open('EvidenceExtractionFiles/smsInfo.txt', 'a+') as f: rows = cur.fetchall() for row in rows: #print(row) f.write("%s\n" % str(row)) print("SMS Data is written to the evidence File") # path to where the db files are stored def main(): database = "H:\College Fourth Year\Development Project\Final Year Project 2018\mmssms.db" # create a database connection conn = create_connection(database) with conn: # print("Query specific columns") select_data(conn) # close db connection if(conn): conn.close() print("Database closed") if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/84237897

http://stackoverflow.com/comment/84118314
comment on: http://stackoverflow.com/q/48559509
has text: No. I am not using heroku.. I will be using my Ubuntu server for hosting. But, you could share your solution with hope
score: 0
type: QuestionComment
type: Comment

django-rest-framework
tags question: http://stackoverflow.com/q/48554606
tags question: http://stackoverflow.com/q/48501279
tags question: http://stackoverflow.com/q/48511076
tags question: http://stackoverflow.com/q/48573874
tags question: http://stackoverflow.com/q/48598533
tags question: http://stackoverflow.com/q/48612302
tags question: http://stackoverflow.com/q/48623389
tags question: http://stackoverflow.com/q/48491431
tags question: http://stackoverflow.com/q/48620404
tags question: http://stackoverflow.com/q/48598779
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/48519881
tags question: http://stackoverflow.com/q/48605270
tags question: http://stackoverflow.com/q/48541819
tags question: http://stackoverflow.com/q/48604710
tags question: http://stackoverflow.com/q/48562670
tags question: http://stackoverflow.com/q/48637315
tags question: http://stackoverflow.com/q/48552509
tags question: http://stackoverflow.com/q/48492639
type: Tag
tags question: http://stackoverflow.com/q/48594918
tags question: http://stackoverflow.com/q/48564129
tags question: http://stackoverflow.com/q/48573371
tags question: http://stackoverflow.com/q/48506898
tags question: http://stackoverflow.com/q/48515837
tags question: http://stackoverflow.com/q/48635936
tags question: http://stackoverflow.com/q/48601110
tags question: http://stackoverflow.com/q/48493290
tags question: http://stackoverflow.com/q/48520821
tags question: http://stackoverflow.com/q/48569659
tags question: http://stackoverflow.com/q/48542211
tags question: http://stackoverflow.com/q/48592239
tags question: http://stackoverflow.com/q/48513611
tags question: http://stackoverflow.com/q/48560270

http://stackoverflow.com/q/48604263
downvote count: 3
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48604314
has comment: http://stackoverflow.com/comment/84205252
favorite count: 0
type: Question
tagged with: python-3.x
has title: How do I print all prime factors of a large number (eg. 99999999) keeping in mind the performance/time and not using any special packages?
has comment: http://stackoverflow.com/comment/84205439
score: -2
tagged with: python
has body: I have written the following code. import math def check_isprime(num): flag=0 if num&lt;2: return False for i in range(2,int(math.sqrt(num))+1): if num%i == 0: flag=1 break if flag: return False else: return True def find_prime_factors(number): while number != 1: for i in range(2,number+1): if check_isprime(i): if number%i==0: print i number=number/i break #find_prime_factors(99999999) (Not able to execute) #find_prime_factors(10000000) (This is fine) The code is working properly for many large numbers too, but failed for others as the loop is running for more number of times. Is it possible to optimize this a little bit, or is there any better approach?
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48604314

http://stackoverflow.com/comment/84178522
comment on: http://stackoverflow.com/q/48588810
type: Comment
has text: Oh, thank you! Understood. Nevertheless, the output I get doesn't make sense. I updated my question with a picture of my result
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84111020
score: 0
comment on: http://stackoverflow.com/q/48496406
type: QuestionComment
has text: I have tried to get the the API response and traverse it over by using the functions like Get From Dictionary, Create DIctionary. But the issue is Its not reading the API response as a dictionary.
type: Comment

http://stackoverflow.com/a/48609721
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84215952
score: 4
answers question: http://stackoverflow.com/q/48609632
has comment: http://stackoverflow.com/comment/84215862
has comment: http://stackoverflow.com/comment/84215978
has comment: http://stackoverflow.com/comment/84215922
type: Answer
has comment: http://stackoverflow.com/comment/84227119
has comment: http://stackoverflow.com/comment/84215979
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48609632
has body: Restructure with a for loop and specify only when you want to do something: players = [['James', 202], ['Curry', 193], ['Durant', 205], ['Jordan', 199], ['David', 211]] for p, height in players: if height &gt;= 200: print(p) # James # Durant # David Or use a list comprehension: [p for p, height in players if score &gt;= 200] # ['James', 'Durant', 'David'] The problem with your code is that when it hits continue, i does not increment as the next iteration of the loop begins. Read up on continue here. Here's how you would do it with a while loop: i = 0 while i &lt; len(players): p, height = players[i] if height &gt;= 200: print(p) i += 1 # James # Durant # David

scipy
tags question: http://stackoverflow.com/q/48488665
tags question: http://stackoverflow.com/q/48539558
tags question: http://stackoverflow.com/q/48542674
tags question: http://stackoverflow.com/q/48558269
tags question: http://stackoverflow.com/q/48631092
tags question: http://stackoverflow.com/q/48581187
tags question: http://stackoverflow.com/q/48582925
tags question: http://stackoverflow.com/q/48552133
tags question: http://stackoverflow.com/q/48564578
tags question: http://stackoverflow.com/q/48633288
tags question: http://stackoverflow.com/q/48582675
tags question: http://stackoverflow.com/q/48494814
tags question: http://stackoverflow.com/q/48607860
tags question: http://stackoverflow.com/q/48600781
tags question: http://stackoverflow.com/q/48551460
tags question: http://stackoverflow.com/q/48572647
tags question: http://stackoverflow.com/q/48612354
tags question: http://stackoverflow.com/q/48535829
tags question: http://stackoverflow.com/q/48543002
tags question: http://stackoverflow.com/q/48582986
tags question: http://stackoverflow.com/q/48560723
tags question: http://stackoverflow.com/q/48547580
tags question: http://stackoverflow.com/q/48600521
tags question: http://stackoverflow.com/q/48632372
type: Tag
tags question: http://stackoverflow.com/q/48502828
tags question: http://stackoverflow.com/q/48615775
tags question: http://stackoverflow.com/q/48621407
tags question: http://stackoverflow.com/q/48542640
tag name: scipy
tags question: http://stackoverflow.com/q/48544064
tags question: http://stackoverflow.com/q/48604495
tags question: http://stackoverflow.com/q/48591473
tags question: http://stackoverflow.com/q/48604141
tags question: http://stackoverflow.com/q/48622933
tags question: http://stackoverflow.com/q/48491649
tags question: http://stackoverflow.com/q/48581540
tags question: http://stackoverflow.com/q/48506782
tags question: http://stackoverflow.com/q/48590672
tags question: http://stackoverflow.com/q/48569631
tags question: http://stackoverflow.com/q/48527473
tags question: http://stackoverflow.com/q/48519363
tags question: http://stackoverflow.com/q/48541623
tags question: http://stackoverflow.com/q/48505061
tags question: http://stackoverflow.com/q/48642216
tags question: http://stackoverflow.com/q/48590694
tags question: http://stackoverflow.com/q/48491241
tags question: http://stackoverflow.com/q/48561123
tags question: http://stackoverflow.com/q/48532544
tags question: http://stackoverflow.com/q/48549357
tags question: http://stackoverflow.com/q/48596810
tags question: http://stackoverflow.com/q/48619835
tags question: http://stackoverflow.com/q/48620073
tags question: http://stackoverflow.com/q/48582908
tags question: http://stackoverflow.com/q/48574930
tags question: http://stackoverflow.com/q/48637274
tags question: http://stackoverflow.com/q/48532652
tags question: http://stackoverflow.com/q/48547499

angularjs
tags question: http://stackoverflow.com/q/48520265
tags question: http://stackoverflow.com/q/48499299
type: Tag
tags question: http://stackoverflow.com/q/48543326
tag name: angularjs

http://stackoverflow.com/comment/84173977
has text: No problem. Upvote my answer too if you like the solution. :)
type: Comment
comment on: http://stackoverflow.com/a/48588184
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84233327
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48617994
has text: Which database you are using? mysql? postgresql?

http://stackoverflow.com/a/48564206
score: 2
has comment: http://stackoverflow.com/comment/84124339
type: AcceptedAnswer
downvote count: 0
has body: In case you do not need to query on y (only obtain the value), we can make it a property instead: class P(models.Model): par = FloatField() class H(models.Model): p = models.ForeignKey(P, on_delete.CASCADE) x = FloatField() @property def y(self): return calc_y(self.x, self.p.par) So we do not store it in the database: the property is evaluated when needed. So if you have a H instance h, then h.y will let Python evaluate the value and return it. The advantage of doing so is that we avoid data duplication, so it can not happen that the relation between the three variables is not satisfied, we also save on memory, since the database table will be smaller. A problem with this approach is that since the value is not stored explicitly, querying on y is impossible (or at least not without some tricks). So we can not easily query the database for all Hs where y &lt; 0.5 for example.
accepted answer of: http://stackoverflow.com/q/48564067
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48564067

http://stackoverflow.com/comment/84135593
has text: No, this is not what I want. As I say, I want to check short visual response of element interaction. Like a click on [one of these Angular buttons](https://material.angularjs.org/latest/demo/button).
comment on: http://stackoverflow.com/a/48569626
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48581193
upvote count: 1
has comment: http://stackoverflow.com/comment/84170829
answers question: http://stackoverflow.com/q/48579232
has comment: http://stackoverflow.com/comment/84164555
score: 1
has comment: http://stackoverflow.com/comment/84170617
has body: Three things that you should make sure, are all the apps you have in your INSTALLED_APPS setting installed on your system? Have you perhaps forgotten to activate the virtualenv where everything was installed in the first place? If you have both of the things above on your system then maybe you forgot to install the apps from requirements in your venv? You can do this by pip install -r requirements.txt Replace requirements.txt with whatever your requirements file's name is. Make sure you do this after activating the virtual environment.
accepted answer of: http://stackoverflow.com/q/48579232
downvote count: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84166920

http://stackoverflow.com/comment/84136795
score: 0
type: Comment
has text: But you create a ne df before writing that obviously does not have the column you added anymore.
type: AnswerComment
comment on: http://stackoverflow.com/a/48541205

http://stackoverflow.com/comment/84131173
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48567035
has text: @roganjosh I updated the question. Is it clearer now?
type: Comment

http://stackoverflow.com/q/48592885
answer count: 2
has comment: http://stackoverflow.com/comment/84183573
tagged with: python
possible better answer: http://stackoverflow.com/a/48593765
has title: Finding the index of items containing 'inf' or 'nan'
tagged with: list
has comment: http://stackoverflow.com/comment/84183325
has answer: http://stackoverflow.com/a/48593765
has comment: http://stackoverflow.com/comment/84183175
type: AnsweredQuestion
score: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/48593060
downvote count: 1
has comment: http://stackoverflow.com/comment/84183114
favorite count: 0
has answer: http://stackoverflow.com/a/48593060
tagged with: numpy
has body: The following is a sample of 1 item in my list: array([[ 1, 2, 3, 43, 83, 92], [ 12, 54, 93, 23, 94, 83], [ 23, inf, inf, inf, inf, inf], [ 83, 33, 33, 83, 13, 83], [ 83, nan, 83, 73, 43, 43], [ 43, 83, 93, 22, 83, 54], [ 66, nan, 74, 84, 84, 75], [ 74, 44, 65, 6, 9, 7], [ 54, 9, 74, 754, 55, 74]]) Some of those items contain inf or nan values. I'm thus trying to return the index of the items that contain such values. I thus tried doing the following: for x in f: if float('inf') in x: idx.append(f.index(x)) elif float('nan') in x: idx.append(f.index(x)) When I run my script however, I get the following error: idx.append(f.index(x)) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Why is that? How can I solve this issue? As a reminder, the above sample is only 1 item. Since it contains inf and nan, I would like to return the index of that item. The item is basically a list of lists. Thanks.
tagged with: indexing
linked to: http://stackoverflow.com/q/12647471
type: Question

http://stackoverflow.com/comment/84008003
type: Comment
score: 0
type: QuestionComment
has text: @quamrana there is a `read_lock.release()` in the read_from_db method. It's the second to last line.
comment on: http://stackoverflow.com/q/48505658

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/48603455
tags question: http://stackoverflow.com/q/48552512
type: Tag
tags question: http://stackoverflow.com/q/48604184
tags question: http://stackoverflow.com/q/48510248
tags question: http://stackoverflow.com/q/48542947
tags question: http://stackoverflow.com/q/48643604
tags question: http://stackoverflow.com/q/48612655
tags question: http://stackoverflow.com/q/48569170
tags question: http://stackoverflow.com/q/48641301
tags question: http://stackoverflow.com/q/48614867
tags question: http://stackoverflow.com/q/48542501
tags question: http://stackoverflow.com/q/48528775
tags question: http://stackoverflow.com/q/48643441
tags question: http://stackoverflow.com/q/48537209
tags question: http://stackoverflow.com/q/48541018
tags question: http://stackoverflow.com/q/48530835
tags question: http://stackoverflow.com/q/48558431
tags question: http://stackoverflow.com/q/48553228
tags question: http://stackoverflow.com/q/48553303
tags question: http://stackoverflow.com/q/48566782
tags question: http://stackoverflow.com/q/48488660
tags question: http://stackoverflow.com/q/48615279
tags question: http://stackoverflow.com/q/48521710
tags question: http://stackoverflow.com/q/48594989
tags question: http://stackoverflow.com/q/48498889
tags question: http://stackoverflow.com/q/48535337
tags question: http://stackoverflow.com/q/48610829
tags question: http://stackoverflow.com/q/48544859
tags question: http://stackoverflow.com/q/48629208
tags question: http://stackoverflow.com/q/48591053
tags question: http://stackoverflow.com/q/48595277
tags question: http://stackoverflow.com/q/48499883
tags question: http://stackoverflow.com/q/48645336
tags question: http://stackoverflow.com/q/48551668
tag name: csv
tags question: http://stackoverflow.com/q/48545726
tags question: http://stackoverflow.com/q/48645262
tags question: http://stackoverflow.com/q/48518993
tags question: http://stackoverflow.com/q/48565326
tags question: http://stackoverflow.com/q/48546662
tags question: http://stackoverflow.com/q/48613584
tags question: http://stackoverflow.com/q/48505575
tags question: http://stackoverflow.com/q/48603774
tags question: http://stackoverflow.com/q/48540690
tags question: http://stackoverflow.com/q/48501079
tags question: http://stackoverflow.com/q/48589525
tags question: http://stackoverflow.com/q/48603425
tags question: http://stackoverflow.com/q/48635413
tags question: http://stackoverflow.com/q/48567866
tags question: http://stackoverflow.com/q/48594977
tags question: http://stackoverflow.com/q/48552245
tags question: http://stackoverflow.com/q/48493487
tags question: http://stackoverflow.com/q/48537026
tags question: http://stackoverflow.com/q/48538663
tags question: http://stackoverflow.com/q/48503463
tags question: http://stackoverflow.com/q/48501791
tags question: http://stackoverflow.com/q/48511783
tags question: http://stackoverflow.com/q/48558811
tags question: http://stackoverflow.com/q/48510700
tags question: http://stackoverflow.com/q/48641166
tags question: http://stackoverflow.com/q/48596923
tags question: http://stackoverflow.com/q/48552589
tags question: http://stackoverflow.com/q/48518204
tags question: http://stackoverflow.com/q/48602238
tags question: http://stackoverflow.com/q/48500283
tags question: http://stackoverflow.com/q/48586647
tags question: http://stackoverflow.com/q/48638900
tags question: http://stackoverflow.com/q/48524928
tags question: http://stackoverflow.com/q/48567355
tags question: http://stackoverflow.com/q/48530915
tags question: http://stackoverflow.com/q/48603448
tags question: http://stackoverflow.com/q/48512562
tags question: http://stackoverflow.com/q/48547586
tags question: http://stackoverflow.com/q/48644014
tags question: http://stackoverflow.com/q/48564598
tags question: http://stackoverflow.com/q/48516371
tags question: http://stackoverflow.com/q/48522845
tags question: http://stackoverflow.com/q/48553991
tags question: http://stackoverflow.com/q/48518349

http://stackoverflow.com/q/48636600
score: 0
tagged with: java
downvote count: 2
answer count: 1
has title: what is best way to use trained tensorflow in java
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
tagged with: jython
tagged with: python
accepted answer: http://stackoverflow.com/a/48636768
has body: I am coding UI by javaFx in eclipse because I can only use java, no python, no c. Now I try to use trained tensorflow file in this UI. (this tensorflow file is under python) I am looking for several ways (API, jython, TCP/IP) but I am not sure which one is best. Please write your opinion which has more advantages or fewer disadvantages.
has answer: http://stackoverflow.com/a/48636768
type: AnsweredQuestion

http://stackoverflow.com/q/48591771
answer count: 5
has comment: http://stackoverflow.com/comment/84181884
has answer: http://stackoverflow.com/a/77425148
has answer: http://stackoverflow.com/a/48592523
type: UnansweredQuestion
tagged with: contextmanager
downvote count: 2
has answer: http://stackoverflow.com/a/48592500
tagged with: with-statement
tagged with: block
favorite count: 0
has answer: http://stackoverflow.com/a/69935451
has comment: http://stackoverflow.com/comment/84201743
has answer: http://stackoverflow.com/a/48591891
tagged with: python
score: 24
upvote count: 26
has title: Using context managers without "with" block
has comment: http://stackoverflow.com/comment/88341131
type: Question
has body: Below is an example of my my_create method, and an example of that method in use. @contextmanager def my_create(**attributes): obj = MyObject(**attributes) yield obj obj.save() with my_create(a=10) as new_obj: new_obj.b = 7 new_obj.a # =&gt; 10 new_obj.b # =&gt; 7 new_obj.is_saved() # =&gt; True To users of Ruby/Rails, this may look familiar. It's similar to the ActiveRecord::create method, with the code inside the with block acting as, well, a block. However: with my_create(a=10) as new_obj: pass new_obj.a # =&gt; 10 new_obj.is_saved() # =&gt; True In the above example, I've passed an empty "block" to my my_create function. Things work as expected (my_obj was initialized, and saved), but the formatting looks a little wonky, and the with block seems unnecessary. I would prefer to be able to call my_create directly, without having to setup a passing with block. Unfortunately, that's not possible with my current implementation of my_create. my_obj = create(a=10) my_obj # =&gt; &lt;contextlib.GeneratorContextManager at 0x107c21050&gt; I'd have to call both __enter__ and __exit__ on the GeneratorContextManager to get my desired result. The question: Is there a way to write my my_create function so that it can be called with a "block" as an optional "parameter"? I don't want to pass an optional function to my_create. I want my_create to optionally yield execution to a block of code. The solution doesn't have to involve with or contextmanager. For instance, the same results as above can be achieved with a generator and a for loop, although the syntax becomes even more unclear. At this point I'm afraid that a readable-enough-to-be-sensibly-usable solution doesn't exist, but I'm still interested to see what everyone comes up with. Some clarification: Another example would be: @contextmanager def header_file(path): touch(path) f = open(path, 'w') f.write('This is the header') yield f f.close() with header_file('some/path') as f: f.write('some more stuff') another_f = header_…

http://stackoverflow.com/comment/84017784
comment on: http://stackoverflow.com/q/48511411
type: Comment
type: QuestionComment
score: 0
has text: @SuperStew : I do not want the DB.. I tried in the past, it is working... I want to get things in python only no other languages.

http://stackoverflow.com/q/48608814
has body: I have a shell script that run a python script, shell script contains a lot of "if" statements. Simple example of runner.sh ([1=1] is just for example): if [ 1=1 ]; then export DB_NAME="test_1" sleep 5; python ~/tmp/test_sleep/test.py $DB_NAME; fi &amp; if [ 1=1 ]; then export DB_NAME="test_2" sleep 5; python ~/tmp/test_sleep/test.py $DB_NAME; fi &amp; if [ 1=1 ]; then export DB_NAME="test_3" sleep 5; python ~/tmp/test_sleep/test.py $DB_NAME; fi &amp; if [ 1=1 ]; then export DB_NAME="test_4" sleep 5; python ~/tmp/test_sleep/test.py $DB_NAME; fi # wait for background processes to finish CHILD_ERROR=0 for CHILD_PID in `pgrep -P $$` do # store child error if any wait $CHILD_PID || CHILD_ERROR=$? done And test.py: from time import gmtime, strftime import sys print "%s at %s" % (sys.argv[1], strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())) Expected that each statement will sleep for 5 seconds before execution, but when I run it I see that runner.sh wait 5 second and then run all .py scripts in the same time: test_2 at Sun, 04 Feb 2018 13:42:56 +0000 test_1 at Sun, 04 Feb 2018 13:42:56 +0000 test_3 at Sun, 04 Feb 2018 13:42:56 +0000 test_4 at Sun, 04 Feb 2018 13:42:56 +0000 So the question is how to make sleep work inside the "if" statement? I can't make it outside cause I need to check a lot of if's (that's why I have fi &amp; ) I know that all ifs running on background and sleep work for each process, all I need that those background processes start with some sleep delay (that have to increased for each statement). For example 30s for 1st, +30s for next one and so on.
tagged with: sleep
has comment: http://stackoverflow.com/comment/84214479
accepted answer: http://stackoverflow.com/a/48609292
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84214094
has comment: http://stackoverflow.com/comment/84214301
answer count: 2
tagged with: bash
downvote count: 0
tagged with: shell
upvote count: 1
has title: shell sleep inside the 'if' statement
favorite count: 0
has comment: http://stackoverflow.com/comment/84214721
type: Question
possible better answer: http://stackoverflow.com/a/48609528
has answer: http://stackoverflow.com/a/48609292
score: 1
has answer: http://stackoverflow.com/a/48609528
tagged with: python

http://stackoverflow.com/q/48644767
downvote count: 0
has title: ln2 const value in _math.c in cpython
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84294442
has comment: http://stackoverflow.com/comment/84303885
score: 3
has body: I'm looking at _math.c in git (line 25): #if !defined(HAVE_ACOSH) || !defined(HAVE_ASINH) static const double ln2 = 6.93147180559945286227E-01; static const double two_pow_p28 = 268435456.0; /* 2**28 */ and I noticed that ln2 value is different from the what wolframalpha value for ln2. (bald part is the difference) ln2 = 0.693147180559945286227 (cpython) ln2 = 0.6931471805599453094172321214581 (wolframalpha) ln2 = 0.693147180559945309417232121458 (wikipedia) so my question is why there is a difference? what am I missing?
possible better answer: http://stackoverflow.com/a/48649424
tagged with: cpython
has answer: http://stackoverflow.com/a/48649424
has answer: http://stackoverflow.com/a/48649085
tagged with: python
accepted answer: http://stackoverflow.com/a/48653387
has answer: http://stackoverflow.com/a/48653387
answer count: 3
upvote count: 3

http://stackoverflow.com/comment/84750137
type: Comment
has text: @Gideon. Did you consider some counter-strike strategies by fulfilling some JavaScript variables during headless browsing? [These elements](http://antoinevastel.github.io/bot%20detection/2017/08/05/detect-chrome-headless.html) for example.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48872158

http://stackoverflow.com/comment/84276562
score: 0
comment on: http://stackoverflow.com/q/48639923
has text: @Sraw I tried it. The same problem.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84048017
comment on: http://stackoverflow.com/q/48525813
has text: It might be that the get/print is getting the attribute from the class level, but the setter is attempting to set the attrib on the instance level method where it doesn't exist.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48633479
answers question: http://stackoverflow.com/q/48633016
has body: It seems like, from your description, the problem is that you aren't adding enough items to your website list. You can use this array initalizer to create an empty list of size 5: websites = [None] * 5 which will make a list that is just [None, None, None, None, None] You'd also have to actually append that to your websites list, which you are not doing in your current except statement, so your try except would look like try: place_web = place_data.a['href'] websites.append(place_web) except Exception as e: place_web = [None] * 5 websites.append(place_web) This also sort of assumes that the websites list is always the same size, is that the case? i.e. if it doesn't fail, it will always have 6 links?
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84269106
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48633016

http://stackoverflow.com/comment/85114929
comment on: http://stackoverflow.com/q/48511355
score: 0
type: Comment
type: QuestionComment
has text: @JakubGórzyński It's properly doing type checking across modules (e.g. `foo.Bar object has no member 'fizz', maybe you meant 'buzz'?`) So I know it can see things that are imported. Besides that, the directory I'm pointing it to is a valid python package (it has an `__init__.py` file), so it should be able to figure everything out from there.

http://stackoverflow.com/comment/84030711
comment on: http://stackoverflow.com/q/48517318
score: 0
type: QuestionComment
has text: But how does your application should know which brooker to use ? If you have connection refused you either have it running on different port or your app cannot see the brooker. Just refer to http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
type: Comment

http://stackoverflow.com/a/48639813
has comment: http://stackoverflow.com/comment/84313714
has comment: http://stackoverflow.com/comment/84313296
upvote count: 5
answers question: http://stackoverflow.com/q/48638398
type: Answer
has comment: http://stackoverflow.com/comment/84314440
has comment: http://stackoverflow.com/comment/84310340
has comment: http://stackoverflow.com/comment/84314027
score: 4
has comment: http://stackoverflow.com/comment/84313491
has comment: http://stackoverflow.com/comment/84310477
has comment: http://stackoverflow.com/comment/84314041
has body: float.__round__ takes special care to produce correctly-rounded results, using a correctly-rounded double-to-string algorithm. NumPy does not. The NumPy docs mention that Results may also be surprising due to the inexact representation of decimal fractions in the IEEE floating point standard [R9] and errors introduced when scaling by powers of ten. This is faster, but produces more rounding error. It leads to errors like what you've observed, as well as errors where numbers even more unambiguously below the cutoff still get rounded up: &gt;&gt;&gt; x = 0.33499999999999996 &gt;&gt;&gt; x 0.33499999999999996 &gt;&gt;&gt; x &lt; 0.335 True &gt;&gt;&gt; x &lt; Decimal('0.335') True &gt;&gt;&gt; x &lt; 0.67/2 True &gt;&gt;&gt; round(x, 2) 0.33 &gt;&gt;&gt; numpy.round(x, 2) 0.34000000000000002 You're getting a slower time for NumPy's rounding, but that doesn't have anything to do with which rounding algorithm is slower. Any time comparison between NumPy and regular Python math will boil down to the fact that NumPy is optimized for whole-array operations. Doing math on single NumPy scalars has a lot of overhead, but rounding an entire array with numpy.round easily beats rounding a list of floats with round: In [6]: import numpy In [7]: l = [i/7 for i in range(100)] In [8]: a = numpy.array(l) In [9]: %timeit [round(x, 1) for x in l] 59.6 µs ± 408 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [10]: %timeit numpy.round(a, 1) 5.27 µs ± 145 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) As for which one is more accurate, that's definitely float.__round__. Your number is closer to 5.92270987 than to 5.92270988, and it's round-ties-to-even, not round-everything-to-even. There's no tie here.
has comment: http://stackoverflow.com/comment/84313984
has comment: http://stackoverflow.com/comment/84313448
has comment: http://stackoverflow.com/comment/84276362
has comment: http://stackoverflow.com/comment/84311817
has comment: http://stackoverflow.com/comment/84313850
has comment: http://stackoverflow.com/comment/84311232
has comment: http://stackoverflow.com/comment/84316606
downvote count: 1
has comment: http://stackoverflow.com/comment/84295767

http://stackoverflow.com/q/48541544
has comment: http://stackoverflow.com/comment/84079463
has body: We are facing a problem in accessing member attributes of a class when we the member attribute name is stored in another variable. For example : We have a class A, which has member attributes is var1, var2, var2, and upto var 100. From another class, we are trying to access var67, the name of attribute we want to access ( i.e. var67) is stored in a different variable x, as a string ("var67")(this x is generated from a different function). So from the value of x how can we access var67 attribute as we just can't do A.x . Please guide us any short approach other than building a method in class A to access variables in such case. Thanks! MyClass: variable = "blah" def function(self): print("This is a message inside the class.") myobjectx = MyClass() x="variable" myobjectx.(getattr(MyClass(), x)) The last line will throw a syntax error
downvote count: 4
has comment: http://stackoverflow.com/comment/84078655
upvote count: 0
has title: Accessing member attributes of a class when we the member attribute's name is stored in another variable
tagged with: syntax
score: -4
answer count: 1
tagged with: instance-variables
favorite count: 0
has comment: http://stackoverflow.com/comment/84078214
type: Question
has answer: http://stackoverflow.com/a/48541606
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84078220
has comment: http://stackoverflow.com/comment/84079706
tagged with: python

http://stackoverflow.com/q/48545198
tagged with: flask
answer count: 1
has body: Currently, I have a static JS file which is returned to user on a specific api request. The code which handles this is as follow @app.route('/js/&lt;path:path&gt;') def send_js(path): return send_from_directory('js', path) However, What i want to do is modify the current JS file (add some user specific modifications) and then return it to the user. Being a Java developer, I would have first read the file, made the in-memory modification and write those bytes to response object. However, while trying to google send_file and send_from_directory i couldn't find a way where i can provide content of the file? How should i implement this in flask?
linked to: http://stackoverflow.com/q/11017466
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48545323
duplicate of: http://stackoverflow.com/q/11017466
tagged with: download
type: Question
upvote count: 1
tagged with: python
type: UnansweredQuestion
has title: Sending a JS file in Flask

http://stackoverflow.com/q/48517547
type: Question
tagged with: python
type: UnansweredQuestion
score: 1
has body: I'm a newbie to Python and Flask, and I use Oracle, when learning Flask tutorial, I code as follow, but it smells really bad, please help me with these questions, thanks a lot! 1) need I release connection to poll explicitly? 2) how can I implement poll acquire and release gracefully? def get_dbpool(): if not hasattr(g, 'db_pool'): g.dbPool = connect_db() return g.dbPool @app.teardown_appcontext def close_db(error): if hasattr(g, 'db_pool'): g.dbPool.close() @app.route('/') def hello_world(): db = get_dbpool().acquire() cursor=db.cursor() sql='' cursor.execute(sql) rows = cursor.fetchall() cursor.close() get_dbpool().release(db) return json.jsonify(combines=rows)
has answer: http://stackoverflow.com/a/48545524
tagged with: cx-oracle
downvote count: 0
upvote count: 1
tagged with: flask
answer count: 1
favorite count: 0
has title: How to use cx_Oracle session pool with Flask gracefuly?

http://stackoverflow.com/a/48542174
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48532060
answers question: http://stackoverflow.com/q/48532060
type: Answer
score: 1
type: AcceptedAnswer
has body: You need to use private C API (as in link below) https://github.com/asmagill/hammerspoon_asm.undocumented/blob/master/coredock/coredock.h Or you can read dock settings and calculate it from /users//Library/Preferences/com.apple.dock.plist
downvote count: 0

skbio
tags question: http://stackoverflow.com/q/48631092
tag name: skbio
type: Tag

http://stackoverflow.com/a/67038209
score: 0
answers question: http://stackoverflow.com/q/48577014
has body: You can easily add the desired dimension with None afterwards x[:, j][:, None] but you can even go for including it in the indexing in the first place x[:, j, None]
type: Answer

http://stackoverflow.com/comment/84227110
type: Comment
has text: Are they using [`merlin`](https://github.com/CSTR-Edinburgh/merlin) as a dependency? It looks like `io_funcs.binary_io` is [this file](https://github.com/CSTR-Edinburgh/merlin/blob/master/src/io_funcs/binary_io.py)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48614998

http://stackoverflow.com/a/48613715
has comment: http://stackoverflow.com/comment/84224654
has comment: http://stackoverflow.com/comment/84225161
has comment: http://stackoverflow.com/comment/84478036
type: Answer
has comment: http://stackoverflow.com/comment/84224858
has comment: http://stackoverflow.com/comment/84224799
has comment: http://stackoverflow.com/comment/84224802
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84224763
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48613592
has comment: http://stackoverflow.com/comment/84224819
has body: By default, flask uses flask.json.JSONEncoder to encode objects as JSON. In order to jsonify your user-defined classes you will need to create a subclass of JSONEncoder that implements the serialisation of your class. How you implement the serialisation is up to you, but the easiest method is probably to convert your object into something that JSONEncoder already knows about (like a dict). Try adding this code to your app. (You should use the first version of the SiteConfig class that you posted, not your modified one). from flask.json import JSONEncoder # A customized JSON encoder that knows about your SiteConfig class class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, SiteConfig): return obj.__dict__ return JSONEncoder.default(self, obj) # Tell your flask app to use your customised JSON encoder app.json_encoder = CustomJSONEncoder With this you should get the response: { "config": { "category": "1", "command": "20c", "delay": 60, "frequency": 60 }, "statusCode": 200 } See here for a similar example.
accepted answer of: http://stackoverflow.com/q/48613592

http://stackoverflow.com/comment/84145674
score: 1
type: Comment
type: QuestionComment
has text: It only happens once. Try to modify the function again, then use `import temp` again, I don't think you'll see any further modifications, because the import system recognizes `temp` as already loaded.
comment on: http://stackoverflow.com/q/48574385

http://stackoverflow.com/a/48591004
has body: Regex: char+ meaning a+b+c+... Details: + Matches between one and unlimited times Python code: import re def LNDS(text): array = [] for y in range(97, 122): # a - z st = r"%s+" % chr(y) for x in range(y+1, 123): # b - z st += r"%s+" % chr(x) match = re.findall(st, text) if match: array.append(max(match, key=len)) else: break if array: array = [max(array, key=len)] return array Output: print(LNDS('abababababab abc')) &gt;&gt;&gt; ['abc'] print(LNDS('abcghiijkyxz')) &gt;&gt;&gt; ['ghiijk'] For string abcghiijkyxz regex pattern: a+b+ i+j+k+l+ a+b+c+ j+k+ a+b+c+d+ j+k+l+ b+c+ k+l+ b+c+d+ l+m+ c+d+ m+n+ d+e+ n+o+ e+f+ o+p+ f+g+ p+q+ g+h+ q+r+ g+h+i+ r+s+ g+h+i+j+ s+t+ g+h+i+j+k+ t+u+ g+h+i+j+k+l+ u+v+ h+i+ v+w+ h+i+j+ w+x+ h+i+j+k+ x+y+ h+i+j+k+l+ y+z+ i+j+ i+j+k+ Code demo
has comment: http://stackoverflow.com/comment/84180552
has comment: http://stackoverflow.com/comment/84180077
type: Answer
has comment: http://stackoverflow.com/comment/84183502
answers question: http://stackoverflow.com/q/48588490
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48612859
tagged with: python
has comment: http://stackoverflow.com/comment/84223055
has comment: http://stackoverflow.com/comment/84222541
answer count: 0
score: 1
has body: I'm writing a small program in C++ that runs a Python script which relies on the popular requests Python module. I use C++'s popen() function to run a Python script and read the input like so: std::string command = "./fetch.py"; and pass it in to popen() like so: FILE *in = popen(command.c_str(), "r"); I then use fgets() in a while loop to get all of the output from the script and store each line in a C++ std::vector&lt;std::string&gt;. The issue lies in running the Python script. I've globally installed the requests library (no need for virtual environment since this is the only program my machine will run) and ensured that it can run using the command sh ./fetch.py after running chmod +x ./fetch.py. However, when ran with popen() inside the C++ program, the Python script throws an import error, claiming that the module requests is not found. I've double checked Python's sys.path to ensure that it includes the path for the requests module. I've also tried appending /bin/bash/ -c to the command passed into popen() in hopes of running the script with bash, and the same thing happened. I'm running this on a Raspberry Pi with the most recent Raspbian Lite distribution, a Linux derivative, and running the script using Python 3. I installed the requests module globally using pip3. I am stumped as to why my Python script can find the requests module when ran from the command line, but not with popen() inside my C++ program, so any help or suggestions are appreciated!
has comment: http://stackoverflow.com/comment/84222402
favorite count: 0
tagged with: c++
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/84222424
has title: Calling Python from C++ popen() function
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84222409
has comment: http://stackoverflow.com/comment/84222388
upvote count: 1

recursion
type: Tag
tags question: http://stackoverflow.com/q/48510148
tags question: http://stackoverflow.com/q/48581058
tags question: http://stackoverflow.com/q/48535063
tags question: http://stackoverflow.com/q/48561957
tags question: http://stackoverflow.com/q/48593472
tag name: recursion
tags question: http://stackoverflow.com/q/48504062
tags question: http://stackoverflow.com/q/48574533
tags question: http://stackoverflow.com/q/48615952
tags question: http://stackoverflow.com/q/48624364
tags question: http://stackoverflow.com/q/48551523
tags question: http://stackoverflow.com/q/48602016
tags question: http://stackoverflow.com/q/48614576
tags question: http://stackoverflow.com/q/48591755
tags question: http://stackoverflow.com/q/48514162
tags question: http://stackoverflow.com/q/48543779
tags question: http://stackoverflow.com/q/48511374

http://stackoverflow.com/a/56848909
upvote count: 6
has comment: http://stackoverflow.com/comment/100921310
answers question: http://stackoverflow.com/q/48590268
downvote count: 1
has body: to get top 5: dataframe['name'].value_counts()[0:5]
score: 5
type: Answer

http://stackoverflow.com/q/48599923
downvote count: 0
score: 1
upvote count: 1
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/7852855
has title: Converting time format for column of pandas dataframe
favorite count: 0
type: Question
has body: I have a pandas timeframe that has a column in this time format: e.g. 05:00:00 (hour, minute, seconds). These values are extracted off my SQL database via pandas with the following query function df = pd.read_sql("SELECT .....'" \ , con=mariadb_connection) I would like to convert these time values into minutes (or seconds) as I would like to perform linear regression on the values which are my time duration variable. How can I go about doing that? Is there a way I can convert these values (e.g. multiply 60 to 14 of 14:30:00 and add to 30, to get the total duration in minutes i.e 870) into duration values without the : and then place them back into the same rows and columns of the dataframe for further analysis? Currently, I cannot work with the current time format as scikit linear regression function does not accept this format into one of the function's argument. Example dataframe: voltage valueA Duration valueB 0 12.45 0.86 14:04:30 9.157145 1 12.52 0.61 14:02:32 10.010095 2 12.24 0.17 14:00:33 10.010095
has comment: http://stackoverflow.com/comment/84196494
tagged with: datetime
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/84196428
has answer: http://stackoverflow.com/a/48599970
accepted answer: http://stackoverflow.com/a/48599970
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/84196502
answer count: 1

http://stackoverflow.com/q/48628778
type: Question
has body: I tried the code in open AI gym documentation. It works but errors occur after I close the window. The code I used is below: import gym env = gym.make('CartPole-v0') for i_episode in range(20): observation = env.reset() for t in range(100): env.render() print(observation) action = env.action_space.sample() observation, reward, done, info = env.step(action) if done: print("Episode finished after {} timesteps".format(t+1)) break And here is the error: File "&lt;ipython-input-3-b38d53bb166b&gt;", line 1, in &lt;module&gt; runfile('D:/Python/openAIGym.py', wdir='D:/Python') File "D:\Anaconda\envs\tensorflow\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "D:\Anaconda\envs\tensorflow\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "D:/Python/openAIGym.py", line 6, in &lt;module&gt; env.render() File "D:\Anaconda\envs\tensorflow\lib\site-packages\gym\core.py", line 150, in render return self._render(mode=mode, close=close) File "D:\Anaconda\envs\tensorflow\lib\site-packages\gym\core.py", line 286, in _render return self.env.render(mode, close) File "D:\Anaconda\envs\tensorflow\lib\site-packages\gym\core.py", line 150, in render return self._render(mode=mode, close=close) File "D:\Anaconda\envs\tensorflow\lib\site-packages\gym\envs\classic_control\cartpole.py", line 146, in _render return self.viewer.render(return_rgb_array = mode=='rgb_array') File "D:\Anaconda\envs\tensorflow\lib\site-packages\gym\envs\classic_control\rendering.py", line 104, in render self.window.flip() File "D:\Anaconda\envs\tensorflow\lib\site-packages\pyglet\window\win32\__init__.py", line 311, in flip self.context.flip() AttributeError: 'NoneType' object has no attribute 'flip' BTW, this is in python 3.6.
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48729052
tagged with: openai-gym
has title: AttributeError: 'NoneType' object has no attribute 'flip' when using gym
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48566405
accepted answer of: http://stackoverflow.com/q/48566268
has body: You can usingto_datetime df['Dateofbirth']=pd.to_datetime(df['Dateofbirth'],errors='coerce') df['Age']=(pd.to_datetime('2017-03-31')-df['Dateofbirth']).dt.days/365.25 df.fillna('unknow') Out[370]: Dateofbirth Age 0 1957-04-30 00:00:00 59.9179 1 1966-11-10 00:00:00 50.3874 2 1966-11-10 00:00:00 50.3874 3 unknow unknow 4 1958-10-28 00:00:00 58.423 5 1958-06-04 00:00:00 58.8227
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48566268
type: Answer

http://stackoverflow.com/q/48606245
linked to: http://stackoverflow.com/q/37164675
score: 1
answer count: 1
downvote count: 0
tagged with: web-scraping
upvote count: 1
tagged with: python-requests
favorite count: 0
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84211579
has comment: http://stackoverflow.com/comment/84212229
tagged with: session
has body: I am trying to scrape the bookmyshow website for finding out movie details like at what time tickets are available and how many seats are available. I have got to find how to get the show timings in which seats are available but now i want to get total seats avaialble in that show. My code is : import requests from bs4 import BeautifulSoup import json base_url = "https://in.bookmyshow.com" s =requests.session() headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"} r = s.get("https://in.bookmyshow.com/vizag/movies", headers = headers) print(r.status_code) soup = BeautifulSoup(r.text,"html.parser") movies_list = soup.find("div",{"class":"__col-now-showing"}) movies = movies_list.findAll("a",{"class":"__movie-name"}) for movie in movies: print(movie.text) show = [] containers = movies_list.findAll("div",{"class":"card-container"}) for container in containers: try: detail = container.find("div",{"class":"__name overflowEllipses"}) button = container.find("div",{"class":"book-button"}) print(detail.text) print(button.a["href"]) url_ticket = base_url + button.a["href"] show.append(url_ticket) except: pass for i in show: print(i) for t in show: res = s.get(t,headers=headers) bs = BeautifulSoup(res.text,"html.parser") movie_name = bs.find("div",{"class":"cinema-name-wrapper"}) print(movie_name.text.replace(" ","").replace("\t","").replace("\n","")) venue_list = bs.find("ul",{"id":"venuelist"}) venue_names = venue_list.findAll("li",{"class":"list"}) try: for i in venue_names: vn = i.find("div",{"class":"__name"}) print(vn.text.replace(" ","").replace("\t","").replace("\n","")) show_times = i.findAll("div",{"data-online":"Y"}) for st in show_times: print(st.text.replace(" ","").replace("\t","").replace("\n","")) except: pass print("\n") heads = { "accept":"*/*", "accept-encoding":"gzip, deflate, br", "accept-language":"en-US,en;q=0.9", "origin":"https://in.bookmyshow.com", "referer":"http…
tagged with: python
has title: Scraping seat layout page of book my show using python
has answer: http://stackoverflow.com/a/48606800

http://stackoverflow.com/comment/83977939
has text: @DavidParks my preferred solution is to simply define a factory function, e.g. `def factory(start): return lambda: mygen(start)` then `gs = [factory(start) for start in some_list]`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48492234
score: 1

http://stackoverflow.com/comment/84203391
type: QuestionComment
comment on: http://stackoverflow.com/q/48603340
has text: The scope of the loop variable `x` is the set comprehension itself (everything from `{` to `}`). It does not exist outside of the braces.
score: 1
type: Comment

http://stackoverflow.com/comment/84276217
comment on: http://stackoverflow.com/q/48639401
score: 0
has text: Yes, we are having a project skeleton built on Python 2.7.5
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48501742
has body: Ah the wonders of open source. Curious, I went and looked at the mintapi you linked, to see if there was anything obvious and simple I could do to recreate the object instance without the arduous setup. It turns out there isn't, really. :( Here is what is called when you instantiate the Mint object: def __init__(self, email=None, password=None): if email and password: self.login_and_get_token(email, password) As you can see, if you don't give it a truthy email and password, it doesn't do anything. (As a sidenote, it should really be checking is None, but whatever). So, we can avoid having do go through the setup process nice and easily, but now we need to find out how to fake the setup process based on previous data. Looking at .login_and_get_token(), we see the following: def login_and_get_token(self, email, password): if self.token and self.driver: return self.driver = get_web_driver(email, password) self.token = self.get_token() Nice and simple, again. If it already has a token, it's done, so it goes away. If not, it sets a driver, and sets .token by calling .get_token(). This makes the whole process really easy to override. Simply instantiate a Mint object with no arguments like so: mint = mintapi.Mint() Then set the .token on it: mint.token = 'something magical' Now you have an object that is in an almost ready state. The problem is that it relies on self.driver for basically every method call, including your .initiate_account_refresh(): def initiate_account_refresh(self): self.post( '{}/refreshFILogins.xevent'.format(MINT_ROOT_URL), data={'token': self.token}, headers=JSON_HEADER) ... def post(self, url, **kwargs): return self.driver.request('POST', url, **kwargs) This looks like it's a simple POST that we could replace with a requests.post() call, but I suspect that seeing as it's doing it through the web browser that it's relying on some manner of cookies or session storage. If you wanted to experiment, you could subclass Mint like so: class HeadlessMint(Min…
has comment: http://stackoverflow.com/comment/83997396
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83997437
type: Answer
answers question: http://stackoverflow.com/q/48501276
has comment: http://stackoverflow.com/comment/83997535

http://stackoverflow.com/comment/91289296
type: Comment
has text: Thanks for the suggestion, but my question is really about how to interpret mongo queries against documents stored locally in memory
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52160022

http://stackoverflow.com/comment/84105714
score: 0
has text: @Shadow I have two different folders. How do you create a specific server based on each folder.
type: QuestionComment
comment on: http://stackoverflow.com/q/48554683
type: Comment

django-urls
tags question: http://stackoverflow.com/q/48554190
tags question: http://stackoverflow.com/q/48534047
type: Tag
tags question: http://stackoverflow.com/q/48524468
tags question: http://stackoverflow.com/q/48637431
tags question: http://stackoverflow.com/q/48608894
tags question: http://stackoverflow.com/q/48571418
tags question: http://stackoverflow.com/q/48491431
tag name: django-urls

http://stackoverflow.com/comment/84022480
type: Comment
type: QuestionComment
has text: I have done that without forms. Directly linking view to model. Thanks for the answer.
score: 0
comment on: http://stackoverflow.com/q/48512876

http://stackoverflow.com/comment/84199473
comment on: http://stackoverflow.com/q/48601420
has text: Yes. `preprocessing.scale`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83997081
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48501822
type: QuestionComment
has text: Possible duplicate of [Sort a series by month name?](https://stackoverflow.com/questions/48042915/sort-a-series-by-month-name)

http://stackoverflow.com/comment/84046550
type: AnswerComment
comment on: http://stackoverflow.com/a/48525334
type: Comment
has text: im getting an error "context['SiteID']=self.site_id" - 'AddSubnet' object has no attribute 'site_id'
score: 0

http://stackoverflow.com/comment/84122910
has text: `l = [1, 2, 3]`; `for x in l: ...`;
type: Comment
comment on: http://stackoverflow.com/q/48563600
score: 0
type: QuestionComment

http://stackoverflow.com/a/48645371
upvote count: 5
type: Answer
has body: Just don't name your methods with two __ like in .__delete. This is not for "private" methods, regardless of the misleading documentation you may have read - this just causes the method name to be mangled with the class name it is declared in. So, a call to self.__delete on a subclass will try to find a .__delete on that subclass, and only there, and will never call the same method on the superclass - and the converse is also true: if a you have such a call on the abstract superclass, the subclass method is never called, becuase internally they are renamed to include the class names as prefix. Just use a single _ and things should start working as you expect.
answers question: http://stackoverflow.com/q/48645049
score: 5
has comment: http://stackoverflow.com/comment/84287980
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48645049
downvote count: 0

http://stackoverflow.com/q/48632585
has title: How to generate json using Jinja2 Template Engine
tagged with: templates
possible better answer: http://stackoverflow.com/a/48634163
upvote count: 10
tagged with: jinja2
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48634163
has body: I am trying to generate a json file from a .xlsx file. so far I was able to get data from the file but I am not sure how to put them on json using jinja2. There is a problem in template structure. How can I solve this? Output should be like this "Matches": { "1": { "time": "19:00", "teams": "Team 1 - Team 2" }, "2": { "time": "21:00", "teams": "Team 3 - Team 4" }, ... ... ... } My code is something like this. Obviously template section is wrong. from openpyxl import load_workbook from jinja2 import Template start_coloumn_of_matches = 3 end_coloumn_of_matches = 20 wb = load_workbook(filename = 'myfile.xlsx') sheet_ranges = wb['Sheet1'] keys = [] teams = [] times = [] for x in range(start_coloumn_of_matches, end_coloumn_of_matches + 1): team_column = 'A' + str(x) time_column = 'D' + str(x) teams.append(sheet_ranges[team_column].value) times.append(sheet_ranges[time_column].value) keys.append(x) template = Template(''' "Matches": { {% for key in keys %} "{{key}}": {% endfor %} { {% for team in teams %} "teams": "{{team}}", {% endfor %} {% for time in times %} "time": "{{time}}" {% endfor %} } }, ''' ) print(template.render(teams = teams, times = times, keys = keys))
score: 10
tagged with: python
has answer: http://stackoverflow.com/a/70086462
has answer: http://stackoverflow.com/a/48720031
type: AnsweredQuestion
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/48720031
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/48585912
answers question: http://stackoverflow.com/q/48585807
score: -2
type: Answer
has body: Python evaluation is lazy. It will only be evaluated when it's actually needed. https://swizec.com/blog/python-and-lazy-evaluation/swizec/5148 Lazy evaluation python
has comment: http://stackoverflow.com/comment/84168758
upvote count: 0
downvote count: 2

http://stackoverflow.com/comment/84214784
has text: I'm glad it worked. I'm sure the output could be changed, but that seems like a different question. You asked how to reproduce `git log --numstat`, which is what my answer does. Please ask about formatting as a separate question, and I or someone else would be happy to help! Since this answer does satisfy your original post, please accept it if you would.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48602152
score: 0

http://stackoverflow.com/comment/84063839
has text: This is the way to do it. Great work. Only issue is mutating the original dict, if that is acceptible.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48534139

http://stackoverflow.com/q/48617624
has answer: http://stackoverflow.com/a/48619059
answer count: 2
possible better answer: http://stackoverflow.com/a/48618850
has title: Selenium is normal during debugging, but the run click fails
has answer: http://stackoverflow.com/a/48618850
downvote count: 0
tagged with: selenium
upvote count: 1
type: Question
tagged with: phantomjs
has body: I've searched several solutions but it didn't work. That's my code driver = webdriver.PhantomJS() driver.get('https://baijia.baidu.com') wait = WebDriverWait(driver,10) wait.until(EC.element_to_be_clickable((By.ID, 'getMoreArticles'))).click() content = driver.page_source page = open('test.html','wb') page.write(content) I've tried to debug the code, It successfully returns the clicked page. when I run the code, it also returns successfully, however it don't returns the clicked page, just the source page. I tried to search the solutions, take the page down to the bottom: driver.execute_script("window.scrollTo(0, document.body.scrollHeight)",element) But it's the same result, only debug successfully. Thanks
score: 1
has comment: http://stackoverflow.com/comment/84232803
tagged with: python
accepted answer: http://stackoverflow.com/a/48619059
favorite count: 0
has comment: http://stackoverflow.com/comment/84233116
type: AnsweredQuestion

http://stackoverflow.com/comment/84197913
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48577485
type: AnswerComment
has text: I don't really understand what is not clear. Yes, `iterrows` yields rows of a dataframe along with corresponding indices, but use of it is justified if you actually use those rows. In your case you are using only the indices. Either use `row` or don't use `iterrows` at all. So, for example, either `for _, row in df.iterrows(): print(pd.DataFrame(row).T)` or `for i in range(df.shape[0]): print(df[i:i+1])`

http://stackoverflow.com/comment/84215913
has text: agreed, took my comments back
type: QuestionComment
comment on: http://stackoverflow.com/q/48609632
score: 0
type: Comment

http://stackoverflow.com/q/48633250
has comment: http://stackoverflow.com/comment/84265928
has title: Getting more than 100 days of data web scraping Yahoo
score: 0
answer count: 3
tagged with: finance
tagged with: screen-scraping
tagged with: stockquotes
tagged with: python
has answer: http://stackoverflow.com/a/48877867
type: Question
has answer: http://stackoverflow.com/a/53600261
has body: Like many others I have been looking for an alternative source of stock prices now that the Yahoo and Google APIs are defunct. I decided to take a try at web scraping the Yahoo site from which historical prices are still available. I managed to put together the following code which almost does what I need: import urllib.request as web import bs4 as bs def yahooPrice(tkr): tkr=tkr.upper() url='https://finance.yahoo.com/quote/'+tkr+'/history?p='+tkr sauce=web.urlopen(url) soup=bs.BeautifulSoup(sauce,'lxml') table=soup.find('table') table_rows=table.find_all('tr') allrows=[] for tr in table_rows: td=tr.find_all('td') row=[i.text for i in td] if len(row)==7: allrows.append(row) vixdf= pd.DataFrame(allrows).iloc[0:-1] vixdf.columns=['Date','Open','High','Low','Close','Aclose','Volume'] vixdf.set_index('Date',inplace=True) return vixdf which produces a dataframe with the information I want. Unfortunately, even though the actual web page shows a full year's worth of prices, my routine only returns 100 records (including dividend records). Any idea how I can get more?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50337450

http://stackoverflow.com/a/48530324
type: Answer
has body: Your list doesn't have anything at the beginning. So you need to zerofill it to access all the element by index without inserting them explicitly. x=[0] * bins for i in range(0, len(data)): comp = data[i] for j in range(0, bins): lorng=lo+(j*binwidth) hirng=lo+((j+1)*binwidth) if comp==lo: x[0]+=1 #increment lowest value bin for lowest value data if comp &gt; lorng and comp &lt;= hirng: x[j]+=1 #increment bin for data in a given range print(x) It's worth noting that x = [0] * bins initializes the list x with bins zeroes.
answers question: http://stackoverflow.com/q/48530092
score: 0

http://stackoverflow.com/comment/84101912
score: 2
type: Comment
type: QuestionComment
has text: It looks like your method should work. Maybe one of the other fields is whitespace? _e.g._: `' '`.
comment on: http://stackoverflow.com/q/48552470

http://stackoverflow.com/comment/84048834
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48526580
has text: Are you sure `utable.npy` is not empty?

http://stackoverflow.com/q/48589348
has comment: http://stackoverflow.com/comment/84177031
favorite count: 0
accepted answer: http://stackoverflow.com/a/48589957
type: Question
has answer: http://stackoverflow.com/a/48589957
has title: Filter list based on peewee query
score: 1
tagged with: python
has body: Given the following model: class User(BaseModel): name = peewee.CharField() and a list of names: names = ['Laurence', 'Emily', 'Rose', 'Chris', 'Isaac'] how can I filter such a list based on if a User exists in the database with a name equal to any name in the list, but without having to make a query for each element in the list? For example, if users with names "Laurence" and "Rose" existed, how could I filter my list of names to ['Emily', 'Chris', 'Isaac'] without doing something like: [name for name in names if not User.select().where(User.name == name).exists()]
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84175790
tagged with: peewee
downvote count: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/84049883
type: Comment
comment on: http://stackoverflow.com/q/48527304
type: QuestionComment
has text: What have you tried so far? How are you importing the data from the Excel? Can you show us what you have?
score: 1

http://stackoverflow.com/q/48605163
score: 0
has comment: http://stackoverflow.com/comment/84256310
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/84248669
tagged with: django-orm
answer count: 1
linked to: http://stackoverflow.com/q/44665361
tagged with: django
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48617401
has comment: http://stackoverflow.com/comment/84226609
has body: I'm trying to determine how to construct a query. I have two models from an external database that I"m trying to import into a different schema. The source data has three models: class Group(model): ... name = models.CharField() class Person(model): ... name = models.CharField() class Membership(model): ... status = models.CharField() created_date = models.DateTimeField() modified_date = models.DateTimeField() person = models.ForeignKey( 'Person', related_name='memberships', ) group = models.ForeignKey( 'Group', related_name='memberships', ) In the Memberships, I have fields representing the person and band, with create dates and update dates, as well as other relevant data. Here's the problem: the Membership rows don't have any field that represents which is the canonical record, and they mix and match persons and dates and other data. What I'm doing currently is taking all the Memberships for a given band, running distinct on them for the combination of band and person and using those results to query the Memberships again for the latest instance of each particular combination. While this works, as you might imagine is is unspeakably slow and I know there must be a better way. So I'm looking for how to use some of the advanced django query expressions (Window? Over, F-expressions?) to get this done as much as possible on the database. Here is the code that is getting me the records I want: groups = (the groups I want) for group in groups: unique_members = group.members.values( 'person', 'group', ).distinct() for member in members: current_member = group.members.filter( person__id=member['person'], group__id=member['structure'], ).lastest('created_date', 'modified_date') With current_member being the most recent membership entry for that unique person/group combination. So for a list of memberships like this: Person Group Created Status John Lennon Beatles 1960-01-01 Current Paul McCartney Beatles 1960-01-01 Current Pete Best Beatles 1960-01-01 Expired George Harri…
has answer: http://stackoverflow.com/a/48617401
has comment: http://stackoverflow.com/comment/84219377
tagged with: django-models
tagged with: python
has title: how to construct this Django ORM queryset query?
type: Question

http://stackoverflow.com/a/48617673
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48617580
accepted answer of: http://stackoverflow.com/q/48617580
has comment: http://stackoverflow.com/comment/84237769
type: Answer
has body: You are just comparing the values that's why you are getting only False values Use this expression with dataframe. df=df[(df['STime'] &gt; '7:00:00') and (df['ETime'] &lt; '18:00:00')]
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84237627

http://stackoverflow.com/comment/84022519
has text: use in [pagination](https://docs.djangoproject.com/en/2.0/topics/pagination/) and process each page in parallel.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48513797
type: QuestionComment

http://stackoverflow.com/q/48596710
has title: Remove plot margins for area plot
has answer: http://stackoverflow.com/a/48597018
upvote count: 2
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48597018
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: matplotlib
answer count: 1
tagged with: python
has body: I have these data and I plot like: df.plot.area() plt.margins(0, 0) plt.show() which gives me this: The result is cool but how do I get rid of the top white margin?
type: Question

http://stackoverflow.com/q/48575783
favorite count: 0
has comment: http://stackoverflow.com/comment/84148569
has answer: http://stackoverflow.com/a/48577329
has comment: http://stackoverflow.com/comment/84148420
has comment: http://stackoverflow.com/comment/84165114
has comment: http://stackoverflow.com/comment/84148170
tagged with: python
has comment: http://stackoverflow.com/comment/84148253
score: -1
type: Question
tagged with: numpy
tagged with: python-3.x
upvote count: 0
has title: Apply a vectorized function to array numpy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84148217
answer count: 1
downvote count: 1
has body: I want to apply a function to an array, but when I call it, it generates an error since the function only enters the first component of the array import numpy as np def fObjetivo(x): print(x) return x[0] + x[1] + x[2] fObjetivo = np.vectorize(fObjetivo) a = np.array([1,2,3]) print(fObjetivo(a)) where are the error?

http://stackoverflow.com/comment/84124916
type: Comment
type: QuestionComment
has text: You need to iterate over every `subword in word`.
comment on: http://stackoverflow.com/q/48564565
score: 1

http://stackoverflow.com/comment/84082835
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48542449
has text: Can you please give reason for negative down vote on question?

http://stackoverflow.com/a/58579665
has body: Just as a side note in case anyone still has this issue, this is an issue of backward compatibility with Keras1.x. "border_mode" used to exist as an argument to the Convolution2D class in (at least) Keras1.1.0 and as such is still hanging around in a lot of older code. In Keras2 series (I referenced 2.3.1) you will see that almost the entire API to Convolution2D has changed, so if you are porting a repository using an older version of Keras I doubt border_mode would be the biggest of your concerns.
answers question: http://stackoverflow.com/q/48525060
upvote count: 5
type: Answer
score: 5
downvote count: 0

http://stackoverflow.com/comment/84145260
comment on: http://stackoverflow.com/q/48574201
has text: Do those two comments solve your problem? You have to send in the input argument, return the appropriate value, and assign that to a local variable.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48509910
answers question: http://stackoverflow.com/q/48509590
has body: It is likely that your blank values are actually nan rather than "". You can change this as follows: data3 = data3.fillna("") before your tests.
has comment: http://stackoverflow.com/comment/89842132
type: Answer
has comment: http://stackoverflow.com/comment/84096441
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48509590

http://stackoverflow.com/q/48611967
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84221119
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48704154
tagged with: python-3.x
tagged with: debugging
has answer: http://stackoverflow.com/a/57621258
possible better answer: http://stackoverflow.com/a/57621258
score: 3
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/84228377
has title: Unable to debug Django process from vs code
has answer: http://stackoverflow.com/a/49169737
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84222688
accepted answer: http://stackoverflow.com/a/48704154
type: AnsweredQuestion
answer count: 3
has body: Im trying to debug my Django process from vs code. But I am not able to get it to work. In my manage.py: import ptvsd try: ptvsd.enable_attach("my_secret", address=('localhost', 3000)) except: pass In my docker-compose: version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" - "3000:3000" depends_on: - db And my debug info in launch.json: { "name": "Attach (Remote Debug)", "type": "python", "request": "attach", "localRoot": "${workspaceFolder}", "remoteRoot": "/code", "port": 3000, "secret": "my_secret", "host": "localhost" }, Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ EXPOSE 3000 When starting the debug session I get a message saying: "debug adapter process has terminated unexpectedly". Does anyone have any tips on how to get this working? Im running ptvsd 3.0.0 both on my computer and in the docker container.

http://stackoverflow.com/a/48739367
has comment: http://stackoverflow.com/comment/93986091
answers question: http://stackoverflow.com/q/48495648
has comment: http://stackoverflow.com/comment/91479910
downvote count: 0
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/48495648
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91496752
has comment: http://stackoverflow.com/comment/94005428
has comment: http://stackoverflow.com/comment/123714556
has comment: http://stackoverflow.com/comment/84488503
has body: This is possible. Each response includes an end_cursor parameter. In your next request add a max_id parameter using the value of end_cursor, like so: https://www.instagram.com/explore/tags/losangeles/?__a=1&amp;max_id=&lt;value&gt;. I have a working example here written in react/axios: https://codepen.io/ghostreef/pen/ZrKrXX. My example pulls from a user account, so my response xml is different. The end_cursor for tags is at data.graphql.hashtag.edge_hashtag_to_media.page_info.end_cursor and the image data is at data.graphql.hashtag.edge_hashtag_to_media.edges and you'll have to iterate over the nodes.
type: Answer

http://stackoverflow.com/q/48598215
type: Question
answer count: 2
upvote count: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48598910
has title: Multiple shifts on dataframe
has body: I would like to repeatedly shift select columns of a a dataframe based on the number of shifts specified in array nShiftsPerCol. How to generate the output dataframe DFO that contains the columns with nonzero shifts specified and each of those columns shifted multiple times. Note, the first shift is zero or no shift. Append the shift number to the column name. import pandas as pd import numpy as np df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [2, 3, 4, 5, 6], 'C': [3, 4, 5, 6, 7]}) print(df) nCols = df.shape[0] nShiftsPerCol = np.zeros(nCols) nShiftsPerCol[0]=3 # shift column A 3 times nShiftsPerCol[2]=2 # shift column C 2 times Original dataframe A B C 0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 Desired output A_0 A_1 A_2 C_0 C_1 0 1 2 3 3 4 1 2 3 4 4 5 2 3 4 5 5 6 3 4 5 NA 6 7 4 5 NA NA 7 NA
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48598317
has answer: http://stackoverflow.com/a/48598317
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/48598910

http://stackoverflow.com/q/48530710
tagged with: python
tagged with: numpy
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48530924
tagged with: arrays
answer count: 1
has body: Having a 3-dimensional numpy array A I want to get all the edges (imagine this array as a cuboid). Well, A[0, 0, :] would give me one edge, A[0, -1, :] second one and A[:, -1, -1] yet another one... so all I'd have to do is get all permutations of 0, -1 and : and use them as indices. Zero and minus one are easy, but how would I do this with colon? I can solve it the long way, but it's ugly and I bet there is some neat numpy solution to this. Something like: for indices in permutations([0, -1, ':']): edge = A[indices] ... What I want to do in the end is numpy.any() on the set of all edges to see if all edge-values are zero.
has title: Get all edges of a cuboid (3D NumPy array)
tagged with: indexing
accepted answer: http://stackoverflow.com/a/48530924
type: Question

http://stackoverflow.com/q/48562123
accepted answer: http://stackoverflow.com/a/48563539
has answer: http://stackoverflow.com/a/48563539
tagged with: python
favorite count: 0
type: Question
tagged with: interpolation
has body: I have a pandas dataframe with column of year month data(yyyymm). I am planning on interpolate data to daily &amp; weekly values. Here is my df below. df: 201301 201302 201303 ... 201709 201710 a 0.747711 0.793101 0.771819 ... 0.818161 0.812522 b 0.776537 0.759745 0.733673 ... 0.757496 0.765181 c 0.801699 0.847655 0.796586 ... 0.784537 0.763551 d 0.797942 0.687899 0.729911 ... 0.819887 0.772395 e 0.777472 0.799676 0.782947 ... 0.804533 0.791759 f 0.780933 0.750774 0.781056 ... 0.790846 0.773705 g 2.071699 2.261739 2.126915 ... 1.891780 2.098914 As you can see that my df is in montly column data and I am hoping to change this to daily values. I am planning on using linear functions. Here is example. # (201302 - 201301)/31 (since January 2013 has 31 days) a = (0.793101-0.747711)/31 # now a is the daily increasing (or decresing depends on values) value for a day. # 2013-01-01 value woud be 0.747711 # 2013-01-02 value woud be 0.747711 + a # 2013-01-03 value woud be 0.747711 + (a*2) # last day of January would be 0.747711 + (a*30) # first day of Feb would be 0.747711 + (a*31) which is 0.793101 (201302 value) So my df_daily would have every day from 2013 to 2017 Oct(first day) and the values would be just like above. I am very week on working with timestamps so it would be great if there is any way to interpolate my value from month to day values. Thanks! Oh please let me know if my question is confusing...
tagged with: time-series
upvote count: 2
answer count: 1
downvote count: 0
tagged with: timestamp
score: 2
has title: Python Interpolate Monthly value to Daily value (linear): Pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84120859
has comment: http://stackoverflow.com/comment/84120692
has comment: http://stackoverflow.com/comment/84120938
tagged with: pandas

http://stackoverflow.com/a/48535622
answers question: http://stackoverflow.com/q/48535166
has comment: http://stackoverflow.com/comment/84093056
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48535166
has body: Try this : if choice=='Y' or choice=='y': break return data[i] elif choice=='N' or choice=='n': continue and I don't understand why that break is there if you are returning something.

http://stackoverflow.com/comment/84144315
comment on: http://stackoverflow.com/q/48573742
score: 0
type: Comment
type: QuestionComment
has text: It's making an `int` out of every character in the result of `str` on a number...

http://stackoverflow.com/comment/84262921
has text: Yes, thank you so much for looking at it.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48632765

http://stackoverflow.com/q/48615377
type: AnsweredQuestion
has body: I'm making some plots of ocean temperature and salinity from data I have pulled from a NetCDF file. They are being used as frames in animations I'm making using the moviepy library. Packages I'm using: from netCDF4 import Dataset # reads netCDF file import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap # basemap tools from datetime import datetime, timedelta #for working with datetimes import moviepy.editor as mpy # creates animation from moviepy.video.io.bindings import mplfig_to_npimage # converts map to numpy array from matplotlib.backends.backend_agg import FigureCanvasAgg # draws canvas so that map can be converted When I draw the plots by themselves they look fine. Here's an exaple of the salinity map. # map setup fig = plt.figure() fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9) # Setup the map m = Basemap(projection='merc', llcrnrlat=-38.050653, urcrnrlat=-34.453367,\ llcrnrlon=147.996456, urcrnrlon=152.457344, lat_ts=20, resolution='h') # draw stuff m.drawcoastlines() m.fillcontinents(color='black') # plot salt cs = m.pcolor(lons,lats,np.squeeze(salt), latlon = True ,vmin=salt_min, vmax=salt_max, cmap='viridis') # plot colourbar plt.colorbar() # datetime title plt.title('Regional - Salinity (PSU)\n' + frame_time.strftime("%Y-%m-%d %H:%M:%S") + ' | ' + str(fname) + '_idx: ' + str(frame_idx)) # stop axis from being cropped plt.tight_layout() However I want to plot temperature and salinity side by side but when I do the colour bars and figures don't draw as I would expect. # set up figure fig = plt.figure() fig.subplots_adjust(left=0., right=1., bottom=0., top=0.9) # Temperature figure plt.subplot(1, 2, 1) # Setup the map m = Basemap(projection='merc', llcrnrlat=-38.050653, urcrnrlat=-34.453367,\ llcrnrlon=147.996456, urcrnrlon=152.457344, lat_ts=20, resolution='h') # draw stuff m.drawcoastlines() m.fillcontinents(color='black') # plot salt cs = m.pcolor(lons,lats,np.squeeze(temp), latlon = True ,vmin=temp_min, …
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48615666
favorite count: 0
type: Question
upvote count: 2
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/23876588
tagged with: subplot
answer count: 1
tagged with: python
has title: Plots draw incorrectly when attempting to make subplots in Matplotlib
accepted answer: http://stackoverflow.com/a/48615666
tagged with: plot

http://stackoverflow.com/comment/84019373
type: QuestionComment
comment on: http://stackoverflow.com/q/48511429
score: 0
has text: @NathanVērzemnieks I admit that I'm still trying to wrap my head around it...
type: Comment

http://stackoverflow.com/q/48571792
tagged with: cmd
has body: I am trying to add an option to my help section inside my python code. When the user runs the cmd call with the -h they will be prompted the following below. If they do not know what show is available, I want the to choose the option -sl which will run a cmd and output the list as a result in the same terminal. Because of my inexperience and the cmd involving awk, the quotations are also proving to be an issue. Untouched command line call is a follows: jobsinfo --allshow | awk -F "[, ]+" '/jobs/{print $(NF-1)}' showlist = "jobsinfo --allshow | awk -F " + "[, ]+" + "'/jobs/{print $(NF-1)}'" # Help section parser = argparse.ArgumentParser(description="Check the render queue for a time period") parser.add_argument("-l", "--location", default=site, help="The location you want to check. ""#Examples: london, denver, montreal...") parser.add_argument("-p", "--project", default="New", help="The project you want to check. The Default is set to new. " "#Examples: Please see SHOW list here: http://dnet.dneg.com/display/COMMS/SHOW+INFORMATION") # parser.add_argument("-sl", "--showlist", action=showlist, help="List the Shows currently on Servers.") parser.add_argument("-d", "--days", type=int, default=14, help="The number of days you wish to go back. The default is set to 14 days. " "#Examples: -d 3, -d 9, -d 14") args = parser.parse_args() Any help would be greatly appreciated. Thanks!
type: Question
score: 0
tagged with: awk
type: UnansweredQuestion
tagged with: python
answer count: 1
tagged with: linux
tagged with: bash
has answer: http://stackoverflow.com/a/48598116
has title: Python Add CMD Call to ArgeParse

http://stackoverflow.com/q/48572201
has body: I'm building a small Python framework to run some experiments; I want to be able to launch many (&gt;50) applications concurrently. However, I also want to be able to simulate different applications arriving at different times. The quick and dirty way to do this would be to spawn a new Process object every time a new application arrives. The more refined answer is to use Process Pools (and cut down on the number of objects created). I've used both in the past, so I understand the basics of each. What I'm unsure of is how to expand a Pool dynamically, such that if a Process object is unavailable, a new one is spawned and the Pool expands; but if a Process object is available, it's reused appropriately. Is there a data structure -- or an object -- in Python's multiprocessing library to accomplish this?
has comment: http://stackoverflow.com/comment/84141861
answer count: 0
type: UnansweredQuestion
has title: How can I reuse a Process if available, but spawn a new one if not?
linked to: http://stackoverflow.com/q/5181949
has comment: http://stackoverflow.com/comment/84150592
has comment: http://stackoverflow.com/comment/84141819
type: Question
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/84177160
has comment: http://stackoverflow.com/comment/84141767
tagged with: python-multiprocessing
score: 0

http://stackoverflow.com/a/48594938
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48594895
has body: No. That's not possible since Django is built off of Python, and Python does not allow the names of variables (including class attributes) to begin with a number. You'll have more luck renaming your field to a format that has a prepended name such as "volume_" - for e.g.: volume_24h Or something along those lines.
answers question: http://stackoverflow.com/q/48594895
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/125098892
score: 0
has text: Old question but I don't think this is what is being asked. He's specifically referring to Django Rest Framework, where you can implement the rest api with generics, views, viewsets and mixins. Here's a post with a better answer: https://stackoverflow.com/questions/67476659/generic-views-vs-apiview-vs-viewsets-vs-modelviewsets
type: AnswerComment
comment on: http://stackoverflow.com/a/48508813
type: Comment

http://stackoverflow.com/a/48525528
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48521762
score: 1
has body: The trickiest part is to pass the test result into the fixture, the rest is pretty much trivial. Following the pytests example Making test result information available in fixtures, add a custom hook in your conftest.py: import pytest @pytest.hookimpl(hookwrapper=True, tryfirst=True) def pytest_runtest_makereport(item, call): outcome = yield rep = outcome.get_result() setattr(item, "rep_" + rep.when, rep) return rep Now you can enhance your driver fixture with custom teardown logic in case the test fails: # test_selenium.py import pytest from selenium import webdriver def debug(driver): print('debug: ', driver.title) @pytest.fixture def driver(request): driver = webdriver.Firefox() yield driver if request.node.rep_setup.passed and request.node.rep_call.failed: # this is the teardown code executed on test failure only debug(driver) # this is the teardown code that is always executed driver.quit() def test_fail(driver): driver.get('http://wtf') def test_ok(driver): driver.get('https://www.google.de') Running the tests yields: $ pytest -sv =============================== test session starts =============================== platform darwin -- Python 3.6.3, ... cachedir: .cache rootdir: /Users/hoefling/projects/private/stackoverflow/so-48521762, inifile: plugins: ... collecting ... collected 2 items test_spam.py::test_fail FAILED [ 50%] debug Server Not Found test_spam.py::test_ok PASSED [100%] ==================================== FAILURES ===================================== ____________________________________ test_fail ____________________________________ driver = &lt;selenium.webdriver.firefox.webdriver.WebDriver( ... ... ------------------------------- Captured log setup -------------------------------- remote_connection.py 474 DEBUG POST http://127.0.0.1:50319/session { ... ... remote_connection.py 561 DEBUG Finished Request ======================== 1 failed, 1 passed in 7.23 seconds =======================

http://stackoverflow.com/comment/84124698
type: Comment
has text: Thanks, but it doesn't properly work. I've edited my question
comment on: http://stackoverflow.com/a/48561988
score: 0
type: AnswerComment

http://stackoverflow.com/q/48505802
tagged with: ipython-magic
tagged with: timing
favorite count: 0
type: Question
score: 9
accepted answer: http://stackoverflow.com/a/48505803
upvote count: 9
has body: The %timeit magic supports execution in line mode and cell mode. Using the cell mode, invoked with %%timeit (note: two percent symbols), can be used to exclude some setup code from the measurement: %%timeit [-n&lt;N&gt; -r&lt;R&gt; [-t|-c] -q -p&lt;P&gt; -o] setup_code code code... But how do you use it? This gives an error: &gt;&gt;&gt; %%timeit sleep(0.1); sleep(0.1) ... UsageError: %%timeit is a cell magic, but the cell body is empty. Did you mean the line magic %timeit (single %)? And this doesn't exclude the first line from the benchmark: &gt;&gt;&gt; %%timeit ... sleep(0.1) ... sleep(0.1) ... 200 ms ± 17.6 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
tagged with: python
has title: How to use %%timeit cell magic and exclude setup code?
tagged with: ipython
type: AnsweredQuestion
tagged with: profiling
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48505803

http://stackoverflow.com/a/48538045
score: 0
has comment: http://stackoverflow.com/comment/84072532
has comment: http://stackoverflow.com/comment/84109204
has body: You can use the &lt; math > function import math print ( math.pow(demo[0],2) where, 2 is the power that you want to raise the value in demo[0]. Edit (Inheriting from the collections, and overriding the abstract list methods , in your case (getitem),that you wish to modify). import collections class MyList(collections.MutableSequence): def __init__(self, *args): self.list=list() self.extend(list(args)) def __len__(self): return len(self.list) def __getitem__(self,i): return (self.list[i]**2) def __delitem__(self,i): del self.list[i] def __setitem__(self,i,v): self.list[i]=v def insert(self,i,v): self.list.insert(i,v) def __str__(self): return str(self.list) Note: When you override these abstract methods, you need to define your list, with the type, you declared in this class. i.e., demo_list=MyList(1,2,3,4) demo_list[1] Output : 4
answers question: http://stackoverflow.com/q/48537953
type: Answer

http://stackoverflow.com/a/48519091
score: 2
accepted answer of: http://stackoverflow.com/q/48518860
downvote count: 0
has comment: http://stackoverflow.com/comment/84032932
type: Answer
has body: Add user-agent before request, headers = { 'User-Agent': 'My User Agent 1.0', } url = "https://api.qwant.com/api/search/images?count=10&amp;offset=1&amp;q=stackoverflow" data = requests.get(url, headers=headers).json()
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48518860
has comment: http://stackoverflow.com/comment/84481377

http://stackoverflow.com/a/48596611
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48567063
answers question: http://stackoverflow.com/q/48567063
score: 3
has body: import requests from bs4 import BeautifulSoup r_obj = requests.Session() url = "http://www.tournamentsoftware.com/cookie/default.aspx?returnurl=%2fdefault.aspx" fr_soup = r_obj.get(url) soup = BeautifulSoup(fr_soup.content , "lxml") #print soup l = soup.find_all("input",type="hidden") #print l data = { l[0]['name']:l[0]['value'], l[1]['name']:l[1]['value'], 'btnAccept':'Yes, I accept'} r_obj.post(url,verify=False,data=data) url_needed = "http://www.tournamentsoftware.com/sport/draw.aspx?id=E880C7A5-0A60-4A98-8FF9-A3B7DD58F3E2&amp;draw=4" final = r_obj.get(url_needed) #print final.content soup1 = BeautifulSoup(final.content,"lxml") detail_tab = soup1.find_all("table")
type: Answer

http://stackoverflow.com/comment/84132133
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48567496
score: 0
has text: Yes, the original has compression, the new one does not. Try `hf2.create_dataset('infrared', data=data, compression='gzip')` when creating your fresh dataset.

http://stackoverflow.com/a/48612866
has comment: http://stackoverflow.com/comment/84229138
downvote count: 2
upvote count: 1
answers question: http://stackoverflow.com/q/48611425
has body: You could use gunicorn or its analogs to launch the app in production mode with several workers. As said here: gunicorn --worker-class eventlet -w 5 module:app Where the number after -w is the number of workers, module is your flask-socketio server module, and app is the flask app (app = flask.Flask(__name__)). Each worker is a process busy with handling incoming requests, so you will have concurrency. If the tasks your app does take significant time, the worker doing that task will be irresponsive while doing it. Note: if you launch your app this way, the if __name__ == '__main__': part will be ignored, it seems that your module will be imported. And you don't need to call app.run yourself in the module in this case
type: Answer
score: -1

http://stackoverflow.com/comment/83994188
comment on: http://stackoverflow.com/q/48500092
has text: @alessioferri20 this is not solution. i have soo many changes.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48503250
type: Question
type: AnsweredQuestion
score: 1
tagged with: python
has body: say I have two models like so... class Product(models.Model): ... overall_rating = models.IntegerField() ... class Review(models.Model): ... product = models.ForeignKey(Product, related_name='review', on_delete=models.CASCADE) rating = models.IntegerField() ... I want to use the ratings from all of the child Review objects to build an average overall_rating for the parent Product. Question: I'm wondering how I may be able to achieve something like this using Django signals? I am a bit of a newbie to this part of Django; have never really understood the signals part before. This overall_rating value needs to be stored in the database instead of calculated using a method since I plan on ordering the Product objects based on their overall_rating which is done on a DB level. The method may look something like this if I were to implement it (just for reference): def overall_rating(self): review_count=self.review.count() if review_count &gt;= 1: ratings=self.review.all().values_list('rating',flat=True) rating_sum = 0 for i in ratings: rating_sum += int(i) return rating_sum / review_count else: return 0 Thank you
accepted answer: http://stackoverflow.com/a/48503388
has answer: http://stackoverflow.com/a/48503388
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has title: Django - Using signals to make changes to other models
favorite count: 0

http://stackoverflow.com/a/48678180
upvote count: 1
has body: I solved it by doing that as well but I have to do it every few days before it comes back again.
answers question: http://stackoverflow.com/q/48600826
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84183018
score: 0
has text: @J.Doe If I'm understanding correctly, you want to take a shuffled one dimensional array and turn it into a numpy matrix? i.e. turn `[4,3,2,1]` into `array([[4,3],[2,1]])`
type: AnswerComment
comment on: http://stackoverflow.com/a/48592830
type: Comment

http://stackoverflow.com/comment/84225893
score: 0
comment on: http://stackoverflow.com/q/48614280
has text: @Darkonaut in that case I get following error // app.json_encoder = CustomEncoder NameError: name 'CustomEncoder' is not defined //
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48528942
type: Answer
answers question: http://stackoverflow.com/q/48528890
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48528890
has comment: http://stackoverflow.com/comment/84054213
has body: Something inside your try failed. Your except caught it handle the error but since there is no raise in it, it continues execution, but response is not set.

http://stackoverflow.com/comment/84021378
type: QuestionComment
comment on: http://stackoverflow.com/q/48513073
has text: Actually, no, I'm just posting that code as I couldn't find anything similar.
score: 0
type: Comment

http://stackoverflow.com/a/48551689
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84121732
type: Answer
answers question: http://stackoverflow.com/q/48550676
has body: The django_migrations.id column should be auto-incrementing. You'll need to modify this column manually. You may well find the same problem with other models. You might find it easier to create a fresh database, run manage.py migrate to create the tables, then finally migrate your data.
accepted answer of: http://stackoverflow.com/q/48550676
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/84099465
has text: Also, look into asynchronous operations.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48551635
type: QuestionComment

http://stackoverflow.com/q/48577896
tagged with: python-3.6
has body: when I use python3 annotation class UserBean(SerializationBean): # serial_field = {"account", "nick_name"} non_serial_field = {"password"} def __init__(self, account: str = None, password: str = None, nick_name: str = None, roommate: UserBean = None): super().__init__() self._account = account self._password = password self._nick_name = nick_name self._roommate = roommate The roommate's annotation will raise NameError: name 'UserBean' is not defined How to resolve it?
has comment: http://stackoverflow.com/comment/84153461
score: 0
duplicate of: http://stackoverflow.com/q/40049016
has title: Python3 Annotation Error
linked to: http://stackoverflow.com/q/40049016
type: Question
has comment: http://stackoverflow.com/comment/84152238
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48611565
favorite count: 0
type: Question
has body: I saw in Will Marshall's Advanced APC MKii he breaks the APC grid into two 4x5 matrices, where you can move the left one, and the right one is static. I'm trying to emulate something like this on the Launchpad. Ultimately what I am hoping for is to create Four 2x7 matrixes (independent clip launch boxes), and nav them around by: # Scene1 button + arrows = Matrix 1 # Scene2 button + arrows = Matrix 2 # Scene3 button + arrows = Matrix 3 # Scene4 button + arrows = Matrix 4 And the bottom row is static across all Matrices should be a stop button for that track. Ideally green when playing and press to stop, red when nothing is playing. Ideally I'd love to be able to default code which Ableton Tracks are the defaults for each Matrix. So Matrix 1 would be Ableton Tracks 1 and 2, while Matrix 2 might default to Ableton Tracks 5 and 6. I don't care about the scene launch buttons on the right so want to use those to drive the Arrow navigation of each matrix. I've spent about 5 hours on this thus far and have made almost zero progress. I tried the framework tutorial http://remotescripts.blogspot.com/2010/03/introduction-to-framework-classes.html which fails / has errors - might be bc it for an old version of Live? I decompiled the existing Launchpad remote scripts and modified matrix size to see if I could just reduce to a 4x4 or 2x8 and that failed each time. I check the Log.txt and was tweaking the diff places the errors were sending me to. I tried to take code from Will's scripts and inject them into the Launchpad.py and SpecialSessionComponent.py to see if his code for the 2 sessions might help override what the Launchpad loads to. This loaded fine, didn't bomb out per the Log.txt, but it didn't override the launchpad remote scripts which loaded as usual. I also messed with Launchpad95 but that's kind of too huge. I'm an OK python programmer. Some stuff I can code on my own, stuff like this I am a cut-paste-tweaker, and in this sense I'm making zero progress. Questions: an…
type: UnansweredQuestion
tagged with: python
tagged with: ableton-live
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has title: Novation Launchpad Midi Remote Script for Ableton Live

http://stackoverflow.com/comment/84021434
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48509348
has text: Go back through the logs and find the very first Python error that occurred. The ``populate() isn't reentrant`` error is a follow on error caused by Django not being able to be initialised more than once in a process. The real cause will be the first error before that, which is not that error.

http://stackoverflow.com/q/48521886
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84038234
score: 1
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84038448
has title: comparison to False should be 'if cond is False:' or 'if not cond:
has comment: http://stackoverflow.com/comment/84038249
upvote count: 4
linked to: http://stackoverflow.com/q/132988
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84038315
answer count: 2
tagged with: pep8
has body: while line_number &lt; dictionary_elements_number and validation_bool == False: getting this error when i run it throught pep8 E712 comparison to False should be 'if cond is False:' or 'if not cond:' isn't that a bit weird?
has answer: http://stackoverflow.com/a/74884446
has comment: http://stackoverflow.com/comment/84038409
possible better answer: http://stackoverflow.com/a/74884446
favorite count: 0
has answer: http://stackoverflow.com/a/48522050
type: Question
accepted answer: http://stackoverflow.com/a/48522050
has comment: http://stackoverflow.com/comment/84038240

http://stackoverflow.com/q/48639129
has answer: http://stackoverflow.com/a/48720956
answer count: 1
tagged with: tensorflow
has title: Deploying TensorFlow Checkpoint to Google Cloud Platform
type: Question
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42216208
tagged with: google-cloud-platform
score: 0
has body: I have trained a TensorFlow model and saved a checkpoint, and would like to deploy it to Google Cloud Platform. In the model deployment documentation it says that you need to create a SavedModel. It seems that others also use checkpoints instead of SavedModel. Given that I have already spent time training this model and only have checkpoints instead of a SavedModel, is there a method I can use to deploy the model still or will I need to retrain?
tagged with: machine-learning

http://stackoverflow.com/comment/84047584
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Pip does not work after upgrade to ubuntu-16.10](https://stackoverflow.com/questions/42184792/pip-does-not-work-after-upgrade-to-ubuntu-16-10)
comment on: http://stackoverflow.com/q/48513473

http://stackoverflow.com/comment/84089982
comment on: http://stackoverflow.com/q/48533781
score: 0
type: QuestionComment
has text: Just as an FYI, you were completely on the right track with both solutions. Just a couple of misunderstandings of the mechanisms involved.
type: Comment

http://stackoverflow.com/a/48751958
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48609976
type: Answer
has body: As per the API documentation you need to pass in an authentication token and not the basic service credentials. The Documentation has sample web socket code - https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/#recognize_audio_websockets
score: 1

http://stackoverflow.com/comment/84165731
score: 0
has text: create only if the record doesn't exists .. either by handling ObjectDoesNotExist exception or by checking exists() .
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48584254

http://stackoverflow.com/comment/84306894
type: QuestionComment
score: 0
has text: @SunBear That's not exactly the part I'm irritated by. `self.lb1_values = tk.StringVar(value=name1)` irritates me as `name1` is a `list` as opposed to a string which is the type it is supposed to be.
comment on: http://stackoverflow.com/q/48618665
type: Comment

http://stackoverflow.com/q/48519337
has answer: http://stackoverflow.com/a/48519443
has answer: http://stackoverflow.com/a/72970805
type: Question
has body: I am exporting a pandas DataFrame to Excel, and since it contains a lot of rows and columns, it would be useful to keep the top row and the first column when browsing its contents. There is a feature present in Excel that allows for freezing the top row and the first column. Is accessible through XlsxWriter when exporting DataFrames to excel?
answer count: 2
downvote count: 0
tagged with: python
tagged with: excel
upvote count: 22
score: 22
tagged with: pandas
type: AnsweredQuestion
has title: How to freeze the top row and the first column using XlsxWriter?
tagged with: xlsxwriter
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48519443
possible better answer: http://stackoverflow.com/a/72970805
favorite count: 0

http://stackoverflow.com/q/48618665
has comment: http://stackoverflow.com/comment/84234406
has body: I wrote the following tkinter script to understand how to add a list of data into a tkinter.Listbox widget. I discovered 2 methods for doing so. Next, I wanted to extract the same list from the tkinter.Listbox widget. Out of the 4 different approaches, I only managed to get the 4th approach (i.e. e4) to work. How can I get approaches e1, e2 and e3 to work? The end goal is to get the same list that was initially supplied to the tkinter.Listbox widget. Test Script: import tkinter as tk # Python 3 tkinter modules import tkinter.ttk as ttk class App(ttk.Frame): def __init__(self, parent, *args, **kwargs): # 1. Initialise Frame ttk.Frame.__init__(self, parent) self.parent = parent # Method1 name1 = ['Peter', 'Scotty', 'Walter', 'Scott', 'Mary'] self.lb1_values = tk.StringVar(value=name1) self.listbox1 = tk.Listbox(self, listvariable=self.lb1_values) # Method2 self.listbox2 = tk.Listbox(self) name2 = ['Sarah', 'Sean', 'Mora', 'Mori', 'Mary'] for item in name2: self.listbox2.insert(tk.END, item) self.listbox1.grid(in_=self, row=0, column=0, sticky='nsew') self.listbox2.grid(in_=self, row=0, column=1, sticky='nsew') # Extract values from listbox and covert to a list e1 = self.lb1_values.get() print('e1 = ', e1) print('type(e1) = ', type(e1)) e1 = e1.strip(',') print('e1 = ', e1) e2 = self.listbox1.cget('listvariable') print('\ne2 = ', e2) print('type(e2) = ', type(e2)) e2 = e2.split(',') print('e2 = ', e2) e3 = self.listbox2.cget('listvariable') print('\ne3 = ', e3) print('type(e3) = ', type(e3)) e4 = self.listbox2.get(0, tk.END) print('\ne4 = ', e4) print('type(e4) = ', type(e4)) e4 = list(e4) print('e4 = ', e4) if __name__ == '__main__': root = tk.Tk() root.title('App'), root.geometry('400x200') app = App(root) app.grid(row=0, column=0, sticky='nsew') #root.mainloop() Output: e1 = ('Peter', 'Scotty', 'Walter', 'Scott', 'Mary') type(e1) = &lt;class 'str'&gt; e1 = ('Peter', 'Scotty', 'Walter', 'Scott', 'Mary') e2 = PY_VAR0 type(e2) = &lt;class 'str'&gt; e2 = ['PY_VAR0'] e3 …
favorite count: 0
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84306622
has comment: http://stackoverflow.com/comment/84237366
has comment: http://stackoverflow.com/comment/84306894
answer count: 1
tagged with: listbox
downvote count: 0
has title: Extracting a list of items from tkinter.Listbox
has comment: http://stackoverflow.com/comment/84236008
upvote count: 7
has comment: http://stackoverflow.com/comment/84367013
has comment: http://stackoverflow.com/comment/84238284
accepted answer: http://stackoverflow.com/a/48626736
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84236837
has answer: http://stackoverflow.com/a/48626736
has comment: http://stackoverflow.com/comment/84234884
has comment: http://stackoverflow.com/comment/84351157
score: 7
tagged with: python

http://stackoverflow.com/comment/84230061
has text: oh wow and the wierd thing is that it was working even it has that ambiguos expression of mine, thank you so much it worked perfectly.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48616449

http://stackoverflow.com/a/48617680
answers question: http://stackoverflow.com/q/48617598
has comment: http://stackoverflow.com/comment/84234259
type: Answer
has comment: http://stackoverflow.com/comment/84239630
accepted answer of: http://stackoverflow.com/q/48617598
has body: You can use pipenv for virtualenv creation and package management needs, e.g.: pipenv --python 3.6 pipenv --python 3 See the documentation: https://pipenv.kennethreitz.org/basics/#specifying-versions-of-python That way, when you'll recreate the env with pipenv, it'll use the specified Python version and install the required packages.
score: 0
has comment: http://stackoverflow.com/comment/84241506
upvote count: 1
has comment: http://stackoverflow.com/comment/84243459
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/q/48493137
possible better answer: http://stackoverflow.com/a/48493177
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/48493223
tagged with: ttk
has answer: http://stackoverflow.com/a/48493177
has body: What's the most fail-proof way of dynamically fetching a widget's internal Tcl/Tk class name? try: # In order to be able to import tkinter for import tkinter as tk # either in python 2 or in python 3 from tkinter import ttk except: import Tkinter as tk import ttk if __name__ == '__main__': root = tk.Tk() widget = ttk.Combobox(root) # Would be "TCombobox" in this case widget.pack() root.mainloop() This is only base widget though, please consider deep inheriting classes of this widget.
tagged with: python
score: -2
linked to: http://stackoverflow.com/q/27281097
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48493223
tagged with: tk-toolkit
duplicate of: http://stackoverflow.com/q/27281097
has title: What's the most fail-proof way of dynamically acquiring a widget's internal Tcl/Tk class name?
favorite count: 0
type: Question
tagged with: tkinter
answer count: 2

http://stackoverflow.com/comment/84168312
type: Comment
type: QuestionComment
has text: the model depends on the graph, if you change the graph you have to load the corresponding model.
comment on: http://stackoverflow.com/q/48579159
score: 0

http://stackoverflow.com/comment/84180836
has text: Converting the sublists to strings and then searching them is expensive.
type: Comment
comment on: http://stackoverflow.com/q/48591755
score: 3
type: QuestionComment

http://stackoverflow.com/q/48599095
has title: Selenium page object model python, inherit from particular class
favorite count: 0
type: Question
has body: Trying to implement page object model practise with selenium and python but an instance of chrome is not launching. can anyone point me in the right direction? I'm expecting Chrome to launch and fill in a login form. this is what the console is spitting out currently: Process finished with exit code 0. And an " unresolved reference 'Login' " error on the Login_test method. Also getting a red line under Login. while trying to use it in the test_login method. This is how my files are set up. I have 2 python files in separate folders. Both of these folders are in a project folder. Pages/login_page.py Tests/login_test.py #login_page.py file &gt; from selenium.webdriver.common.by import By class Login: _username_input = {"by": By.NAME, "value": "username"} _password_input = {"by": By.NAME, "value": "password"} _submit_button = {"by": By.ID, "value": "btn-inloggen"} _success_message = {"by": By.CSS_SELECTOR, "value": ".#header &gt; div.right &gt; a:nth-child(4)"} def __init__(self, driver): self.driver = driver self.driver.get("website") def with_(self, username, password): self.driver.find_element(self._username_input["by"], self._username_input["value"]).send_keys(username) self.driver.find_element(self._password_input["by"], self._password_input["value"]).send_keys(password) self.driver.find_element(self._submit_button["by"], self._submit_button["value"]).click() def login_succesfull_(self): return self.driver.find_element(self._success_message["by"], self._success_message["value"]).is_displayed()&lt; #test_login.py file from selenium import webdriver from Pages import login_page class TestLogin: def login(self, request): driver = webdriver.Chrome() def quit(): driver.quit() request.addfinalizer(quit) return login_page.Login(driver) def test_login(self): Login.with_("username", "password") assert Login.login_succesfull_()
has comment: http://stackoverflow.com/comment/84194717
has answer: http://stackoverflow.com/a/48599398
has comment: http://stackoverflow.com/comment/84194923
upvote count: 2
has comment: http://stackoverflow.com/comment/84195015
has comment: http://stackoverflow.com/comment/84194975
answer count: 1
downvote count: 0
tagged with: python
tagged with: object
score: 2
has comment: http://stackoverflow.com/comment/84194870
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84194955
has comment: http://stackoverflow.com/comment/84195001
tagged with: models
tagged with: selenium
tagged with: pom.xml
has comment: http://stackoverflow.com/comment/84195006
has comment: http://stackoverflow.com/comment/84194972
has comment: http://stackoverflow.com/comment/84194964
accepted answer: http://stackoverflow.com/a/48599398

http://stackoverflow.com/comment/84248022
comment on: http://stackoverflow.com/a/48588489
score: 0
type: Comment
type: AnswerComment
has text: There's no difference.

http://stackoverflow.com/comment/84188406
comment on: http://stackoverflow.com/q/48595482
has text: So you're doing an AJAX call and you want to redirect based on the server response? I think Flask is irrelevant here, please show us the JS side.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84120141
comment on: http://stackoverflow.com/a/48542328
has text: have a look at `pd.DataFrame.shift`: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html, I'm sure there's a way to use `apply` on the shifted dataframe, but you may need to fill in `NaN` values for a row at the top or bottom.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48571060
has comment: http://stackoverflow.com/comment/84139590
has answer: http://stackoverflow.com/a/48572589
has comment: http://stackoverflow.com/comment/84172963
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48573596
has comment: http://stackoverflow.com/comment/84142315
has answer: http://stackoverflow.com/a/48573596
score: 0
has comment: http://stackoverflow.com/comment/84139138
has body: Good evening, i have to work on a xml file, the problem is that the elements in the file ends with a different format than usual, for example: &lt;1ELEMENT> text &lt;\1ELEMENT> I use the function root=etree.parse('filepath'), and, by changing manually in the text out of the compiler the \ in /, the function works correctly. The big problem is that i need to automate that replacing process and the only solution that i thinked about is importing the file as array make a replace / to \ and build a new xml file;but it seems a little bit clunky. Summing up i need to know if exist a function to replace the terms i mentioned above before to use the root=etree.parse('filepath').
has title: (python) parsing xml file but the elements ends with \
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48571357
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48571357
tagged with: xml-parsing
answer count: 3

http://stackoverflow.com/a/48611373
answers question: http://stackoverflow.com/q/48609466
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48609466
has body: They mean the same. In fact, tf.inv was renamed to tf.reciprocal and tf.inv is no longer exposed to the top level module in the latest versions (though both still exist in gen_math_ops.py). From the migration documentation: Many functions have been renamed to match NumPy. This was done to make the transition between NumPy and TensorFlow as easy as possible. There are still numerous cases where functions do not match, so this is far from a hard and fast rule, but we have removed several commonly noticed inconsistencies. tf.inv should be renamed to tf.reciprocal This was done to avoid confusion with NumPy's matrix inverse np.inv You can see there several more functions that were renamed, like tf.mul and tf.neg.
score: 2
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84139635
score: 0
type: Comment
type: QuestionComment
has text: Have you tried anything? What's your html template look like?
comment on: http://stackoverflow.com/q/48571304

http://stackoverflow.com/a/48680641
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48622463
has body: You need: @rpc(RequestInquiry, _body_style='bare') def inquiry_A2(ctx, inquiry_A2): return True
answers question: http://stackoverflow.com/q/48622463
type: Answer
score: 0

http://stackoverflow.com/a/48629638
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/84256446
type: Answer
has body: You need to pass username of user to be deleted in url path('del-user/&lt;slug:username&gt;', del_user, name='del_user'),
has comment: http://stackoverflow.com/comment/84464608
has comment: http://stackoverflow.com/comment/84256492
upvote count: 2
has comment: http://stackoverflow.com/comment/84256575
has comment: http://stackoverflow.com/comment/84256368
has comment: http://stackoverflow.com/comment/84256138
answers question: http://stackoverflow.com/q/48629582

http://stackoverflow.com/a/48632038
answers question: http://stackoverflow.com/q/48631907
type: Answer
score: -1
upvote count: 0
downvote count: 1
has body: I imagine this won't be the most useful answer, but you could always parallelize the process manually. https://docs.python.org/2/library/multiprocessing.html

http://stackoverflow.com/q/48642481
type: Question
has body: I wrote a test code in python using numba. from numba import cuda import numpy as np import numba @cuda.jit def function(output, size, random_array): i_p, i_k1, i_k2 = cuda.grid(3) a=cuda.local.array(shape=1,dtype=numba.float64) if i_p&lt;size and i_k1&lt;size and i_k2&lt;size: a1=i_p a2=i_k1+1 a3=i_k2+2 a[0]=a1 a[1]=a2 a[2]=a3 for i in range(len(random_array)): output[i_p,i_k1,i_k2,i] = a[int(random_array[i])] output=cuda.device_array((2,2,2,5)) random_array=np.array([np.random.random()*3 for i in range(5)]) print(random_array) random_array0=cuda.to_device(random_array) size=2 threadsperblock = (8, 8, 8) blockspergridx=(size + (threadsperblock[0] - 1)) // threadsperblock[0] blockspergrid = ((blockspergridx, blockspergridx, blockspergridx)) # Start the kernel function[blockspergrid, threadsperblock](output, size, random_array0) print(output.copy_to_host()) # test if it is consistent with non gpu case output=np.zeros([2,2,2,5]) for i in range(size): for j in range(size): for k in range(size): a=[i,j+1,k+2] for ii in range(len(random_array)): output[i,j,k,ii] = a[int(random_array[ii])] print(output) I am confused about the usage of cuda.local.array. It has two arguments. One is shape and another is dtype. However, the result does not change with different set up of shape. For example, shape=0 or shape =1 or shape=100. I don't understand this argument shape. Does anyone know this?
tagged with: python
tagged with: numba
answer count: 1
downvote count: 0
upvote count: 1
tagged with: cuda
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48646100
has title: What is the correct usage of cuda.local.array in numba?
has answer: http://stackoverflow.com/a/48646100
score: 1
favorite count: 0

http://stackoverflow.com/q/48573622
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: pandas to change the colum value withoutchanging the format
has body: I have a Excel sheet with 10000 Rows. I have to change the value of a Colum5 based on value of Colum2 and update the excel sheet. I am able to change the values using: import numpy as np df=pd.read_excel('part2.xlsx') count=0 while (count&lt;10000): if df['Grade'][count] == 'A' : #df.loc[df['Grade'][count]] = 'Good' df['Grade'][count] = 'Good' print(count) print(df['Grade'][count]) count=count+1 df.to_excel('temp.xlsx') The issue with this is as I am writing to a new Excel sheet all the formatting is gone. I want to achieve the same thing in the same excelsheet so that format is not removed. 2) is there any use in keeping the df.loc here?
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48573822

http://stackoverflow.com/a/69874880
accepted answer of: http://stackoverflow.com/q/48523344
answers question: http://stackoverflow.com/q/48523344
type: Answer
score: 0
has body: As mentioned in the comments by Edouard Thiel, you can indeed run submenu.get_parent().get_attach_widget() to receive a reference to the parent menu. More info at https://people.debian.org/~osamu/gtk3tutor/python-gtk3/Gtk.Menu.get_attach_widget.page
type: AcceptedAnswer

http://stackoverflow.com/a/48594235
upvote count: 1
answers question: http://stackoverflow.com/q/48582311
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48582311
has body: The clone() method does not necessarily clone the entire graph. It allows you to "cut out" a piece of graph, via the substitutions argument. The substitutions argument specifies the input nodes of the part of the graph you want to clone; basically where you want to cut it. For example, to clone a middle layer of a stack, identify its root, let's call it layer_root its input(s). Let's say there is one input node, you store it as layer_input Then you should be able to clone just this part according to this following code sketch: substitutions = { layer_input : C.placeholder(name='cloned_layer_input') } cloned_layer = layer_root.clone(clone_method, substitutions) The substitutions will cause clone() to stop cloning once it hits layer_input, and in the clone, replace it with the placeholder. The result will be a callable, like any layers of the layers lib (like C.Dense()) or any function defined with @C.Function, which is I believe what you are looking for.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48636722
has body: For IBM Cloud Object Storage, it should be import ibm_boto3 rather than import boto3. The original boto3 is for accessing AWS, which uses different authentication. Maybe those two have a different interpretation of the endpoint value.
score: 1
answers question: http://stackoverflow.com/q/48625239
type: Answer
has comment: http://stackoverflow.com/comment/84275155
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48505255
downvote count: 0
has comment: http://stackoverflow.com/comment/84005685
answers question: http://stackoverflow.com/q/48503893
score: 3
has comment: http://stackoverflow.com/comment/84007946
has comment: http://stackoverflow.com/comment/84006416
type: Answer
has comment: http://stackoverflow.com/comment/84007418
has comment: http://stackoverflow.com/comment/84007667
has comment: http://stackoverflow.com/comment/84008171
has comment: http://stackoverflow.com/comment/84007270
has comment: http://stackoverflow.com/comment/84007989
has comment: http://stackoverflow.com/comment/84006339
upvote count: 3
has comment: http://stackoverflow.com/comment/84005559
has comment: http://stackoverflow.com/comment/84008131
has body: If you simply pass the imported class name to the target class, like class TargetClass(ImportedClass): That is not "passing the imported class", this is making TargetClass inherit from ImportedClass. the imported code is unable to use global variables that have already been declared. There's no such thing as "global variable" in Python, in the meaning of "variables that are declared once somewhere and are then accessible everywhere in every module." Every module has its own scope. At best a variable can be global to a module, but never global to a program. If a name hasn't been explicitly imported or defined inside a module, it doesn't exist. This means that they can't interact with their own instance. The problem is that you're not trying to "interact with their own instance", you're trying to interact with names which do not exist in the module. ... subroutines ... Python doesn't have subroutines, it has functions. Some of these distinctions may seem like nitpicking, but they're important, and in your case this all adds up to some very bad spaghetti code which simply isn't easy to fix. You need to start using proper OOP practices, and stop swimming upstream against the issues you're creating for yourself. This is a broad topic, so here are simply a few pointers: Unless you have used import to import something or you have declared it in your module, it doesn't exist and you cannot use it. Never depend on globals in any way. If you import something, you can use it as is. Anything that can't be imported and will only be available at runtime must probably be passed as a function parameter. The first parameter to an instance method is named self. Just do it. Dependencies of a class are passed as parameter to __init__. Stripping out the clear nonsense from your class and just leaving the somewhat sane code, you still have dependency issues: class Class(): def sub2(self): self.sub1() # sub1 is not defined here, cannot be relied upon def sub4(self): print(Global) # not de…
has comment: http://stackoverflow.com/comment/84005430

http://stackoverflow.com/q/48507481
has comment: http://stackoverflow.com/comment/84009584
score: 0
answer count: 2
tagged with: syntax-error
has body: Hi everyone I edited this post and still got an error can someone please help. The error is: File "C:\Users\myshop\myshop\urls.py", line 25, in &lt;module&gt; url(r'^', include('shop.urls', namespace='shop')), File "C:\Users\Faruq\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. and the urls.py is this: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static app_name='shop' urlpatterns = [ url('admin/', admin.site.urls), url(r'^', include('shop.urls', namespace='shop')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
has comment: http://stackoverflow.com/comment/84026128
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84009914
has comment: http://stackoverflow.com/comment/84009452
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48507514
type: UnansweredQuestion
has title: SyntaxError app_name while using Django
has answer: http://stackoverflow.com/a/48507571
tagged with: django
tagged with: python

http://stackoverflow.com/comment/84023285
has text: @cᴏʟᴅsᴘᴇᴇᴅ No the result is fine.Thanks.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48513721

http://stackoverflow.com/a/48514280
answers question: http://stackoverflow.com/q/48514162
score: 5
upvote count: 5
has body: This is because the repr of the bound method includes the object it is bound to: &gt;&gt;&gt; class C: ... def __repr__(self): ... return '&lt;repr here!&gt;' ... def x(self): pass ... &gt;&gt;&gt; C().x &lt;bound method C.x of &lt;repr here!&gt;&gt; &gt;&gt;&gt; str(C().x) '&lt;bound method C.x of &lt;repr here!&gt;&gt;' Note that I've made a few leaps here -- here they are: '%s' % x is roughly equivalent to str(x) When something doesn't define __str__, it falls back to __repr__ (this is the case for the method descriptor) In retrieving the repr of the class, you end up with this cycle: AttributeDisplay.__repr__ => AttributeDisplay.gatherAttributes.__repr__ => AttributeDisplay.__repr__ (repr of the class as part of bound method repr) => ...
type: Answer
accepted answer of: http://stackoverflow.com/q/48514162
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84055719
comment on: http://stackoverflow.com/a/48517213
score: 1
type: Comment
has text: @sloth, yes, I also considered using only one sprite class, but then thought it would be a little clearer with separate classes. For an actual game, you'd probably need separate classes or subclasses anyway unless you use an entity-component-system.
type: AnswerComment

http://stackoverflow.com/comment/84173026
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48585988
has text: @DuD. Please don't post answers as comments, as this bypasses SO's quality controls for answers, and you deprive yourself of those sweet sweet answer points.

http://stackoverflow.com/q/48607583
has comment: http://stackoverflow.com/comment/84213606
favorite count: 0
type: Question
has title: Minimizing Log Likelihood in Python
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: excel
has body: This is a general question about optimisation in Python. The problem I am attempting to solve has 91 parameters which need to be optimised in order to minimise the log likelihood function. Currently, I am using scipy.optimize.minimize, however, I find the process is very slow, compared to using Excel's solver, despite my expectation that Python would be much faster. Is this a case of scipy.optimize.minimize isn't as fast as Excel's Solver in general or is the number of parameters too great for scipy? And if so, is there an alternative to Excel's Solver in Python that would be faster?
tagged with: optimization
score: 2
tagged with: solver
has comment: http://stackoverflow.com/comment/84220737

http://stackoverflow.com/a/48646421
score: 0
has body: I think the solution is joined-table inheritance. Each level of abstraction is mapped to an actual table containing only the columns specific to that level. SQLAlchemy does the job of generating the right JOINs to get data from each table.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48625715
accepted answer of: http://stackoverflow.com/q/48625715
type: Answer

http://stackoverflow.com/comment/84090416
comment on: http://stackoverflow.com/a/48547069
has text: I like the simplicity of this answer (+1), but why bother with `x`? You could just use `[a for a in s if s.count(a) > 1]`. Also -- perhaps you can edit your answer to include your comment as part of the answer.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/48528112
has comment: http://stackoverflow.com/comment/84051456
upvote count: 5
has answer: http://stackoverflow.com/a/48528640
tagged with: python
has comment: http://stackoverflow.com/comment/84051417
possible better answer: http://stackoverflow.com/a/48528391
has comment: http://stackoverflow.com/comment/84051203
has answer: http://stackoverflow.com/a/48528199
answer count: 4
has body: I've got the following string: blah blah blah blah in Rostock What's the pythonic way for removing all the string content from the word 'in' until the end, leaving the string like this: 'blah blah blah blah'
has comment: http://stackoverflow.com/comment/84051485
type: Question
has answer: http://stackoverflow.com/a/48528391
has comment: http://stackoverflow.com/comment/84051206
score: 5
has answer: http://stackoverflow.com/a/48528167
has comment: http://stackoverflow.com/comment/84051234
accepted answer: http://stackoverflow.com/a/48528199
downvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/84051242
favorite count: 0
has comment: http://stackoverflow.com/comment/84051644
has comment: http://stackoverflow.com/comment/84051323
has title: Remove string characters from a given found substring until the end in Python
type: AnsweredQuestion

http://stackoverflow.com/comment/111549829
type: Comment
comment on: http://stackoverflow.com/a/48514338
type: AnswerComment
has text: @Alexey Trofimov can you explain df.groupby("Col2")["Col2"].transform(len) what does this mean
score: 1

http://stackoverflow.com/comment/84046686
score: 0
type: Comment
type: AnswerComment
has text: If you set `self.site_id` in `dispatch` before calling `super()`, then you shouldn't get that error.
comment on: http://stackoverflow.com/a/48525334

http://stackoverflow.com/comment/84138448
type: QuestionComment
comment on: http://stackoverflow.com/q/48570625
has text: But the results could be `4.xml,6.jpg,5.xml,4.jpg,6.xml,5.jpg` in which case none of the matching numbers are adjacent. The results of `glob()` _are not sorted_.
type: Comment
score: 1

http://stackoverflow.com/q/48583135
downvote count: 0
tagged with: raspberry-pi3
upvote count: 1
has body: From picamera.PiCamera() Thread I try to get cls.frameCV2 = snap.array for handling in opencv, and another cls.frame = stream.read() for web streaming. Both work, but very slowly. What is the problem? If Use only frameCV2 it works quite fast, or if I only Use stream.read, it also ok. Here is my code snippet: import time import io import threading import cv2 import picamera from picamera.array import PiRGBArray class Camera(object): thread = None # background thread that reads frames from camera frame = None # current frame is stored here by background thread frameCV2 = None # same, but as a numpy array last_access = 0 # time of last client access to the camera def initialize(self): if Camera.thread is None: # start background frame thread Camera.thread = threading.Thread(target=self._thread) Camera.thread.start() # wait until frames start to be available while self.frame is None: time.sleep(0) def get_frame(self): Camera.last_access = time.time() self.initialize() return self.frame def get_frame_for_internal_proc(self): # store frame for cv2 я добавил Camera.last_access = time.time() self.initialize() return self.frameCV2 @classmethod def _thread(cls): with picamera.PiCamera() as camera: # camera setup camera.resolution = (800, 600) camera.hflip = True camera.vflip = True # let camera warm up camera.start_preview() time.sleep(2) rawCapture = PiRGBArray(camera) # я добавил stream = io.BytesIO() for snap in camera.capture_continuous(rawCapture, 'bgr', use_video_port=True): cls.frameCV2 = snap.array # frame for cv2 # store frame for web camera.capture(stream, format='jpeg') stream.seek(0) cls.frame = stream.read() # reset stream for next frame stream.seek(0) stream.truncate() rawCapture.truncate(0) # if there hasn't been any clients asking for frames in # the last 10 seconds stop the thread if time.time() - cls.last_access &gt; 10: break cls.thread = None
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48682493
tagged with: opencv
has title: I try to get 2 frames from picamera. Why it works very slowly?
tagged with: opencv3.0
score: 1
answer count: 1

http://stackoverflow.com/comment/83982341
score: 0
type: Comment
type: QuestionComment
has text: The interpreter translates that string into a call to `.__getitem__` method. passing in a tuple of `slice` objects. The array version is compiled, but the `index_tricks` module has some interesting uses of this idea. numpy/index_tricks.py
comment on: http://stackoverflow.com/q/48494581

http://stackoverflow.com/comment/84292302
has text: Yea.. with exceptions I was prompting the user twice.
score: 0
comment on: http://stackoverflow.com/q/48585400
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84220769
has text: It must be multiple requests. All services. All components for a service... Thats just how the API is written https://github.com/apache/ambari/blob/trunk/ambari-server/docs/api/v1/components-component.md
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48610405
type: Comment

http://stackoverflow.com/comment/84169209
comment on: http://stackoverflow.com/q/48585899
type: Comment
type: QuestionComment
has text: @FHTMitchell Dude you just fixed it thanks! Idk why I didn't try that before!
score: 0

http://stackoverflow.com/comment/84205109
has text: I've added an example for npz-files. For that you only call `savez` once with all the entries (as one list of arrays or many arrays).
comment on: http://stackoverflow.com/a/48603568
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84194683
has text: @Tai: that is even in the answer. Yes, it does. The question is whether that is a problem.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48598904
type: AnswerComment

http://stackoverflow.com/comment/84193207
has text: @Lingxi Not in Python-3 but in Python-2 `zip` returns a list. In Python-2 you should use `itertools.izip()`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48598297
type: Comment

http://stackoverflow.com/q/48494267
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48494327
tagged with: pandas
has body: So I have Date/Time string in a pandas dataframe that looks like this: 2016-10-13 02:33:40 And I need to cut out the year/month/day completely, and convert the time to minutes. So that time/date above needs to be converted into just: 153 ^^2 hours and 33 minutes = 153 minutes I am basically trying to sift the data by the amount of time in between each entry and converting it all to minutes (since the amount of time that passes will not go past a day per session) seemed to make the most sense to me. But, I am open to any other suggestions! Thanks for the help
linked to: http://stackoverflow.com/q/17951820
answer count: 1
has title: Changing Date/Time in python pandas
duplicate of: http://stackoverflow.com/q/17951820

http://stackoverflow.com/comment/84210609
comment on: http://stackoverflow.com/q/48607132
score: 0
type: Comment
type: QuestionComment
has text: Sorry about the edits and bad formatting of text... I’m on a smartphone..

http://stackoverflow.com/comment/84051630
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48528199
type: Comment
has text: @ThomasWeller To me the program seems like he wants the info before the location in the string. The location and name of a person is in the string so unlikely the "in" will be used as part of a normal sentence.

http://stackoverflow.com/a/48619525
answers question: http://stackoverflow.com/q/48619344
has body: The message means that you try to access to some python object defined as a function as if it were an array. The most likely candidate looking as the code you provided is machine_choice. But please provide a working minimal example, which in that case means including import of necessary modules (random) and lines function. Regarding the purpose of the code (faking a switch) the cascaded if solution is usually not a very good solution. Using random.choice with an array or a dictionnary or an array with random number as key or index would be much more pythonic. Also using switch is a common code smell in OO programming and is often best replaced using object polymorphism and a factory. You may have a look at python switch replacement for details.
has comment: http://stackoverflow.com/comment/84264200
score: 0
type: Answer

http://stackoverflow.com/a/48495307
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48495207
upvote count: 1
answers question: http://stackoverflow.com/q/48495207
has body: I believe you need concat, replace NaNs by fillna and cast to ints, then sort_index and remove DatetimeIndex by reset_index. Last add new column by insert: df1 = pd.DataFrame({ 'Column1': [1]}, index=pd.to_datetime(['2016-11-28 00:37:07'])) df2 = pd.DataFrame({'Column2': [1]}, index=pd.to_datetime(['2016-11-28 04:25:44'])) df3 = pd.DataFrame({'Column1': [1,0]}, index=pd.to_datetime(['2016-12-02 11:32:49', '2016-12-02 11:34:19'])) ListofDataframes = [df1, df2, df3] df = pd.concat(ListofDataframes).fillna(0).astype(int).sort_index().reset_index(drop=True) df.insert(0, 'LastNotify', range(1, len(df) + 1)) print (df) LastNotify Column1 Column2 Column3 0 1 1 0 0 1 2 0 1 0 2 3 0 0 1 3 4 0 0 0
type: Answer
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48622097
score: 0
type: Answer
has body: example_dict = {'key_outer_01': {'key_inner_01': 'value_inner_01'}, 'key_outer_02': {'key_inner_02': 'value_inner_02'}} def get_key_value_of_nested_dict(nested_dict, outer_key=None): inner_key = None inner_value = None for key, value in nested_dict.items(): if isinstance(value, dict): outer_key = key return get_key_value_of_nested_dict(value, key) else: inner_key = key inner_value = value return outer_key, inner_key, inner_value print get_key_value_of_nested_dict(example_dict) Output: ('key_outer_01', 'key_inner_01', 'value_inner_01')
answers question: http://stackoverflow.com/q/48621973

http://stackoverflow.com/comment/84588509
type: Comment
has text: @nicholasgwee happy to help!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48566601

http://stackoverflow.com/q/48641350
score: 0
has answer: http://stackoverflow.com/a/48641467
has body: Given two lists lst1 and lst2: lst1 = ['a'] lst2 = [['b'], ['b', 'c'], ['b', 'c', 'd']] I'd like to merge them into a list of multiple lists with a desired output like this: desiredList = [['a', ['b']], ['a', ['b', 'c']], ['a', ['b', 'c', 'd']]] Here is one of my attempts that comes close using lst1 + lst2 and list.append(): lst3 = [] for elem in lst2: new1 = lst1 new2 = elem theNew = new1 + new2 lst3.append(theNew) print(lst3) #Output: #[['a', 'b'], #['a', 'b', 'c'], #['a', 'b', 'c', 'd']] Expanding on this, I thought another variation with theNew = new1.append(new2)would do the trick. But no: lst3 = [] for elem in lst2: new1 = lst1 new2 = elem #print(new1 + new2) #theNew = new1 + new2 theNew = new1.append(new2) lst3.append(theNew) print(lst3) # Output: [None, None, None] And you'll get the same result with extend. I guess this should be really easy, but I'm at a loss. Thank you for any suggestions!
tagged with: python
has answer: http://stackoverflow.com/a/48641640
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48641599
answer count: 4
has answer: http://stackoverflow.com/a/48641837
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84279443
accepted answer: http://stackoverflow.com/a/48641467
possible better answer: http://stackoverflow.com/a/48641599
has title: How to merge two lists into a list of multiple lists?

http://stackoverflow.com/q/48547508
has body: I have installed ImageMagick 6.9.9-34-Q8-x64 following Wand documentation, checked "Install developer headers and libraries", set MAGICK_HOME to the right location, but everytime I import anything, Wand complains that it could not find ImageMagick shared libraries: ImportError: MagickWand shared library not found. You probably had not installed ImageMagick library. Try to install: http://docs.wand-py.org/en/latest/guide/install.html#install-imagemagick-on-windows Full output The interesting part is that when I check paths that Wand tried, (tried_path in the full traceback), some of them actually exist, but Wand still fails to use them. What am I missing here?
tagged with: windows
tagged with: python
accepted answer: http://stackoverflow.com/a/48550405
has comment: http://stackoverflow.com/comment/84095978
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84096197
score: 0
tagged with: imagemagick
tagged with: wand
answer count: 3
has comment: http://stackoverflow.com/comment/84096528
has answer: http://stackoverflow.com/a/48550405
has title: Wand can't find ImageMagick shared libraries on Windows
type: Question
has answer: http://stackoverflow.com/a/51996558
has answer: http://stackoverflow.com/a/51844539
possible better answer: http://stackoverflow.com/a/51844539

http://stackoverflow.com/comment/83987803
score: 0
type: Comment
type: QuestionComment
has text: I am using "if not r:break" to come out of the loop. So if empty data is received, it will break the while loop
comment on: http://stackoverflow.com/q/48496982

http://stackoverflow.com/a/76274293
type: Answer
answers question: http://stackoverflow.com/q/48561981
score: 0
has body: The only solution that worked to me is this CMD ["/bin/bash", "-c", "source <your-env>/bin/activate && cd src && python main.py"]

http://stackoverflow.com/comment/84104326
has text: doing that will give the `ValueError: Cannot assign "4": "BookAppt.patientId" must be a "MyUser" instance.` So i use `patient = request.data['patientId']` and it works now. Thank you
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48517811

http://stackoverflow.com/q/48595418
linked to: http://stackoverflow.com/q/4674473
answer count: 1
has comment: http://stackoverflow.com/comment/84188830
favorite count: 0
linked to: http://stackoverflow.com/q/10373660
has comment: http://stackoverflow.com/comment/84189675
type: Question
has comment: http://stackoverflow.com/comment/84189189
has comment: http://stackoverflow.com/comment/84188687
has body: I have a clustered a DataFrame and then used groupby to group it by the resulting 'clusters' value clusterGroup = df1.groupby('clusters') Each group in clusterGroup has multiple rows (and ~30 columns) and I need to create a new dataframe of a single row for each group that is that represents the cluster center for each group. I'm using Kmeans to do this, specifically ".cluster_centers_" The idea was to loop through each group and calculate the cluster center then append this to a new dataframe called logCenters. df1.head() 9367 13575 13577 13578 13580 13585 13587 13588 13589 13707 13708 13719 13722 13725 13817 13819 14894 20326 20379 20384 20431 20433 22337 22346 22386 22388 22391 clusters 493 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 105.0 0.0 0.0 0.0 0.0 0.0 0.0 112.0 0.0 107.0 0.0 0.0 0.0 14 510 0.0 0.0 0.0 113.0 0.0 0.0 111.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 105.0 0.0 0.0 0.0 0.0 0.0 26 513 0.0 0.0 0.0 114.0 0.0 0.0 106.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 106.0 0.0 0.0 0.0 0.0 0.0 26 516 0.0 0.0 0.0 114.0 0.0 0.0 111.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 108.0 0.0 0.0 0.0 0.0 0.0 26 519 0.0 0.0 0.0 113.0 0.0 0.0 113.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 109.0 0.0 0.0 0.0 0.0 0.0 26 . from sklearn.cluster import KMeans K = 1 logCenters = [] for x in clusterGroup: kmeans_model = KMeans(n_clusters=K).fit(x) centers = np.array(kmeans_model.cluster_centers_) logCenters.append(centers) The error I get when running this loop is: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-108-148e4053f5fb&gt; in &lt;module&gt;() 3 logCenters = [] 4 for x in clusterGroup: ----&gt; 5 kmeans_model = KMeans(n_clusters=K).fit(x) 6 centers = np.array(kmeans_model.cluster_centers_) 7 logCenters.append(centers) /home/nbuser/anaconda3_23/lib/python3.4/site-packages/sklearn/cluster/k_means_.py in fit(self…
tagged with: python
type: UnansweredQuestion
has title: for loop to find cluster centers
has answer: http://stackoverflow.com/a/48596626
tagged with: python-3.x
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84188245
tagged with: k-means
has comment: http://stackoverflow.com/comment/84189372
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/48514382
has body: That can be done with a couple of comprehensions like: Code: def get_values_as_tuple(dict_list, keys): return [tuple(d[k] for k in keys) for d in dict_list] How? How does this work? This is a nested comprehension. Let's go from the inside out, and start with: tuple(d[k] for k in keys) This creates a tuple of all of the elements in d that are specified via k in keys. So, that is nice, but what the heck are d, k and keys? keys is passed to the function, and are the keys we will look for in our dicts. k is the individual values in keys from k in keys. d is the individual dicts in dict_list from d in dict_list. The outer comprehension builds a list of the tuples discussed above: [tuple(d[k] for k in keys) for d in dict_list] Test Code: dictionaries = [{'id': 1, 'name': 'test1', 'description': 'foo'}, {'id': 2, 'name': 'test2', 'description': 'bar'}] def get_values_as_tuple(dict_list, keys): return [tuple(d[k] for k in keys) for d in dict_list] print(get_values_as_tuple(dictionaries, ('id', 'name', 'description'))) Results: [(1, 'test1', 'foo'), (2, 'test2', 'bar')]
accepted answer of: http://stackoverflow.com/q/48514315
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84064323
answers question: http://stackoverflow.com/q/48514315
score: 3
type: Answer

http://stackoverflow.com/comment/84169644
type: Comment
has text: Thank you so much.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48586179

http://stackoverflow.com/q/48622538
type: Question
has body: What is the best way to copy django objects for bulk creating, when multiple fields may vary between instances? for example i have: objects_to_create = [] for i in range(5): new_obj = obj new_obj.pk = None new_obj.foo = i objects_to_create.append(new_obj) M.objects.bulk_create(objects_to_create) However, for all of these newly created objects, foo will have value 4, because bulk create is saving 5 instances of new_obj as it is at the end of the loop. Is there a way to create copies that can then be modified before saving? Thanks.
tagged with: bulkinsert
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
has title: Django copy instances bulk create
answer count: 1
accepted answer: http://stackoverflow.com/a/48622998
has answer: http://stackoverflow.com/a/48622998

http://stackoverflow.com/comment/84059163
type: AnswerComment
has text: @roganjosh I think, he suggested to increase the radius with each new occurence of a `(x, y)` tuple in the list. The problem I see with this approach that you have no upper limit for this process - one dot might fill the whole screen. You have to know the maximum frequency and normalise all other values accordingly.
comment on: http://stackoverflow.com/a/48531675
score: 0
type: Comment

http://stackoverflow.com/q/48529256
type: UnansweredQuestion
tagged with: utf-8
linked to: http://stackoverflow.com/q/7262828
upvote count: 2
has comment: http://stackoverflow.com/comment/84053834
duplicate of: http://stackoverflow.com/q/7262828
answer count: 0
has comment: http://stackoverflow.com/comment/84054242
has comment: http://stackoverflow.com/comment/84053796
score: 1
has body: This is killing me. So I have a long string, validated in JSONlint, that only works when loaded as a raw string. raw_string = r'...' normal_string = '...' normal_string = r'%s' % normal_string data = json.loads(raw_string) #&lt;== works data = json.loads(string) #&lt;== doesn't I cannot get the string to be interpreted as raw string as it runs. I believe there is something fishy about this string because there is an error no matter how the problem is approached. (encoding, decoding, etc) You can see the work here: https://repl.it/@dennis_pitt/Interpret-String-as-Raw Please point me in the right direction. Python3.5
downvote count: 1
has comment: http://stackoverflow.com/comment/84054571
favorite count: 0
has comment: http://stackoverflow.com/comment/84053818
tagged with: python-3.x
has title: Python3 Interpret string as Raw
has comment: http://stackoverflow.com/comment/84053986
type: Question
has comment: http://stackoverflow.com/comment/84058976
has comment: http://stackoverflow.com/comment/84058159
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: character-encoding

http://stackoverflow.com/q/48645682
type: UnansweredQuestion
tagged with: noaa
tagged with: matplotlib-basemap
score: -1
has body: Hi i am using this code from here How to read NetCDF file and write to CSV using Python I want to be able to pull out the "Mean_period_of_swell_waves_ordered_sequence_of_data" from from the THREDDS Catalog here but am recieving the below error. I am using Canopy Any ideas why? Thanks Alec IndexErrorTraceback (most recent call last) /home/GRIB-extract-SWPER.py in &lt;module&gt;() 73 #vname = 'surf_el' 74 var = nc.variables[vname] ---&gt; 75 hs = var[istart:istop,iy,ix] 76 tim = dtime[istart:istop] 77 netCDF4/_netCDF4.pyx in netCDF4._netCDF4.Variable.__getitem__ (netCDF4/_netCDF4.c:39739)() netCDF4/_netCDF4.pyx in netCDF4._netCDF4.Variable._get (netCDF4/_netCDF4.c:49789)() IndexError:
tagged with: pygrib
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/28420988
tagged with: netcdf4
type: Question
has answer: http://stackoverflow.com/a/48652906
has title: Change data source from THREDDS Catalouge for NetCDF
tagged with: python

shell
tags question: http://stackoverflow.com/q/48531897
tags question: http://stackoverflow.com/q/48531883
tags question: http://stackoverflow.com/q/48600413
tags question: http://stackoverflow.com/q/48606717
tags question: http://stackoverflow.com/q/48521983
tags question: http://stackoverflow.com/q/48627450
type: Tag
tags question: http://stackoverflow.com/q/48573376
tags question: http://stackoverflow.com/q/48554990
tag name: shell
tags question: http://stackoverflow.com/q/48572194
tags question: http://stackoverflow.com/q/48640209
tags question: http://stackoverflow.com/q/48510110
tags question: http://stackoverflow.com/q/48562073
tags question: http://stackoverflow.com/q/48490633
tags question: http://stackoverflow.com/q/48598623
tags question: http://stackoverflow.com/q/48608814
tags question: http://stackoverflow.com/q/48516449
tags question: http://stackoverflow.com/q/48643406

http://stackoverflow.com/comment/83987733
has text: Thank you for post.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48497230

http://stackoverflow.com/a/48593367
upvote count: 1
answers question: http://stackoverflow.com/q/48593142
has comment: http://stackoverflow.com/comment/84187110
has comment: http://stackoverflow.com/comment/84184609
has comment: http://stackoverflow.com/comment/84187103
has comment: http://stackoverflow.com/comment/84184650
type: Answer
score: 1
has body: There are many ways to accomplish this, one option is to use the re module to identify the first numerical digit (\d) and then capture the remainder (*) as the substring: import re substring = re.sub('^[^\d]*', '', text) print substring output: 3 * 4
downvote count: 0

http://stackoverflow.com/q/48491537
answer count: 1
has comment: http://stackoverflow.com/comment/83976286
has comment: http://stackoverflow.com/comment/83976384
tagged with: python
has answer: http://stackoverflow.com/a/48491642
linked to: http://stackoverflow.com/q/761519
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83976233
has body: I have a directory called my.directory and a file in it called file.py, I need to write a python script that uses file.py and I cannot change the names of the files or directories, moreover the script cannot be in the same directory as file.py. I have tried this: import my.directory.file and this import my\.directory.file neither of which work, I would like to know if this is possible and if so how. Thanks edit: I phrased the above question in a general way because I didn't think the particular details of the problem were important however here are the details anyway. I'm trying to import from python3.6/site-packages
has comment: http://stackoverflow.com/comment/83976643
has title: importing python modules that have a . in the name of the directory
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/761519

http://stackoverflow.com/comment/84241694
comment on: http://stackoverflow.com/q/48622002
has text: Does it start, when you execute your bat-file manualy? You are missing an `r` in front of the string in line: `dst='C:\Users\\"%s"\AppData\SPEED.exe' % USER_NAME`. Furthermore, if your bat-file does not start: delete the `@echo off`-line and start it manualy in the console to get an stderr-print
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84255549
type: Comment
comment on: http://stackoverflow.com/q/48629259
type: QuestionComment
has text: @ChristianDean although it is a dupe the answers to that question are really old and most of the top answers are platform-specific. I would really like to see someone adding a Python 3.6 solution here.
score: 1

http://stackoverflow.com/q/48594611
accepted answer: http://stackoverflow.com/a/48594674
has comment: http://stackoverflow.com/comment/84186283
linked to: http://stackoverflow.com/q/44564414
has answer: http://stackoverflow.com/a/48594675
possible better answer: http://stackoverflow.com/a/48594675
favorite count: 0
type: Question
has title: Preventing function to not stop at first `return` within the `for` loop
linked to: http://stackoverflow.com/q/7664779
tagged with: python
has comment: http://stackoverflow.com/comment/84186352
answer count: 4
has body: I have a function to check for the "negative", "positive" and "zero" value in the list. Below is my function: def posnegzero(nulist): for x in nulist: if x &gt; 0: return "positive" elif x &lt; 0: return "negative" else: return "zero" But when I run this function, it stops after checking the value of the first number in the list. For example: &gt;&gt;&gt; posnegzero([-20, 1, 2, -3, -5, 0, 100, -123]) "negative" I want it to continue for the entire list. In the above function, if I change every instance of return to print, then it does what it should but now I don't want it to say None when the function is complete. Any ideas of where I went wrong?
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-2.7
duplicate of: http://stackoverflow.com/q/44564414
tagged with: list
linked to: http://stackoverflow.com/q/231767
has answer: http://stackoverflow.com/a/48595743
has comment: http://stackoverflow.com/comment/84189583
has answer: http://stackoverflow.com/a/48594762
downvote count: 0
has answer: http://stackoverflow.com/a/48594674

http://stackoverflow.com/comment/84224318
type: AnswerComment
has text: Cool! I'm happy I could help. Check out the [subprocess](https://docs.python.org/3/library/subprocess.html) documentation page on the Python website for more info about the module.
type: Comment
comment on: http://stackoverflow.com/a/48604090
score: 0

http://stackoverflow.com/q/48627890
has body: I'm implementing API which takes users' code and execute at my server. For instance, user submits the code as following push("item") then I want to execute this string code in the users's context, such as users_stack.push("item") What would be the design pattern and how do I convert user's code this way?
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has title: Python - API / wrapper function design pattern
tagged with: exec
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84147887
score: 0
comment on: http://stackoverflow.com/a/48575624
type: Comment
has text: I'm using job.id instead of job.name, because it's bit more easier
type: AnswerComment

http://stackoverflow.com/comment/83999589
has text: Can you post an example of the issue in action?
type: Comment
comment on: http://stackoverflow.com/q/48502930
type: QuestionComment
score: 0

http://stackoverflow.com/a/62351439
has body: I have found a way to close taskmgr.exe (task manger) and without admin perms. import os os.system('wmic process where name="taskmgr.exe" call terminate') It works for me every time.
type: Answer
accepted answer of: http://stackoverflow.com/q/48530006
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48530006
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48533653
answers question: http://stackoverflow.com/q/48533418
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84063708
has body: Looks like Python can't find anything to build. A couple of quick things: You don't seem to have saved your file. Save it with a .py extention. Is Python on your path? Try to type " python " in a cmd terminal.
score: 1

http://stackoverflow.com/a/48628973
has body: You just need to add PySys_SetArgv(1, argv); after Py_Initialize (documentation). This prepends the directory that your program is in to your Python path. (This is equivalent to prepending . to the path, rather than ./Test, but it should be more reliable, for example if your program is not started from its own directory. It gets the needed information on where your program is located from C++ argv) It's probably a bad idea to call your module Test. There's a built-in Python module called test, and on a case-insensitive OS like Windows that might conflict and get loaded instead.
accepted answer of: http://stackoverflow.com/q/48610651
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48610651
score: 3
has comment: http://stackoverflow.com/comment/84271175
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84265149

http://stackoverflow.com/q/48505013
accepted answer: http://stackoverflow.com/a/48508376
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48505354
answer count: 2
has answer: http://stackoverflow.com/a/48508376
tagged with: pandas
score: 7
downvote count: 0
upvote count: 7
favorite count: 0
possible better answer: http://stackoverflow.com/a/48505354
type: Question
has body: Given the following dataframe: import pandas as pd pd.DataFrame({"start": ["2017-01-01 13:09:01", "2017-01-01 13:09:07", "2017-01-01 13:09:12"], "end": ["2017-01-01 13:09:05", "2017-01-01 13:09:09", "2017-01-01 13:09:14"], "status": ["OK", "ERROR", "OK"]}) HAVE: | start | end | status | |---------------------|---------------------|--------| | 2017-01-01 13:09:01 | 2017-01-01 13:09:05 | OK | | 2017-01-01 13:09:07 | 2017-01-01 13:09:09 | ERROR | | 2017-01-01 13:09:12 | 2017-01-01 13:09:14 | OK | I want to convert it to another format, that is, "unfold" the intervals and make them into a DatetimeIndex, and resample the data. The result should look like this: WANT: | | status | |---------------------|-----------| | 2017-01-01 13:09:01 | OK | | 2017-01-01 13:09:02 | OK | | 2017-01-01 13:09:03 | OK | | 2017-01-01 13:09:04 | OK | | 2017-01-01 13:09:05 | OK | | 2017-01-01 13:09:06 | NAN | | 2017-01-01 13:09:07 | ERROR | | 2017-01-01 13:09:08 | ERROR | | 2017-01-01 13:09:09 | ERROR | | 2017-01-01 13:09:10 | NAN | | 2017-01-01 13:09:11 | NAN | | 2017-01-01 13:09:12 | OK | | 2017-01-01 13:09:13 | OK | | 2017-01-01 13:09:14 | OK | Any help is very much appreciated!
tagged with: python
has title: Pandas Datetime Interval Resample to Seconds

http://stackoverflow.com/q/48529318
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 0
has title: Converting CSV to DB for SQL
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84054748
tagged with: sqlite
has comment: http://stackoverflow.com/comment/84053835
has body: I am trying to convert a .csv file I've download into a .db so that I can analyze it in DBreaver with SQLite3. I'm using Anaconda Prompt and python within it. Can anyone point out where I'm mistaken? import pandas as pd import sqlite 3 df = pd.read_csv('0117002-eng.csv') df.to_sql('health', conn) And I just haven't been able to figure out how to set up conn appropriately. All the guides I've read have you do something like: conn = sqlite3.connect("file.db") But, as I mentioned I have only the csv file. And when I did try to do that, it also doesn't work.
has comment: http://stackoverflow.com/comment/84059893
has comment: http://stackoverflow.com/comment/84054185
type: Question

http://stackoverflow.com/q/48536762
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48536974
answer count: 3
has answer: http://stackoverflow.com/a/48536974
has answer: http://stackoverflow.com/a/48566854
has title: Fastest way of finding common elements between two list of lists in python
favorite count: 0
type: Question
upvote count: 4
has body: I have a list as follows. mylist = [ [ [ "chocolate_pudding", 920.8000000000001 ], [ "caramel_pudding", 345.59999999999997 ], [ "pudding", 248.0 ], [ "banana_pudding", 27.599999999999998 ] ], [ [ "biscuits", 190.8 ], [ "chocolates", 33.599999999999994 ], [ "chocolate_pudding", 920.8000000000001 ] ], [ [ "tiramusu", 145.8 ] ], [ [ "cakes", 139.29999999999998 ] ], [ [ "butter_cakes", 133.0 ] ], [ [ "chocolate_pudding", 920.8000000000001 ] ] ] I want to find elements that appears more than one time in the lists (e.g., ["chocolate_pudding", 920.8000000000001]) and want to remove the repeating ones, while keeping the very first entry. So, my output should look like below. mylist = [ [ [ "chocolate_pudding", 920.8000000000001 ], [ "caramel_pudding", 345.59999999999997 ], [ "pudding", 248.0 ], [ "banana_pudding", 27.599999999999998 ] ], [ [ "biscuits", 190.8 ], [ "chocolates", 33.599999999999994 ] ], [ [ "tiramusu", 145.8 ] ], [ [ "cakes", 139.29999999999998 ] ], [ [ "butter_cakes", 133.0 ] ] ] The code I have been trying is as follows. mylist_copy = mylist for item in mylist: myindex = mylist.index(item) #print(item) for single_item in item: #print(single_item) for item_copy in mylist_copy: if mylist_copy.index(item_copy) != myindex: if single_item in item_copy: print(single_item) Since, it has many for loops I want an efficient way of doing it. Note: I also tried; mylist_copy = mylist for item in mylist: myindex = mylist.index(item) for item_copy in mylist_copy: if mylist_copy.index(item_copy) != myindex: print(set(item).intersection(item_copy)) However, intersection does not support lists. Is there an easy and fast way of doing this in python?
has comment: http://stackoverflow.com/comment/84068563
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/48536907
score: 4
has answer: http://stackoverflow.com/a/48536907

http://stackoverflow.com/comment/84039077
comment on: http://stackoverflow.com/q/48521184
type: QuestionComment
has text: im very sorry ,Sir the output is only in string so every time the client count it will send a string
score: 0
type: Comment

http://stackoverflow.com/q/48558679
has comment: http://stackoverflow.com/comment/84129431
answer count: 1
has title: Getting correct intervals on datetime x-axis in Bokeh
has answer: http://stackoverflow.com/a/48590648
tagged with: python
tagged with: plot
score: 0
has comment: http://stackoverflow.com/comment/84127492
has body: I have the code below to plot a stacked bar chart. How should one deal correctly with the datetime format in the dates list and with the x-axis to get a spacing between the x-ticks that corresponds to linear time? dates = ['2018-01-25 13:04:59', '2018-01-26 06:16:23', '2018-01-26 11:03:12', '2018-01-26 14:10:33'] animals = ["pig", "cow", "ape"] colors = ["#c9d9d3", "#718dbf", "#e84d60"] data = {'dates' : dates, 'pig' : [2, 1, 4, 3], 'cow' : [5, 3, 4, 2], 'ape' : [3, 2, 4, 4]} source = ColumnDataSource(data=data) p = figure(x_range=dates, plot_height=350) p.vbar_stack(animals, x='dates', width=0.9, color=colors, source=source, legend=[value(x) for x in animals])
tagged with: bokeh
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/135687988
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48643004
type: Comment
has text: This should not be the accepted answer, you do want to do all that in a venv most of the time

http://stackoverflow.com/a/48540584
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48540438
has body: Use cumcount and if need new column as first add insert: df['day'] = df.groupby(level=0).cumcount() + 1 print (df) a b day 9 a1 b1 1 9 a2 b2 2 12 a3 b3 1 14 a4 b4 1 df.insert(0, 'day', df.groupby(level=0).cumcount() + 1) print (df) day a b 9 1 a1 b1 9 2 a2 b2 12 1 a3 b3 14 1 a4 b4
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48540438

http://stackoverflow.com/comment/84189378
score: 0
has text: This is some hacky, yet pretty awesome work. I'll accept this as the answer, but I'd really like if `a`, `b`, `a_ind`, `b_ind` can be different types. Thanks a lot. :-D
type: AnswerComment
comment on: http://stackoverflow.com/a/48588441
type: Comment

http://stackoverflow.com/q/48622983
has answer: http://stackoverflow.com/a/48633171
tagged with: apache
has body: We are trying to build a flaskapp by following the instructions of PythonProgramming. Please find the folder structure below. username@server:/var/www/FlaskApp$ pwd /var/www/FlaskApp username@server:/var/www/FlaskApp$ ls FlaskApp flaskapp.wsgi username@server:/var/www/FlaskApp/FlaskApp$ pwd /var/www/FlaskApp/FlaskApp username@server:/var/www/FlaskApp/FlaskApp$ ls __init__.py static templates xlogin.py Content of flaskapp.wsgi #!/usr/bin/python import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/FlaskApp/FlaskApp") from FlaskApp import app as application application.secret_key = 'Thisissupposedtobesecret!' Content of "/etc/apache2/sites-available/FlaskApp.conf" &lt;VirtualHost *:80&gt; ServerName &lt;server IP&gt; ServerAdmin &lt;email&gt; WSGIDaemonProcess myapp python-path=/var/www/FlaskApp/FlaskApp WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi process-group=myapp application-group=%{GLOBAL} &lt;Directory /var/www/FlaskApp&gt; &lt;Files flaskapp.wsgi&gt; Order allow,deny Allow from all &lt;/Files&gt; &lt;/Directory&gt; Alias /static /var/www/FlaskApp/FlaskApp/static &lt;Directory /var/www/FlaskApp/FlaskApp/static/&gt; Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; When the app is run directly with python2 or python3, it is running fine. username@server:/var/www/FlaskApp/FlaskApp$ python3 __init__.py /home/raj/.local/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:794: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning. 'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and ' * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat /home/raj/.local/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:794: FSADeprecationWarning: SQLAL…
upvote count: 1
tagged with: python
tagged with: flask
has title: WSGI script '/var/www/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module
score: 0
tagged with: mod-wsgi
answer count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: wsgi

assign
tags question: http://stackoverflow.com/q/48558077
type: Tag
tag name: assign

http://stackoverflow.com/comment/84184670
comment on: http://stackoverflow.com/a/48593728
type: Comment
has text: the sample code works fine on unixlike platforms -- the OP's issue is a windows-specific quirk
type: AnswerComment
score: 1

http://stackoverflow.com/a/48500739
has body: To me it seems that check_file_for_data always consumes two lines from the file when you do next(islice(file_obj, 1, 2)) One line is skipped and the next returned. I don't really see how your snippet could have ever worked without seeking back to the start of the file in line_producer.
has comment: http://stackoverflow.com/comment/83994949
type: Answer
answers question: http://stackoverflow.com/q/48500283
has comment: http://stackoverflow.com/comment/84030441
has comment: http://stackoverflow.com/comment/84008648
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48493370
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48493386
has body: To avoid duplicates of the same user, I want to neatly organize a nested dictionary of {k: artist1, artist2, artist3, etc} using pandas groupby function. Here is sample data (my instinct tells me chain an agg func?) ...like df.groupby('users')? users artist 0 00001411dc427966b17297bf4d69e7e193135d89 the most serene republic 1 00001411dc427966b17297bf4d69e7e193135d89 stars 2 00001411dc427966b17297bf4d69e7e193135d89 broken social scene 3 00001411dc427966b17297bf4d69e7e193135d89 have heart 4 00001411dc427966b17297bf4d69e7e193135d89 luminous orange 5 00001411dc427966b17297bf4d69e7e193135d89 boris 6 00001411dc427966b17297bf4d69e7e193135d89 arctic monkeys 7 00001411dc427966b17297bf4d69e7e193135d89 bright eyes 8 00001411dc427966b17297bf4d69e7e193135d89 coaltar of the deepers 9 00001411dc427966b17297bf4d69e7e193135d89 polar bear club 10 00001411dc427966b17297bf4d69e7e193135d89 the libertines 11 00001411dc427966b17297bf4d69e7e193135d89 death from above 1979 12 00001411dc427966b17297bf4d69e7e193135d89 owl city 13 00001411dc427966b17297bf4d69e7e193135d89 coldplay 14 00001411dc427966b17297bf4d69e7e193135d89 okkervil river 15 00001411dc427966b17297bf4d69e7e193135d89 jim sturgess 16 00001411dc427966b17297bf4d69e7e193135d89 deerhoof 17 00001411dc427966b17297bf4d69e7e193135d89 fear before the march of flames 18 00001411dc427966b17297bf4d69e7e193135d89 breathe carolina 19 00001411dc427966b17297bf4d69e7e193135d89 mstrkrft
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83980037
has comment: http://stackoverflow.com/comment/83980021
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/22219004
tagged with: pandas-groupby
tagged with: pandas
score: 1
answer count: 1
tagged with: dataframe
upvote count: 1
has title: pandas dataframe - group artists per unique user
accepted answer: http://stackoverflow.com/a/48493386

http://stackoverflow.com/comment/84226694
score: 0
comment on: http://stackoverflow.com/q/48613706
has text: @t.m.adam input hash is any digit from 0 to 99. If it’s any easier it is 2 digits. Otherwise it can be 1 or 2
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48494572
answers question: http://stackoverflow.com/q/48494486
accepted answer of: http://stackoverflow.com/q/48494486
has body: If you implement an __iter__() method, you can do this functionality: Code: class MockList: def __iter__(self): return iter(range(1, 6)) Test Code: for i in MockList(): print(i) Results: 1 2 3 4 5
score: 6
upvote count: 6
type: Answer
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48617759
accepted answer: http://stackoverflow.com/a/48630320
linked to: http://stackoverflow.com/q/48548135
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48630320
has body: Anther question to my previous query, Can we access all the account stacks and their information from AWS Lambda? I have been asked to write a script to validate if all the stack-set have got created/updated in their appropriate region by putting their logs in the splunk. Here's my approach- Create a simple python (AWS Lambda) script to validate all the region for their stackset and update its log information to the splunk (on each create or update of a stackset). Hardcode all the accounts in the python script eg. accounts = [535353..., 435..., 645542..., etc] Iterate over all accounts and their region using python-trophosphere or boto3 And for each region run a query to describe stack sets or describe events to validate (after a create/update script has run) whether the stackset has got create/updated. Code excerpt would be: client = boto3.client('cloudformation') description = client.describe_stack_set() parse description to verify the status of the particular stackset for that account region Update all that parsed description or (entire description) in the splunk logs. But I'm not sure on: if I'd be able to access all the accounts and their regions from a lambda script. The approach is right or not Suggest me a solution if I'm not on the right path.
type: Question
has title: Can we access all the account stacks and their information from AWS Lambda?
tagged with: aws-cloudformation
tagged with: python
tagged with: lambda

http://stackoverflow.com/comment/84224250
comment on: http://stackoverflow.com/q/48572525
has text: fields.encode('utf8') returns 'object has no attribute 'encode'.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/84076859
comment on: http://stackoverflow.com/a/48540812
score: 1
type: Comment
has text: You should use the csv module instead of splitting on commas.
type: AnswerComment

http://stackoverflow.com/q/48494018
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48494603
score: -3
upvote count: 1
has answer: http://stackoverflow.com/a/48494119
tagged with: python
has answer: http://stackoverflow.com/a/48494062
favorite count: 0
has comment: http://stackoverflow.com/comment/83985551
has comment: http://stackoverflow.com/comment/83981260
has title: Print variable before string
has body: Can someone tell me what I'm doing wrong? 1) age = int(input("How old are you? ")) print((age), + ("is how old you are.")) Thanks
has answer: http://stackoverflow.com/a/48494081
type: Question
has answer: http://stackoverflow.com/a/48494061
downvote count: 4
has comment: http://stackoverflow.com/comment/83981235

http://stackoverflow.com/comment/84269070
comment on: http://stackoverflow.com/a/48635963
type: AnswerComment
score: 1
has text: Hi, I don't want to use GenericViews, also I'm curious why the current approach isn't working and not so much in an alternatives. Thanks aynway!
type: Comment

http://stackoverflow.com/a/48615061
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48614047
has body: With a minor alteration (two lines added, and one altered), it worked for me: import turtle line = turtle.Turtle() window = turtle.Screen() def click_location(x,y): line.up() line.setpos(x,y) line.down() #return line.pos() print(line.pos()) location = window.onclick(click_location) print(location) turtle.mainloop()

http://stackoverflow.com/a/48500504
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83994317
answers question: http://stackoverflow.com/q/48500152
has comment: http://stackoverflow.com/comment/83994499
accepted answer of: http://stackoverflow.com/q/48500152
type: Answer
downvote count: 0
has body: As usual with interactive features which use the event loop of a GUI you need to keep a reference to the object that handles the callback. The problem with the approach of not storing the timer in this code def _redraw_later_not_ok(self, fig): print('start') timer = fig.canvas.new_timer(interval=10) timer.single_shot = True timer.add_callback(lambda : fig.canvas.draw_idle()) timer.start() print('stop') is that timer gets garbage collected once the _redraw_later_not_ok function terminates (i.e. directly after stop is printed). At this point there would be a pointer to a place in memory, which may or may not store the callback (any more). An attempt by the python interpreter to call the callback would hence (most probably) fail. The solution is indeed to always keep a reference to the object that steers the callback. This is the solution shown in _redraw_later_ok, where the timer is made a class attribute, self.timer. Such that it can later be used at the time the callback is called. I do not understand in how far using this working approach would prevent the use of several figures, so it may make sense to create a MWE with two figures that shows the problem clearly.

http://stackoverflow.com/a/48787532
upvote count: 1
answers question: http://stackoverflow.com/q/48630484
score: 0
has comment: http://stackoverflow.com/comment/84746770
has comment: http://stackoverflow.com/comment/84664306
has comment: http://stackoverflow.com/comment/84747045
downvote count: 1
has body: As you do not provide the URL from where you download its guessing work. Target most likely has a recapta-like wall installed to prevent scraping. So be sure you don't hit this "recapta" wall and if you do implement code that notifies you to perform a manual task for granting access. For js this solution was given by zavodnyuk here: try to set custom User-Agent with compatible one (e.g. from your real browser). capabilities: { 'browserName': 'chrome', chromeOptions: {args: [ "user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36", "--headless", "--disable-gpu" ] } worked for selenium/protractor on js I hope this hints you in the right direction as there is not much about it described for python on the internet. EDIT based on comment1: In basic debugging mode I rely on print-statements at the start of possible candidate defs. Where I say printstatement it can be a write line to file as well. Not relying on thrid party fancy packages because I want to learn from the code most of the times and then is above approach time consuming but well worth the effort of spend time. For example how I bluntly debug: def header_inspect(self, ID, action, data): print 'header_inspect, ID : %s\n, action : %s\nprocess-data : %s' % (ID, action, data)
type: Answer

http://stackoverflow.com/comment/83990707
type: Comment
has text: Right, now how do I print it for Month==1?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48498519

http://stackoverflow.com/q/48528519
type: UnansweredQuestion
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/37373975
has title: Bokeh autofill datetime axis missing values: how to stop it?
tagged with: datetime
tagged with: python
tagged with: bokeh
score: 4
has body: I'm trying to build an interactive plot from a pandas dataframe of financial data. The dataframe index has some gap when market are closed, or during weekends. The problem is that Bokeh always autofill those gaps when I use the dataframe index as xasis, making it visually ugly. How can I print my data without gaps?
has answer: http://stackoverflow.com/a/48566153
has comment: http://stackoverflow.com/comment/91629295
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/97008248
has comment: http://stackoverflow.com/comment/97056036
has answer: http://stackoverflow.com/a/48533946
answer count: 2

http://stackoverflow.com/a/48634230
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48634161
type: Answer
has body: When you call montecarlo with the second argument of 0, it's going to pass it to randaxis, which uses it to make a dict with a bunch of empty lists as values. Then you use the length of the first such empty list to determine the number of iterations of the first loop in montecarlo, the one that populates inshape, but of course, since it's empty, you're iterating over range(0), which doesn't iterate at all, and nothing is added to inshape. Eventually you get here: nratio = sumis/len(inshape) wherein you try to divide by the length of an empty list, which is 0, and everything explodes. This will happen anytime you pass 0 as the second argument to montecarlo.

http://stackoverflow.com/a/48535284
score: 1
type: Answer
downvote count: 0
has body: From the Python docs for shelf, Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf Your first try, db['bob']['gender'] = 'u', doesn't work since it's not an assignment to the shelf itself (it's an assignment to the dict db['bob']['gender']). Your second try does work since it is assignment to a key of the shelf itself. The examples in the docs will further hammer in this point. If you were to open with writeback=True, you would be able to code normally. However, as the docs note "it would also consume more memory and make the d.close() operation slower."
upvote count: 1
answers question: http://stackoverflow.com/q/48534933

http://stackoverflow.com/a/48566854
upvote count: 1
score: 1
type: Answer
has body: Once a great person said, take only what you want, why delete? Now two person said : mylist = [[["chocolate_pudding", 920.8000000000001], ["caramel_pudding", 345.59999999999997], ["pudding", 248.0], ["banana_pudding", 27.599999999999998]], [["biscuits", 190.8], ["chocolates", 33.599999999999994], ["chocolate_pudding", 920.8000000000001]], "tiramusu", 145.8, "cakes", 139.29999999999998, "butter_cakes", 133.0, "chocolate_pudding", 920.8000000000001] result=[] track=[] for i in mylist: sublist=[] for k in i: if k not in track: track.append(k) sublist.append(k) if sublist: result.append(sublist) print(result) output: [[['chocolate_pudding', 920.8000000000001], ['caramel_pudding', 345.59999999999997], ['pudding', 248.0], ['banana_pudding', 27.599999999999998]], [['biscuits', 190.8], ['chocolates', 33.599999999999994]], 'tiramusu', 145.8, 'cakes', 139.29999999999998, 'butter_cakes', 133.0]
downvote count: 0
answers question: http://stackoverflow.com/q/48536762

http://stackoverflow.com/comment/126235503
score: 0
has text: Nice to use `mamba` and install all at once https://stackoverflow.com/a/69137255/13697228
comment on: http://stackoverflow.com/q/48589141
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48640209
has title: Command gives different behaviour in terminal or in program (Python and C++)
tagged with: shell
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
tagged with: python
tagged with: c++
tagged with: system
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48641035
tagged with: subprocess
has body: I am trying to execute the following command programatically: ~$ obabel -:"ccco" -O /home/user/output.png obabel is a chemistry library, and basically if the string in the "" is complete nonsense chemically, it won't be able to generate the PNG file, and if it is a legitimate chemical structure the PNG file will be generated. This works in the terminal. However, if I call the same command with Python, PNG files are generated for complete nonsense input strings which don't generate a PNG when the command is executed in the terminal. I'm using subprocess like this: cmd = 'obabel -:"ccco" -O /home/user/output.png' proc = sub.Popen([cmd], shell=True, stderr=sub.PIPE) res = proc.communicate() I have also tried this: os.system(cmd) And tried Python2 and Python3. This happens when running scripts from the terminal or iPython. I have also tried using C++ and running the cmd like this: std::string cmd = "obabel -:\"ccco\" -O /home/user/output.png"; system(cmd.c_str());
score: 1
has answer: http://stackoverflow.com/a/48641035
answer count: 1

http://stackoverflow.com/a/48528342
upvote count: 4
has body: For completeness, one more approach is to only break lines within already existing parentheses or bracket pairs. It avoids the parenthesis wrapping and newline-escaping, but I feel it's much less readable: t_values = df_grouped_by_day.sort_values('day_of_week' ).groupby(['day_of_week', 'day_of_week_name'] )['Show_up' ].apply(lambda sample: ttest_ind(population, sample) ).reset_index())
downvote count: 0
has comment: http://stackoverflow.com/comment/84071389
answers question: http://stackoverflow.com/q/48528146
type: Answer
score: 4

http://stackoverflow.com/comment/84073709
comment on: http://stackoverflow.com/a/48536382
type: Comment
score: 0
type: AnswerComment
has text: Updated the answer, switched up df1 and df2 based on your previous example, and added the ignore.case parameter. Hope this helps!

http://stackoverflow.com/a/50808998
downvote count: 0
type: Answer
score: 11
has body: There is no max limit, but the input is eventually truncated to 20,000 bits. Even if you don't understand the algorithm (I don't), you can follow along in the source code. First, CPython splits the input into 32-bit chunks, and creates a bytearray out of them: https://github.com/python/cpython/blob/55edd0c185ad2d895b5d73e47d67049bc156b654/Modules/_randommodule.c#L258-L293 Then, the Mersene Twister PRNG is seeded with the number 19,650,218, after which some mathematical stuff happens that is well above my understanding: https://github.com/python/cpython/blob/55edd0c185ad2d895b5d73e47d67049bc156b654/Modules/_randommodule.c#L172-L196 But in the midst of all that action, notice this line: https://github.com/python/cpython/blob/55edd0c185ad2d895b5d73e47d67049bc156b654/Modules/_randommodule.c#L180 Anything after the Nth element is never looped over, and therefore effectively discarded. In this case is N is 624 (it's a magic constant: https://github.com/python/cpython/blob/55edd0c185ad2d895b5d73e47d67049bc156b654/Modules/_randommodule.c#L76), so no more than 625 * 32 = 20,000 input bytes are used. Since the comment in the code says "from the right", we will take them at their word (this is all pretty far above my head, so I'm in no position to question them). Therefore I feel confident enough to conclude that the rightmost 20,000 bits of the input are used, and the rest discarded. That said, I imagine the definition of "rightmost" is platform-dependent, so it's probably not behavior you should rely on.
answers question: http://stackoverflow.com/q/48503151
upvote count: 11
has comment: http://stackoverflow.com/comment/125496966
accepted answer of: http://stackoverflow.com/q/48503151
has comment: http://stackoverflow.com/comment/133177975
type: AcceptedAnswer

http://stackoverflow.com/a/48578700
type: Answer
has body: In a sense, this is slightly subjective but there is a clear answer. Do not add new attributes to the original object, create a new class. I could argue about at least one clear reason for that. A new attribute is making the object do more than it used to do, so it is surely violating the single responsibility principle. So, create a new class to hold this data. Yet, we could give you more information if we actually knew what you are trying to do. So, what about adding some more info?
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48578568
answers question: http://stackoverflow.com/q/48578568

http://stackoverflow.com/q/48597673
type: Question
tagged with: google-drive-api
has answer: http://stackoverflow.com/a/49514364
type: UnansweredQuestion
tagged with: wget
tagged with: python
has body: I have been provided with access to a zip file/folder which is stored in my google drive and inside "Shared with me". How can I download it to my laptop through terminal using "wget" or python or anything related. The url for the whole folder within which it is contained goes like, https://drive.google.com/drive/folders/13cx4SBFLTX8CqIqjjec9-pcadGaJ0kNj and the shareable link to the zip file is https://drive.google.com/open?id=1PMJEk3hT-_ziNhSPkU9BllLYASLzN7TL. Since the files are 12GB in size in total, downloading them by clicking is quite tiresome when working with Jupyter notebook.
has comment: http://stackoverflow.com/comment/84232097
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/98622831
has comment: http://stackoverflow.com/comment/84232110
linked to: http://stackoverflow.com/q/48133080
linked to: http://stackoverflow.com/q/25010369
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84204816
linked to: http://stackoverflow.com/q/39003409
has title: Downloading zip folder/file from google drive from shared with me folder
has comment: http://stackoverflow.com/comment/84232516
favorite count: 0
has answer: http://stackoverflow.com/a/70795240
tagged with: jupyter-notebook
tagged with: curl

http://stackoverflow.com/comment/84011008
type: QuestionComment
has text: @denbuttigieg, try to pass `GridSearchCV(..., verbose=3)` and check what does it output...
comment on: http://stackoverflow.com/q/48507651
type: Comment
score: 1

http://stackoverflow.com/q/48597842
favorite count: 0
type: Question
tagged with: pandas
score: 1
duplicate of: http://stackoverflow.com/q/19966018
tagged with: python
has title: pandas - Apply mean to a specific row in grouped dataframe
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: I've been scratching my head about this one for a little while. I've got a data frame which looks like this: import pandas as pd import numpy as np d={'gameweek': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 2, 9: 2, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2, 16: 3, 17: 3, 18: 3, 19: 3, 20: 3, 21: 3, 22: 3, 23: 3}, 'match_id': {0: 0, 1: 0, 2: 1, 3: 1, 4: 2, 5: 2, 6: 3, 7: 3, 8: 4, 9: 4, 10: 5, 11: 5, 12: 6, 13: 6, 14: 7, 15: 7, 16: 8, 17: 8, 18: 9, 19: 9, 20: 10, 21: 10, 22: 11, 23: 11}, 'points': {0: 48.0, 1: np.nan, 2: 41.0, 3: 40.0, 4: 55.0, 5: 50.0, 6: 38.0, 7: 45.0, 8: 40.0, 9: 37.0, 10: 29.0, 11: np.nan, 12: 43.0, 13: 15.0, 14: 46.0, 15: 43.0, 16: 24.0, 17: 45.0, 18: 40.0, 19: 20.0, 20: 45.0, 21: np.nan, 22: 49.0, 23: 35.0}, 'name': {0: 'team1', 1: 'Average', 2: 'team2', 3: 'team3', 4: 'team4', 5: 'team5', 6: 'team6', 7: 'team7', 8: 'team2', 9: 'team7', 10: 'team5', 11: 'Average', 12: 'team1', 13: 'team3', 14: 'team6', 15: 'team4', 16: 'team5', 17: 'team1', 18: 'team7', 19: 'team3', 20: 'team6', 21: 'Average', 22: 'team2', 23: 'team4'}} df = pd.DataFrame.from_dict(data=d) df.head() gameweek match_id name points 0 1 0 team1 48.0 1 1 0 Average NaN 2 1 1 team2 41.0 3 1 1 team3 40.0 4 1 2 team4 55.0 What I'd like to do is replace all of the 'NaNs' with the mean of the grouped gameweek columns. I can work out how to get the mean using a groupby function, e.g. df['points'].groupby(by=df['gameweek']).mean() gameweek 1 45.285714 2 36.142857 3 36.857143 Name: points, dtype: float64 But I'm struggling to then apply that to the correct field for each 'gameweek' column. I've looked at using 'fillna' but can't work out how to target a specific row with a specific value. Any help would be appreciated. Many thanks.
linked to: http://stackoverflow.com/q/19966018

http://stackoverflow.com/q/48590161
has comment: http://stackoverflow.com/comment/84178010
has body: Like we know, sqlalchemy logic operator is and_, or_, in_, but Python built-in logic operator is and, or,in. Why sqlalchemy doesn't use those built-in operator directly?
linked to: http://stackoverflow.com/q/42681231
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84177647
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/84177921
type: Question
has title: why sqlalchemy logic operator is different from Python built-in
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/42681231
tagged with: python

http://stackoverflow.com/a/48671704
score: 0
upvote count: 1
type: Answer
downvote count: 1
has body: Use a Python 3 Docker image (not 2), and I wouldn't use venv here considering the CI use case and that PipEnv now exists. Here's an example CircleCI 2.0 config from our Django example project: https://github.com/CircleCI-Public/circleci-demo-python-django/blob/master/.circleci/config.yml Respectfully, Ricardo N Feliciano Developer Evangelist, CircleCI
answers question: http://stackoverflow.com/q/48632887

http://stackoverflow.com/q/48642747
has comment: http://stackoverflow.com/comment/84282083
has body: #@ Row 1, Column 4: Invalid character value for cast specification @# BCC,01,12697,2013-12- 12,1.0,2014004,CR,ACCOUN TS PAYABLE,-86.23000,,2200-000-000,, ,,,,True,,0,False,,,False,,,,,,0.00000,0.00000 I am trying to remove the tab in the date value and elsewhere in each row of data. columndata = [str(items.replace('\t', '')) for items in list(row)] However, this command returns the following error: File "apdetfac.py", line 60, in &lt;listcomp&gt; columndata = [str(items.replace('\t', '')) for items in list(row)] AttributeError: 'NoneType' object has no attribute 'replace' I tried converting items to str as follows str(items) in list(row) but that generated another error. What to do?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48642919
has comment: http://stackoverflow.com/comment/84281944
has comment: http://stackoverflow.com/comment/84282146
tagged with: replace
score: 0
has comment: http://stackoverflow.com/comment/84282272
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/84282339
has comment: http://stackoverflow.com/comment/84282309
has answer: http://stackoverflow.com/a/48643047
has comment: http://stackoverflow.com/comment/84282270
has comment: http://stackoverflow.com/comment/84282055
has title: python AttributeError: 'NoneType' object has no attribute 'replace' in list
type: Question
has comment: http://stackoverflow.com/comment/84282120
has comment: http://stackoverflow.com/comment/84282194
has comment: http://stackoverflow.com/comment/84282201

http://stackoverflow.com/a/48492694
has body: For your "doubles" you have sets with single values in the them. You can retrieve the first (and only) value a few different ways: &gt;&gt;&gt; s = frozenset({'GRO73461'}) Tuple unpacking: &gt;&gt;&gt; value, = s &gt;&gt;&gt; value 'GRO73461' Convert to a list then take the first index: &gt;&gt;&gt; list(s)[0] 'GRO73461' Create an iterator, then take the next value: &gt;&gt;&gt; next(iter(s)) 'GRO73461' Use a generator expression with next: &gt;&gt;&gt; next(value for value in s) 'GRO73461' You have a list of tuples representing doubles: &gt;&gt;&gt; double = (frozenset({'GRO73461'}), frozenset({'ELE17451'}), 1.0) Using the first tuple unpacking method I showed you, you can unpack these values, all in one expression: &gt;&gt;&gt; (first,), (second,), third = double &gt;&gt;&gt; first, second, third 'GRO73461', 'ELE17451', 1.0 To format the double values you can use a format string: &gt;&gt;&gt; double_format = '{} {} {:0.4f}' &gt;&gt;&gt; double_format.format(first, second, third) 'GRO73461 ELE17451 1.0000' Altogether: &gt;&gt;&gt; doubles = [ ... (frozenset({'GRO73461'}), frozenset({'ELE17451'}), 1.0), ... (frozenset({'ELE26917'}), frozenset({'GRO99222'}), 1.0), ... (frozenset({'SNA80192'}), frozenset({'ELE17451'}), 1.0), ... (frozenset({'DAI22896'}), frozenset({'ELE17451'}), 0.9), ... (frozenset({'GRO99222'}), frozenset({'ELE17451'}), 0.8125) ... ] &gt;&gt;&gt; for double in doubles: ... (first,), (second,), third = double ... print double_format.format(first, second, third) GRO73461 ELE17451 1.0000 ELE26917 GRO99222 1.0000 SNA80192 ELE17451 1.0000 DAI22896 ELE17451 0.9000 GRO99222 ELE17451 0.8125
has comment: http://stackoverflow.com/comment/83978926
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48491412
score: 5
accepted answer of: http://stackoverflow.com/q/48491412
has comment: http://stackoverflow.com/comment/83978893
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84173480
type: Comment
type: AnswerComment
has text: Note that you can calculate `y_values` simply as `fx_lambda(x_values)`
score: 0
comment on: http://stackoverflow.com/a/48588111

http://stackoverflow.com/q/48539829
tagged with: paramiko
type: Question
tagged with: video
has comment: http://stackoverflow.com/comment/84077043
score: 0
tagged with: transfer
has comment: http://stackoverflow.com/comment/84110222
has comment: http://stackoverflow.com/comment/84114459
answer count: 0
has body: I've recently come across the functionality or the requests package of python (http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow) that allows to defer downloading the response body until you access the Response.content of a file, as told here : https://stackoverflow.com/a/16696317/8376187 def download_file(url): local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) return local_filename I use this to stream videos and since the headers of the file is present, my video player read the video smoothly. I would like to do the same with an SSH/SFTP file transfer, i have tryied to use paramiko for that, but my code reads the file without getting the indexes and headers of the file making my video player fail and and is also very slow. The code (assuming connected paramiko SSHClient() ) : sftp_client = client.open_sftp() remote_file = sftp_client.open('remotefile') with open('localfile', 'wb') as f: try: data = remote_file.read(1024) while (data): f.write(data) data = remote_file.read(1024) finally: remote_file.close() Is there a way to reproduce the behavior of requests' "stream=True" option with an ssh/sftp transfer in python ? Thanks :)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84091889
has title: Streaming binary file from ssh in python
linked to: http://stackoverflow.com/q/16694907
has comment: http://stackoverflow.com/comment/84106662
has comment: http://stackoverflow.com/comment/84110730
has comment: http://stackoverflow.com/comment/84110052
has comment: http://stackoverflow.com/comment/84112873
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/84112437

http://stackoverflow.com/q/48618709
tagged with: ffmpeg
upvote count: 2
tagged with: multithreading
has answer: http://stackoverflow.com/a/48677716
has body: I'm building real time multiple videostream monitoring using ffmpeg and subrocess. I currently have the following code, inspired by "Async and await with subprocesses" post. The problem is that after a certain period of time the output stops printing and the processes go into zombie mode. I guess that this problem is related to the overload of PIPE or deadlock. Help needed. """Async and await example using subprocesses Note: Requires Python 3.6. """ import os import sys import time import platform import asyncio async def run_command_shell(command): """Run command in subprocess (shell) Note: This can be used if you wish to execute e.g. "copy" on Windows, which can only be executed in the shell. """ # Create subprocess process = await asyncio.create_subprocess_shell( command, stderr=asyncio.subprocess.PIPE) # Status print('Started:', command, '(pid = ' + str(process.pid) + ')') # Wait for the subprocess to finish stdout, stderr = await process.communicate() # Progress if process.returncode == 0: print('Done:', command, '(pid = ' + str(process.pid) + ')') else: print('Failed:', command, '(pid = ' + str(process.pid) + ')') # Result result = stderr.decode().strip() # Real time print print(result) # Return stdout return result def make_chunks(l, n): """Yield successive n-sized chunks from l. Note: Taken from https://stackoverflow.com/a/312464 """ if sys.version_info.major == 2: for i in xrange(0, len(l), n): yield l[i:i + n] else: # Assume Python 3 for i in range(0, len(l), n): yield l[i:i + n] def run_asyncio_commands(tasks, max_concurrent_tasks=0): """Run tasks asynchronously using asyncio and return results If max_concurrent_tasks are set to 0, no limit is applied. Note: By default, Windows uses SelectorEventLoop, which does not support subprocesses. Therefore ProactorEventLoop is used on Windows. https://docs.python.org/3/library/asyncio-eventloops.html#windows """ all_results = [] if max_concurrent_tasks == 0: chunks = [tasks] else: chunks = make_chunks(l=tasks, n=m…
tagged with: python
linked to: http://stackoverflow.com/q/31784484
has title: Non-blocking realtime read from multiple shell subprocesses (Python)
has comment: http://stackoverflow.com/comment/84244262
linked to: http://stackoverflow.com/q/17667004
tagged with: subprocess
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/312443
score: 1
tagged with: asynchronous
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84244321
linked to: http://stackoverflow.com/q/23611396
type: Question
accepted answer: http://stackoverflow.com/a/48677716

http://stackoverflow.com/a/48515779
downvote count: 0
answers question: http://stackoverflow.com/q/48515746
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84026508
has body: You need to provide the index of the max element in a list to pop x = [66,1,4,3,6,55] list1 = [x.pop(x.index(max(x)))] print(list1) Output [66] Request from Comments: x = [66,1,4,3,6,55] list1 = [] while x: list1.append(x.pop(x.index(max(x)))) print(list1)
has comment: http://stackoverflow.com/comment/84026076
upvote count: 5
has comment: http://stackoverflow.com/comment/84026157
type: Answer
has comment: http://stackoverflow.com/comment/84027350
accepted answer of: http://stackoverflow.com/q/48515746
score: 5

http://stackoverflow.com/comment/84218983
score: 0
type: QuestionComment
has text: you could potentially implement a "`get_chat_env()`" function
type: Comment
comment on: http://stackoverflow.com/q/48611220

http://stackoverflow.com/q/48495233
has title: MongoDB aggreagate query to get list of each element and its count for each record
has comment: http://stackoverflow.com/comment/84230762
type: Question
has body: In my mongodb, i have few collections, i want to create a new collection by comparing the collection 1 and collection 2 using pymongo. Collection 1 : Object id timestamp Prof_Name subjects1 abc67478898k ISODate("2018-01-03T09:26:37.541Z") ABDC "sub1, sub2, sub3" jjjjjjjjjj ISODate("2018-01-03T09:26:37.541Z") XYZ "sub2, sub4, sub8" Collection 2 : Object id timestamp UUID subjects2 rating score 3333333 ISODate("2018-01-03TZ") 7897 "sub1,sub4, sub7" 7 10 444444 ISODate("2018-01-03TZ") 4532 "sub2" 4 6 777777 ISODate("2018-01-03TZ") 7876 "sub1,sub2,sub3" 8 8 1111111 ISODate("2018-01-03TZ") 654 "sub1,sub3" 7 8 I'm getting my 3 collection, for each subject by Prof_name find matching subjects in collection2 and the UUID and UUID_count between a certain timestamp and my mongo query is as below: db.data1.aggregate([ {"$lookup":{ "from":"data2", "let":{"subject":{"$split":["$SUBJECT",", "]}}, "pipeline":[ {"$match": {"expr":{"$and":[{"$eq":[{"$year":"$timestamp"}, 2016]}, {"$eq":[{"$month":"$timestamp"}, 1]}]}}}, {"$addFields":{"SUBJECT_ID":{"$split":["$SUBJECT_ID",", "]},"SUBJECT":"$$subject"}}, {"$unwind":"$SUBJECT"}, {"$match":{"$expr":{"$in":["$SUBJECT","$SUBJECT_ID"]}}}, {"$facet":{ "UUID":[{"$group":{"_id":{"id":"$_id","UUID":"$UUID"}}},{"$count":"UUID_Count"}], "REST":[ {"$group":{"_id":null,"subjects_list":{"$addToSet":"$SUBJECT"},"UUID_distinct_list":{"$addToSet":"$UUID"}}}, {"$addFields":{"subject_count":{"$size":"$subjects_list"},"UUID_distinct_count":{"$size":"$UUID_distinct_list"}}}, {"$project":{"_id":0}} ] }}, {"$replaceRoot":{"newRoot":{"$mergeObjects":[{"$arrayElemAt":["$UUID",0]},{"$arrayElemAt":["$REST",0]}]}}} ], "as":"ref_data" }}, {"$unwind":{"path":"$ref_data","preserveNullAndEmptyArrays":true}}, {"$addFields":{"ref_data.Prof_Name":"$Prof_Name"}}, {"$replaceRoot":{"newRoot":"$ref_data"}}, {"$out":"data3"} ]) Above query gives me below collection. Collection 3 : objectid Prof_name subjects_list UUID_list UUID-count subject_count 12 ABDC sub1,sub2,sub3 789…
tagged with: mongodb
has answer: http://stackoverflow.com/a/48499570
accepted answer: http://stackoverflow.com/a/48499570
tagged with: aggregation-framework
tagged with: python
tagged with: mongodb-query
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83983506
answer count: 1

http://stackoverflow.com/a/55130521
type: Answer
answers question: http://stackoverflow.com/q/48608845
score: 0
has body: I don't think you have thought this whole thing through. I have done some considerable lightweight thread apps with Greenlets created from the Gevent framework. As long as you allow control to switch between Greenlets with appropriate sleep's or switch's -- everything tends to work fine. Rather than blocking or waiting for a reply, it is recommended that the wait or block timeout, raise and except and then sleep (in except part of your code) and then loop again - otherwise you will not switch Greenlets readily. Also, take care to join and/or kill all Greenlets, since you could end up with zombies that cause copious effects that you do not want. However, I would not recommend this for your application. Rather, one of the following Websockets extensions that use Gevent... See this link Websockets in Flask and this link https://www.shanelynn.ie/asynchronous-updates-to-a-webpage-with-flask-and-socket-io/ I have implemented a very nice app with Flask-SocketIO https://flask-socketio.readthedocs.io/en/latest/ It runs through Gunicorn with Nginx very nicely from a Docker container. The SocketIO interfaces very nicely with Javascript on the client side. (Be careful on the webscraping - use something like Scrapy with the appropriate ethical scraping enabled)

http://stackoverflow.com/a/48491963
has comment: http://stackoverflow.com/comment/83977681
type: Answer
score: 1
has body: Here's an approach to the specific example of labeling each row with the index of the next available row that shows an increase of at least 5%. # Example data df = pd.DataFrame({'rate': [100, 105, 99, 110, 130, 120, 98]}) # Series.shift(n) moves elements n places forward = down. We use # it here in the denominator in order to compare each change with # the initial value, rather than the final value. mask = df.rate.diff()/df.rate.shift() &gt;= 0.05 df.loc[mask, 'next_big_change_idx'] = df[mask].index df.next_big_change_idx = df.next_big_change_idx.bfill().shift(-1) # output df rate next_big_change_idx 0 100 1.0 1 105 3.0 2 99 3.0 3 110 4.0 4 130 NaN 5 120 NaN 6 98 NaN
has comment: http://stackoverflow.com/comment/83978119
accepted answer of: http://stackoverflow.com/q/48491764
has comment: http://stackoverflow.com/comment/83978093
has comment: http://stackoverflow.com/comment/83978124
answers question: http://stackoverflow.com/q/48491764
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84007296
upvote count: 1
has comment: http://stackoverflow.com/comment/83979343
has comment: http://stackoverflow.com/comment/83977826
has comment: http://stackoverflow.com/comment/83977283
has comment: http://stackoverflow.com/comment/83977231
has comment: http://stackoverflow.com/comment/83977194

global
type: Tag
tags question: http://stackoverflow.com/q/48599690
tags question: http://stackoverflow.com/q/48527434
tag name: global
tags question: http://stackoverflow.com/q/48589189

http://stackoverflow.com/q/48539701
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84074723
has comment: http://stackoverflow.com/comment/84074583
linked to: http://stackoverflow.com/q/12309269
score: -3
has title: python from list of tuple create json
tagged with: python
has comment: http://stackoverflow.com/comment/84074576
has comment: http://stackoverflow.com/comment/84074535
has answer: http://stackoverflow.com/a/48590173
accepted answer: http://stackoverflow.com/a/48590173
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84075377
answer count: 3
has answer: http://stackoverflow.com/a/48541624
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
downvote count: 3
has body: I ask advice. I need to create a JSON object with the same keys. This is necessary to send a request to zabbix for host.create . https://www.zabbix.com/documentation/3.0/ru/manual/api/reference/host/create If you specify more than one group, it accepts only {"groupid": "2", "groupid": "8"} Does not understand: {"groupid": ["2","8"]} I suppose to use a structure. [("groupid","2"),("groupid","8")] I solved the problem in this way, but I do not understand how to convert to JSON, because the keys are not strings import json from json import JSONEncoder class SameKeys(JSONEncoder): def __init__(self, name): self.name = name def __repr__(self): return json.dumps(self.name) data = [("groupid", "2"), ("groupid", "8")] a = {SameKeys("groupid"): "2", SameKeys("groupid"): "8"} print(a) But I can not understand how to do it better so as not to make crutches, there may already be a ready solution, but having spent time I did not find anything suitable. Thank you for any advice
has comment: http://stackoverflow.com/comment/84075054
has answer: http://stackoverflow.com/a/48540642
possible better answer: http://stackoverflow.com/a/48540642
tagged with: zabbix
has comment: http://stackoverflow.com/comment/84074554
favorite count: 0
type: Question

http://stackoverflow.com/comment/84145904
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48572525
has text: Thanks @lenz. In this case, it's the data that I needed to encode. I use 'str' as that's what the h5py doc informs us to use for python3.
score: 0

http://stackoverflow.com/comment/84174662
type: AnswerComment
has text: So, I tried it for this array [ 12. 2. 3. 1. 22. 4. 5. 8. 10. 11.], where the first value 12 > 5* (the next value which is 2), also the fifth value 22 > 5*(the next value which is 4), so 12 and 22 should have been replaced by nan, I used mask = (x[1:-1] > 2*(x[2:])) and then x[1:-1][mask1] = np.nan, but it didn't work, 12 and 22 were not replaced.
type: Comment
comment on: http://stackoverflow.com/a/48574324
score: 0

http://stackoverflow.com/a/48584375
has comment: http://stackoverflow.com/comment/84165444
has comment: http://stackoverflow.com/comment/84183541
has comment: http://stackoverflow.com/comment/84165846
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48583950
has body: It looks like Transfermarkt is blocking requests from bots with the default User-Agent string sent by Python's urllib library, though it doesn't mention anything about that in its robots. This seems to imply they don't mind us scraping them, but they'd prefer we announce who we are. To do so with urllib, do the following: from urllib import request as u_r def strip_webite(): request = u_r.Request("https://www.transfermarkt.com/marco-reus/verletzungen/spieler/35207") request.add_header('User-Agent', 'my-cool-app') with u_r.urlopen(request) as f: pass if __name__ == "__main__": strip_webite()
answers question: http://stackoverflow.com/q/48583950
score: 2
type: Answer

http://stackoverflow.com/comment/83984293
score: 0
comment on: http://stackoverflow.com/q/48495584
type: QuestionComment
type: Comment
has text: Got it, thanks a lot.

http://stackoverflow.com/q/48638618
upvote count: 4
has answer: http://stackoverflow.com/a/48638734
has body: In [25]: datetime.fromtimestamp(15179052980380002/10000000) Out[25]: datetime.datetime(2018, 2, 6, 17, 21, 38, 38000) As you can see here, it convert to 38000us instead of 38002us (us = microsecond) How can I keep '2' of the right most digit?
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48639084
possible better answer: http://stackoverflow.com/a/48638734
score: 4
has comment: http://stackoverflow.com/comment/84274517
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Python datetime: how to keep whole `us(microsecond)`?
tagged with: datetime
accepted answer: http://stackoverflow.com/a/48639084
tagged with: python

http://stackoverflow.com/a/48597784
score: 1
downvote count: 0
has body: Put simply, there is no function overloading in Python in the sense of having two identically-named functions in the same scope. Each subsequent definition effectively replaces all identically-named definitions before it. This applies irrespectively of whether any of them are static.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48597763

http://stackoverflow.com/q/48550142
tagged with: non-linear-regression
has answer: http://stackoverflow.com/a/48552702
type: AnsweredQuestion
has title: Evolve dynamic system without an analytic expression for time derivative by solving for all the time-changing values at the same time
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48552702
type: Question
has body: I have a dynamic system where I have an expression for the residual of the time derivate but not an analytic expression for what the time derivative actually is: sum(da_i/dt) ** 2 = f(a). I can solve this by performing an optimization at every time step. I think I can recast this into a least squares problem and solve for every value at every time step in a single solve. I think this is a linear casting but I'm not 100% sure about that. How can I form this system of equations to efficiently solve for the values across all times in one solve? ''' my situation is that I know that this relationship is true: (\sum_{i=1}^n d a_i / dt) ** 2 = f(a). In this example, I assume a is 2 dimensional, f(a) = a1 **2 - a1 * a2, and I want to evolve the equation for 5 time steps. ''' def residual(dadt, current_a): return (np.sum(dadt) ** 2 - (current_a[0] **2 - np.sum(a) * current_a[0] * current_a[1])) ** 2 ''' My real problem is a little more complicated than this, but the basic elements are here. Now, my strategy is to attempt to form something like an Ax=b formulation. ''' ''' Here is an approach that works. I find a values that make the residual zero. This approach is a little time-consuming because I have to solve the least-squares problem after each time iteration. This is a little goofy because I use an optimization engine to solve the problem. I think it would be better to cast this as a least squares regression problem. ''' from scipy.optimize import minimize as mini n_time_steps = 300 a0 = np.ones(2) * .5 a = a0 dt = 1e-3 a0_record = [] for _ in range(n_time_steps): a0_record.append(a[0]) dadt = mini(residual, np.ones(a.size), args=(a,)).x a += dadt * dt # Let's plot the time history. Maybe that can help verify the new approach. import matplotlib.pyplot as plt plt.plot(a0_record) plt.savefig('a0baseline.pdf') plt.clf() ''' I want to cast this into a single least-squares problem. In this case, I think I should have 2 * 300 = 600 free variables. Since I only have 300 time st…
tagged with: python
tagged with: linear-algebra
tagged with: calculus

http://stackoverflow.com/comment/84145728
type: QuestionComment
has text: Please add the code and not an image of it.
comment on: http://stackoverflow.com/q/48574420
score: 3
type: Comment

http://stackoverflow.com/a/48687137
answers question: http://stackoverflow.com/q/48595683
has comment: http://stackoverflow.com/comment/112509751
score: 0
type: Answer
has body: First install the MySQL connector for python from the MySQL website and then import the mysql.connector module and initialize a variable to a mysql.connector.connect object and use cursors to modify and query data. Look at the documentation for more help. If you don't have problem with no networking capabilities and less concurrency use sqlite, it is better than MySQL in these cases.

http://stackoverflow.com/comment/84254044
type: Comment
has text: I want the original data as a string.
type: AnswerComment
comment on: http://stackoverflow.com/a/48607035
score: 0

http://stackoverflow.com/a/48557826
has comment: http://stackoverflow.com/comment/84174817
type: Answer
has body: Seems like the case statement could be effective... Here is a link to how it works. https://www.tutorialspoint.com/vba/vba_switch_statement.htm Cheers.
score: 0
answers question: http://stackoverflow.com/q/48556211

http://stackoverflow.com/a/48591957
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48591757
has body: I've tested this with a string such as "){{])" and it returns false correctly. However, it will error on "){" Why is this? Let's break down your code: 1.) s = "){", s has 2 elements, namely: element: ) { index: 0 1 2.) When you enumerate(s), the iteration runs twice: 3.) The first iteration, i == 0, you're testing against s[0] == ")". 4.) Your code have no condition to check for s[0] == ")" directly under the iteration, so nothing happens. 5.) The second iteration, i == 1, you're testing against s[1] == "{". 6.) Your code have a condition (if compare == '{':) to check for s[1] == "{". The if condition is now active. Now your code tries to execute the following: if s[i + 1] == '}': 7.) You're at the second (and last) iteration. The if statement tries to get s[i + 1] to test the condition. However s[1 + 1] which is s[2]. 8.) Recall the elements and index in your 's': element: ) { index: 0 1 ^ doesn't exist 9.) s[2] doesn't exist. Python flips out and yells at you for requesting an index out of range. Forget the index. I just couldn't understand why. Don't. You'll forever make the same mistake. Learn, understand, and overcome it. It's the only way to improve.
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84195433
accepted answer of: http://stackoverflow.com/q/48591757

http://stackoverflow.com/a/48617302
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48617196
has comment: http://stackoverflow.com/comment/84231673
has comment: http://stackoverflow.com/comment/84231532
has comment: http://stackoverflow.com/comment/84231784
has comment: http://stackoverflow.com/comment/84231296
score: 1
has body: Make the following change, month_groups = defaultdict(int) Then you can just do month_groups[month] += value Refer here regarding your error
has comment: http://stackoverflow.com/comment/84231402
has comment: http://stackoverflow.com/comment/84231873
accepted answer of: http://stackoverflow.com/q/48617196
type: AcceptedAnswer

http://stackoverflow.com/comment/99479275
comment on: http://stackoverflow.com/a/48506964
type: Comment
type: AnswerComment
has text: Ah, your hint on not using stateful for this kind of sliding window is very enlightening for me concerning current LSTM-experiments. Thank you for coming back to this old post :)
score: 1

http://stackoverflow.com/q/48526603
downvote count: 0
tagged with: cgi
favorite count: 0
type: Question
has body: I'm working with a local web application which executes, via AJAX, a Python script on the web-server. I tried to deploy the application on a remote server and since have been facing an AJAX statusText: "parsererror". I assume this is because it isn't receiving proper JSON as expected when the script fails. How could I make sure the script interruption returns JSON to the browser, so that I can understand the nature of the error? The AJAX call is the following: $.ajax({ async: true, type: "POST", url: "cgi-bin/myscript.py", contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15", data: JSON.stringify(run_details), dataType: "JSON" }) .done(function(data) { console.log(data) }) .fail(function(xhr) { console.log('Error in myscript (cf. Ajax error below).'); console.log('error',xhr); }); In working conditions, I return data to the client using the following approach, which works well on the local server: success_message = "Some text" result = {'message': success_message}; #Send JSON result back to Ajax print("This line allows the following to be received by browser \n") json.dump(result, sys.stdout) In case an error in the script occurs, I call this function to interrupt the script: def interruptScript(a_cursor, a_conn, error_message): # Close communication with the database a_cursor.close() a_conn.close() #Add error message to object result = {'message': error_message}; #Send JSON result back to Ajax print("This lines allows the following to be received by browser \n") json.dump(result, sys.stdout) sys.exit(1) Ideally, I'd like the error_message to be accessible in AJAX's "responseText" (which is now empty ""). So far, I tried including a string (i.e. sys.exit(error_message)) and a JSON string (i.e. sys.exit(json.dumps(result))) in sys.exit(), but debugging in PyDev I learned that TypeError: an integer is required (got type str), and that this might be a bug. For this reason, I finally added the integer 1, with hope that the json.dump content would be pass…
tagged with: ajax
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/38877777
score: 2
has title: Returning JSON to AJAX after using sys.exit()
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/48507359
favorite count: 0
has body: System: Mac OSX Im relatively new user of Python and currently exploring GIS. Trying to read a shape file with geopandas however I am getting: OSError: Could not find libspatialindex_c library file Using Python 3.7 normally, but since there are dependencies issues with geopandas on this, followed advice here to run on Python2. What i've done here is with mac terminal, created new environment with python2 and installed geopandas there and tried to read shape file. conda create -n mytest python=2.7 geopandas -c conda-forge source activate mytest import geopandas geopandas.read_file('Random_points_twitter.shp') id xcoord ycoord data_twitt 0 0 5.27735 50.25398 0 1 1 3.29896 51.32356 1 2 2 3.29896 51.32356 2 I am successfully able to read this in terminal. But in the browser, it returns me an error. What I've done was first install jupyter on my new env and got a notebook running on browser(code below) (mytest) conda install jupyter (mytest) jupyter-notebook On browser with the new notebook,tried to import and read the shape file (similar to what i did in terminal) but it gives me this error: # OSError Traceback (most recent call last) in () ----> 1 import geopandas /Users/rldy/anaconda/lib/python2.7/site-packages/geopandas/init.py in () ----> 1 from geopandas.geoseries import GeoSeries 2 from geopandas.geodataframe import GeoDataFrame 3 4 from geopandas.io.file import read_file 5 from geopandas.io.sql import read_postgis /Users/rldy/anaconda/lib/python2.7/site-packages/geopandas/geoseries.py in () 10 11 from geopandas.plotting import plot_series ---> 12 from geopandas.base import GeoPandasBase, _series_unary_op, _CoordinateIndexer 13 14 /Users/rldy/anaconda/lib/python2.7/site-packages/geopandas/base.py in () 12 13 try: ---> 14 from rtree.core import RTreeError 15 HAS_SINDEX = True 16 except ImportError: /Users/rldy/anaconda/lib/python2.7/site-packages/rtree/init.py in () ----> 1 from .index import Rtree 2 3 from .core import rt 4 5 version = '0.8.3' /Users/rldy/anaconda…
downvote count: 0
score: 1
tagged with: geopandas
has answer: http://stackoverflow.com/a/56607086
tagged with: libspatialindex
tagged with: macos
has comment: http://stackoverflow.com/comment/84009719
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/57948871
upvote count: 1
tagged with: fiona
type: UnansweredQuestion
has title: OSError: Could not find libspatialindex_c library file on Mac OSX
tagged with: python

http://stackoverflow.com/comment/84094165
has text: Updated to include models, getting the migration now...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48548878

http://stackoverflow.com/comment/84216921
type: QuestionComment
has text: Because square brackets mean a character group `[11-19]` here means a group with the characters `1` and `9`. For `[20-99]` it matches all digits `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8` and `9`.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48610288

http://stackoverflow.com/comment/84144284
comment on: http://stackoverflow.com/q/48569756
score: 0
type: Comment
has text: The actual notebook packages is now just called `notebook`, that is the package that has to be >= 5.0 The `ResizeTool` was deprecated and removed quite some time ago, it was not compatible with other features. I don't know why the `output_file` version would not work, I agree that is strange. Is there any browser JS console errors?
type: QuestionComment

http://stackoverflow.com/a/48496803
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83987876
has body: I believe you need: set_index for columns for later aggregating sum filter columns with Value in columns name and multiple by column factor aggregate sum by both levels of MultiIndex reset_index df = df.set_index(['Id','Day']) df = df.filter(like='Value').mul(df['factor'], axis=0).sum(level=[0,1]).reset_index() print (df) Id Day Value1 Value2 Value3 Value10 0 11 1 26 26 26 26 1 22 2 9 9 15 15 Similar solution for get all columns for multiple by difference with list: df = df.set_index(['Id','Day']) cols = df.columns.difference(['factor', 'Name']) df = df[cols].mul(df['factor'], axis=0).sum(level=[0,1]).reset_index() print (df) Id Day Value1 Value10 Value2 Value3 0 11 1 26 26 26 26 1 22 2 9 15 9 15
has comment: http://stackoverflow.com/comment/83986550
type: Answer
accepted answer of: http://stackoverflow.com/q/48496741
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48496741
has comment: http://stackoverflow.com/comment/83986529
downvote count: 0

http://stackoverflow.com/q/48601771
tagged with: pip
has comment: http://stackoverflow.com/comment/84201112
tagged with: python
tagged with: ubuntu
answer count: 0
has title: Installing cx_Freeze on Ubuntu returns error code 1
score: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/46609269
has comment: http://stackoverflow.com/comment/84200944
favorite count: 0
type: Question
tagged with: cx-freeze
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/46609269
type: UnansweredQuestion
has body: I am unable to install cx_Freeze on Ubuntu 16.04. So far I have tried: python3.6 -m pip install cx_Freeze Which returns an error: i686-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 -I/usr/include/python3.6m -c source/bases/Console.c -o build/temp.linux-i686-3.6/source/bases/Console.o creating build/lib.linux-i686-3.6/cx_Freeze/bases i686-linux-gnu-gcc -pthread build/temp.linux-i686- 3.6/source/bases/Console.o -L/usr/lib/python3.6/config-3.6m-i386-linux-gnu - lpython3.6m -o build/lib.linux-i686-3.6/cx_Freeze/bases/Console -Xlinker - export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions -lpthread -ldl -lutil -lm - lexpat -L/usr/lib -lz -lexpat -s /usr/bin/ld: cannot find -lz collect2: error: ld returned 1 exit status error: command 'i686-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-ornam5bd/cx- Freeze/setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-vq85qfab-record/install- record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-ornam5bd/cx-Freeze/ I tried adding the sudo prefix as well but it returned the same error. I also tried installing from the source but that was also a failure (resulting in an error). I have also read similar problems, none of which work for me: https://askubuntu.com/questions/929168/how-to-install-cx-freeze-5-0-2-for-python-3-5-2/929405#929405 https://askubuntu.com/questions/462794/how-to-conveniently-install-cx-freeze-for-python-3 https://ubuntuforums.org/showthread.php?t=1721444 How can I install cx_Freeze 5.1.1?

http://stackoverflow.com/a/48596945
accepted answer of: http://stackoverflow.com/q/48596882
type: AcceptedAnswer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/48596882
has body: Whenever you use function(), you call the function. If you want to reference the function without calling it, drop the parentheses. &gt;&gt;&gt; type(print('1')) 1 &lt;class 'NoneType'&gt; &gt;&gt;&gt; type(print) &lt;class 'builtin_function_or_method'&gt; When you use function as an argument to another function like so: type(print("1")), python first executes the innermost function, in this case print("1"), then passes the return value as argument to the outer function, it's the same as: result = print("1") type(result)
upvote count: 3
type: Answer

http://stackoverflow.com/q/48532134
has comment: http://stackoverflow.com/comment/84063138
answer count: 4
score: 8
favorite count: 0
type: Question
tagged with: python-import
has answer: http://stackoverflow.com/a/48532869
linked to: http://stackoverflow.com/q/3402168
has title: Python code runs from IDE, but not from terminal
upvote count: 8
has answer: http://stackoverflow.com/a/65996059
type: UnansweredQuestion
tagged with: pythonpath
tagged with: python
has comment: http://stackoverflow.com/comment/84060170
has answer: http://stackoverflow.com/a/65125779
linked to: http://stackoverflow.com/q/18247333
has answer: http://stackoverflow.com/a/48547472
linked to: http://stackoverflow.com/q/448271
has comment: http://stackoverflow.com/comment/84059998
downvote count: 0
has body: My imports don't work when I try to run the code from Linux terminal. Specifically, imports from other packages in the same project. I know this is a PYTHONPATH issue, but I don't know how to diagnose it further or solve it. The code runs fine inside the IDE (eclipse). I am interested in a permanent solution, guessing it will involve editing .bashrc. I simply want to invoke scripts from command line, like python my_script.py os.environ["PYTHONPATH"] gives a key error in ipython terminal. I tried print os.getcwd() print sys.path Inside IDE /home/myname/workspace/project2/main ['/home/myname/workspace/project2/main', '/home/myname/workspacep/problem2', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_6 4-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/p ython2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pytho n2.7/dist-packages/ubuntu-sso-client', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/lib-old'] Inside terminal /home/myname/workspace/project2/main ['/home/myname/workspace/project2/main', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']

http://stackoverflow.com/comment/84250950
has text: Can you try adding `sourceSize.width: 100; sourceSize.height: 100;` in the image? `Image` has this weird `sourceSize` property...
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48625790
type: Comment

http://stackoverflow.com/a/48585683
upvote count: 2
downvote count: 0
type: Answer
has body: You could extract the &lt;span&gt; element and then get the stripped text as follows: from bs4 import BeautifulSoup import requests html = requests.get('https://www.thedibb.co.uk/forums/wait_times.php?a=MK').content soup = BeautifulSoup(html, "html.parser") for attraction in soup.find_all('td', class_='alt2', align='right', height='28'): attraction.span.extract() print attraction.get_text(strip=True) Which would give you output starting: A Pirate's Adventure - Treasures of the Seven Seas Captain Jack Sparrow's Pirate Tutorial Jungle Cruise Meet Characters from Aladdin in Adventureland Pirates of the Caribbean Swiss Family Treehouse
answers question: http://stackoverflow.com/q/48585425
score: 2

http://stackoverflow.com/q/48575598
answer count: 1
has answer: http://stackoverflow.com/a/48575833
downvote count: 0
has title: How to robustly retrieve the bin path of a python environment?
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
tagged with: python
score: 2
has body: I already figured out how one can retrieve the include and site-package paths of a python environment. For instance the following is one of multiple possibilities: from distutils.sysconfig import get_python_lib, get_python_inc print(get_python_lib()) # Prints the location of site-packages print(get_python_inc()) # Prints the location of the include dir However, I was not able to find a robust method to retrieve the bin folder of a python environment, that is, the folder where python itself and tools like pip, pyinstaller, easy_install, etc., typically reside. Does anyone know how I can get this path from within python? Some may want to suggest binpath = os.path.dirname(sys.executable). On Mac however, this does not work if python was installed as a Framework (binpath would point at: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS) What could I use instead that works cross-platform?
type: AnsweredQuestion
tagged with: python-2.7
linked to: http://stackoverflow.com/q/122327
accepted answer: http://stackoverflow.com/a/48575833

http://stackoverflow.com/q/48616871
has body: I am trying to read the second column of an excel file using xlrd module. But the issue is the second column also has blank rows . I need to select only the values but not the rows . Below is my code for it: import xlrd import sys import re workbook_name = sys.argv[1] if workbook_name: book = xlrd.open_workbook(workbook_name) for sheet in book.sheet_names(): if re.search(r'Munich',sheet): sh = book.sheet_by_name(sheet) #num_cols = sh.ncols for row_ids in range(0,sh.nrows): cell_obj = str(sh.cell(row_ids,1)) blank_regex = re.compile(r'u\'\'') if not re.search(blank_regex,cell_obj): #re.sub('^.+u'()',\1,cell_obj) print(cell_obj) else: print ("Please supply workbook_name") When i get the output , this is what i get : text:u'Dom0' text:u'muclgd0008.dedc2.cloud.com' text:u'muclgd0007.dedc2.cloud.com' text:u'muclgd0006.dedc2.cloud.com' text:u'muclgd0005.dedc2.cloud.com' text:u'muclgd0004.dedc2.cloud.com' text:u'muclgd0003.dedc2.cloud.com' text:u'Dom0' text:u'muclmx0032.dedc2.cloud.com' text:u'muclmx0031.dedc2.cloud.com' text:u'muclmx0030.dedc2.cloud.com' text:u'muclmx0029.dedc2.cloud.com' text:u'muclmx0028.dedc2.cloud.com' text:u'muclmx0027.dedc2.cloud.com' text:u'muclmx0026.dedc2.cloud.com' text:u'muclmx0025.dedc2.cloud.com' text:u'muclgp0002.dedc2.cloud.com' text:u'muclgp0001.dedc2.cloud.com' text:u'Hardware Device' text:u'Exadata X2-2 Quater Rack' text:u'Exadata X2-2 Quater Rack' text:u'ZFS Filer' text:u'BDA' I am not sure why this strange text:u'' is coming at the beginning.These characters are not there in the excel sheet. Can someone please guide me on how to remove the same. Thanks in advance.
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84230498
accepted answer: http://stackoverflow.com/a/48617142
downvote count: 1
favorite count: 0
type: Question
tagged with: python
score: -1
tagged with: regex
has answer: http://stackoverflow.com/a/48617142
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84230507
has title: How to remove strange characters while using regex and xlrd module Python
tagged with: xlrd

http://stackoverflow.com/comment/84103424
score: 0
has text: You are right about the value. But the consequences of such observations are hard to evaluate for NP-hard problems (when is my method good, when is yours good; there surely is some merit for greedy in some scenarios). I warned about that. One obvious thing here: my code proves 1965 is the optimal solution as the method is sound and complete. Yours is not and in terms of approximation, yours is probably limited to a factor 2 (factor depends on the exact greedy-approach and there are very good greedy-like approximations much better; 2 is the naive one).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48553316

http://stackoverflow.com/comment/83977826
score: 0
has text: Wow - much better than mine. Unfortunately the 'next_big_change' surfaces on the it's own row as well. For example row4/index3 has a rate of 110 but references index3 (itself) as the next_big_change. I would want 99 and 105 to show this actually.
comment on: http://stackoverflow.com/a/48491963
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48572384
has comment: http://stackoverflow.com/comment/84141725
has comment: http://stackoverflow.com/comment/84141833
type: Answer
downvote count: 0
upvote count: 1
score: 1
has body: See Intra-package References in https://docs.python.org/3/tutorial/modules.html You can also write relative imports, with the from module import name form of import statement. These imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use: from . import echo from .. import formats from ..filters import equalizer i.e. I think you need to e.g. from .example import foo.
answers question: http://stackoverflow.com/q/48572316
has comment: http://stackoverflow.com/comment/84142125

http://stackoverflow.com/comment/84190370
score: 0
comment on: http://stackoverflow.com/q/48596726
has text: `[[3,4][4,4][4,5][4,6][5,3][5,4][5,5][5,6][6,4]]` => `TypeError`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83992533
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48498560
score: 0
has text: You asked about a problem in why your code is not working, so yes, code is 100% relevant here.. Your own answer pointed out what you fixed in your code.

http://stackoverflow.com/q/48496886
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
tagged with: http://stackoverflow.com/tag/json
has title: HostGator: Sent JSON data from Server using cgi python script
answer count: 1
tagged with: cgi
has body: I am trying to implement some script that deliver json data on client based on different client-requests. So far, I am able to deliver html data usin python script. For exmaple, this script works just fine: #!/usr/bin/env python3 print("Content-Type: text/html\n\n") # html markup follows print(""" <Title>Hello in HTML Hello There! Hi There! """) Now I wanted to test a python script which delivers json data: #!/usr/bin/env python3 import sys, json jsonData = {"success": "true"}) print('Content-Type: application/json\n\n') print (json.dumps(jsonData)) I have set right permissions to 755, but still I get as respons error 500. Same example in my localhost is working just fine. Also, If I connect to the server using ssh and execute the python script, it works and I get this outpot: Content-Type: application/json {"success": "true"} As much as I read, there are some issues with cross-origin, but I dont get correctly, how could something like this activated.
has answer: http://stackoverflow.com/a/48498877
favorite count: 0
type: Question
tagged with: server
tagged with: python
accepted answer: http://stackoverflow.com/a/48498877

http://stackoverflow.com/comment/84189305
type: QuestionComment
comment on: http://stackoverflow.com/q/48596094
score: 1
has text: Thank you for this answer, i.e. raw_input
type: Comment

http://stackoverflow.com/comment/84183680
score: 0
comment on: http://stackoverflow.com/q/48585027
has text: I actually cannot replicate your result that getting a empty df with `df19 = pd.merge(df_pw6,df_ex,on=['date','ID'])`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48594892
has comment: http://stackoverflow.com/comment/84267461
tagged with: linux
has body: If a python script is executed in Linux, it will go to RAM and will be executed from there. Once it has executed and completed its task. Will python script code be immediately removed from RAM or will it stay their until computer needs that RAM space for any other task? If someone runs a malicious python script and suppose RAM space is not required for any other task, then using RAM dump I want to get that python script. Its part of a research work, I only want answer to the question mentioned above.
duplicate of: http://stackoverflow.com/q/2975831
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84503366
linked to: http://stackoverflow.com/q/31015556
tagged with: python
has comment: http://stackoverflow.com/comment/84484740
has answer: http://stackoverflow.com/a/48618567
tagged with: security
has comment: http://stackoverflow.com/comment/84189411
has comment: http://stackoverflow.com/comment/84243633
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/84186791
answer count: 1
tagged with: computer-forensics
downvote count: 1
has comment: http://stackoverflow.com/comment/84240437
favorite count: 0
has title: Fetch python script from RAM dump
type: Question
tagged with: python-3.x

bayesian-networks
tag name: bayesian-networks
type: Tag
tags question: http://stackoverflow.com/q/48623439
tags question: http://stackoverflow.com/q/48558155
tags question: http://stackoverflow.com/q/48579079
tags question: http://stackoverflow.com/q/48494667

http://stackoverflow.com/comment/84021098
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48513031
has text: Please read `regex` documentation. It's all there.

http://stackoverflow.com/a/57729747
answers question: http://stackoverflow.com/q/48556340
score: 0
has body: I got the same error. It turned out that my CustomIndexDashboard had an ImportError. Hope this helps.
type: Answer

http://stackoverflow.com/a/48605152
score: 2
upvote count: 2
downvote count: 0
has body: You can try this. df = df.set_index('a') df.where(df &gt; 0).stack().reset_index().drop(0, axis=1) a level_1 0 red d 1 yellow c 2 blue b
answers question: http://stackoverflow.com/q/48605016
type: Answer

http://stackoverflow.com/q/48572965
type: AnsweredQuestion
tagged with: pandas
has title: Efficiently combine min/max on different columns of a pandas dataframe
answer count: 1
has comment: http://stackoverflow.com/comment/84172664
accepted answer: http://stackoverflow.com/a/48573211
score: 1
upvote count: 1
has body: I have a pandas dataframe that contains the results of computation and need to: take the maximum value of a column and for that value find the maximum value of another column take the minimum value of a column and for that value find the maximum value of another column Is there a more efficient way to do it? Setup metrictuple = namedtuple('metrics', 'prob m1 m2') l1 =[metrictuple(0.1, 0.4, 0.04),metrictuple(0.2, 0.4, 0.04),metrictuple(0.4, 0.4, 0.1),metrictuple(0.7, 0.2, 0.3),metrictuple(1.0, 0.1, 0.5)] df = pd.DataFrame(l1) # df # prob m1 m2 #0 0.1 0.4 0.04 #1 0.2 0.4 0.04 #2 0.4 0.4 0.10 #3 0.7 0.2 0.30 #4 1.0 0.1 0.50 tmp = df.loc[(df.m1.max() == df.m1), ['prob','m1']] res1 = tmp.loc[tmp.prob.max() == tmp.prob, :].to_records(index=False)[0] #(0.4, 0.4) tmp = df.loc[(df.m2.min() == df.m2), ['prob','m2']] res2 = tmp.loc[tmp.prob.max() == tmp.prob, :].to_records(index=False)[0] #(0.2, 0.04)
has answer: http://stackoverflow.com/a/48573211
favorite count: 0
has comment: http://stackoverflow.com/comment/84155399
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84172620
downvote count: 0
tagged with: python

http://stackoverflow.com/a/48507475
downvote count: 1
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/48507133
score: 8
has body: In os.path, there are helpful isdir() and isfile() functions: &gt;&gt;&gt; import os &gt;&gt;&gt; &gt;&gt;&gt; os.path.isfile('demo.py') True &gt;&gt;&gt; os.path.isdir('demo.py') False &gt;&gt;&gt; os.path.isfile('__pycache__') False &gt;&gt;&gt; os.path.isdir('__pycache__') Also, you can use os.walk() or os.scandir() to automatically separate the two: for root, dirs, files in os.walk('python/Lib/email'): print('Searching:', root) print('All directories', dirs) print('All files:', files) print('----------------------')

http://stackoverflow.com/q/48542355
type: Question
tagged with: tkinter
has body: When I run the code the box appears in the top left, with most out of the view of the screen. I have gone over the code and cannot find what it causing this. Thanks for any help. from tkinter import * import sqlite3 import LoginMenu class LogOn: def __init__(self, window): self.window = window window.title("Log On") window.state("zoomed") h = self.window.winfo_height() w = self.window.winfo_width() Center_h = h/2 Center_w = w/2 self.FrameLogOn = Frame(window, bg = "PaleTurquoise1") self.FrameLogOn.place(x = Center_w , y = Center_h, anchor = "center") self.lbl_TrainerID = Label(self.FrameLogOn, text = "TrainerID:", bg = "PaleTurquoise1", font =("Arial","16"), width = 15) self.lbl_TrainerID.grid(row = 0, column = 0) self.ent_TrainerID = Entry(self.FrameLogOn, bg = "PaleTurquoise1", font =("Arial","16")) self.ent_TrainerID.grid(row = 0, column = 1) self.lbl_TrainerIDError = Label(self.FrameLogOn, text = "*TrainerID Not Found" ,bg = "PaleTurquoise1", font =("Arial","16"), fg = "PaleTurquoise1", width = 15) self.lbl_TrainerIDError.grid(row = 0, column = 2) self.lbl_Password = Label(self.FrameLogOn, text = "Password:" ,bg = "PaleTurquoise1", font =("Arial","16"), width = 15) self.lbl_Password.grid(row = 1, column = 0) self.ent_Password = Entry(self.FrameLogOn, bg = "PaleTurquoise1", font =("Arial","16")) self.ent_Password.grid(row = 1, column = 1) self.lbl_PasswordError = Label(self.FrameLogOn, text = "*Incorrect Password" ,bg = "PaleTurquoise1", font =("Arial","16"), fg = "PaleTurquoise1", width = 15) self.lbl_PasswordError.grid(row = 1, column = 2) self.btn_LogIn = Button(self.FrameLogOn, text = "Log In", bg = "PaleTurquoise1", font =("Arial", "16"), width = 15, command = self.LogIn) self.btn_LogIn.grid(row = 2, column = 0, columnspan = 3)
accepted answer: http://stackoverflow.com/a/48542852
upvote count: 0
possible better answer: http://stackoverflow.com/a/48542672
tagged with: user-interface
has answer: http://stackoverflow.com/a/48544198
has answer: http://stackoverflow.com/a/48542852
has answer: http://stackoverflow.com/a/48542672
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84102827
answer count: 3
tagged with: python
score: -1
has title: Tkinter Screen Not Centered
has comment: http://stackoverflow.com/comment/84080188
favorite count: 0

http://stackoverflow.com/q/48600413
tagged with: python
tagged with: shell
has answer: http://stackoverflow.com/a/48600435
accepted answer: http://stackoverflow.com/a/48600435
type: AnsweredQuestion
downvote count: 0
has body: I have started Django in about a month ago and I am having problem in it. I had created a model which is one to one linked with User model This is my models.py file: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) options = (('individual','Individual'), ('institute',"An institute"), ) userAs = models.CharField(max_length=100,choices=options) def __str__(self): return self.user.username class Meta: ordering = ["user"] @receiver(post_save,sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserInfo.objects.create(user=instance) ...and I want to change value of userAs from shell and I am unable to do it. This is what I tried: In [10]: us = User.objects.get(username="foo") In [11]: us.userinfo.userAs Out[11]: 'individual' In [12]: type(us.userinfo.userAs) Out[12]: str In [13]: us.userinfo.userAs = 'institute' In [14]: us.save() In [15]: us.userinfo.userAs Out[15]: 'institute' In [16]: us = User.objects.get(username="steve04") In [17]: us.userinfo.userAs Out[17]: 'individual' ...but I am unable to change it.
upvote count: 1
answer count: 1
tagged with: django
favorite count: 0
type: Question
has title: How to change value of choice field in Django shell?
score: 1

http://stackoverflow.com/a/48559830
type: Answer
accepted answer of: http://stackoverflow.com/q/48557893
has body: I would say that aiohttp evolves much faster than Python itself: we make several aiohttp releases per year while Python is released every year and half. That's why aiohttp will never be a part of Python standard library. Note, the same situation is for requests and other HTTP frameworks like Django.
answers question: http://stackoverflow.com/q/48557893
score: 2
type: AcceptedAnswer
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/48538663
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/json
has body: I have CSV file (data.csv) which contains a column with its parent id. Based on this file, I would like to create one or many json files which contain the root and all its children. An example for a CSV file with one root only: BrandID,Name,ParentBrandID 1,Brand, 2,Normal Brand,1 3,Bad Brand,1 4,Best Brand,1 5,Cleaner,4 6,Fat Remover,4 7,Others,1 8,Kitchen,7 And I need to convert that file to a json format that looks like this: { "name":"Brand", "children":[ { "name":"Normal Brand" }, { "name":"Bad Brand" }, { "name":"Best Brand", "children":[ { "name":"Cleaner" }, { "name":"Fat Remover" } ] }, { "name":"Others", "children":[ { "name":"Kitchen" } ] } ] } Is there an straight forward way to do this? If it helps for anything, I need this to use as an entry for d3 libraries. Thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/84072450
type: Question
has title: Convert CSV with a parent column to a herarchical json /s in python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84072472
has comment: http://stackoverflow.com/comment/84097575
tagged with: d3.js
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19697846

http://stackoverflow.com/comment/84033594
type: AnswerComment
has text: yes but why if i change: tree.write('Matching_Result.xml',encoding='utf-8') by : with open("Matching_Result.xml", "w") as f: f.write(xmlstr.encode('utf-8')) by i will have not any change !!
type: Comment
comment on: http://stackoverflow.com/a/48519221
score: 0

http://stackoverflow.com/comment/84141429
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48572081
has text: All those underscores are hurting my eyes!

http://stackoverflow.com/a/48515962
has comment: http://stackoverflow.com/comment/84026246
answers question: http://stackoverflow.com/q/48515893
has comment: http://stackoverflow.com/comment/84026570
has comment: http://stackoverflow.com/comment/84046282
has comment: http://stackoverflow.com/comment/84026189
type: Answer
has comment: http://stackoverflow.com/comment/84027090
has body: Try this: console=Hostdata(hw_id = i[0],location_id = i[1],consoleip = i[2],biosversion = i[3]) You are trying to assign the value to the value that the variable holds instead of the value to the variable. Basically, the &lt;> is console.
score: 0
has comment: http://stackoverflow.com/comment/84027305

http://stackoverflow.com/comment/84232888
type: Comment
type: QuestionComment
has text: Escape them. Yes, again. (Usually. But Python also has `raw` strings – see the official documentation.)
comment on: http://stackoverflow.com/q/48618218
score: 0

http://stackoverflow.com/q/48570596
tagged with: pandas
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/48573957
has comment: http://stackoverflow.com/comment/84137915
type: Question
has title: Why are the pandas plots so different for very similar dataframes?
has comment: http://stackoverflow.com/comment/84142916
has body: The following code snippet with partial display from print executes with no problem: import pandas as pd from matplotlib import pyplot as plt import numpy as np import csv ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) df = pd.DataFrame(np.random.randn(1000, 3), index=ts.index, columns=list('ABC')) print (df) print (df.index) print (df.columns) #df = df.cumsum() # this also is ok df.plot() plt.show() A B C 2000-01-01 0.882544 -0.841398 1.745238 2000-01-02 1.798310 1.049662 -0.115292 2000-01-03 1.223243 -0.086322 -0.565204 2000-01-04 -0.587905 -0.609485 0.296248 2000-01-05 -1.603916 -0.397210 0.007550 2000-01-06 -0.821833 0.112760 -0.082558 ... ... 2002-09-22 -0.530537 0.373358 2.920919 2002-09-23 0.121657 0.634864 -0.964255 2002-09-24 1.153799 2.468507 -2.087136 2002-09-25 -1.079853 0.684926 1.556522 2002-09-26 -2.163454 0.874373 1.942925 [1000 rows x 3 columns] DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08', '2000-01-09', '2000-01-10', ... ... '2002-09-17', '2002-09-18', '2002-09-19', '2002-09-20', '2002-09-21', '2002-09-22', '2002-09-23', '2002-09-24', '2002-09-25', '2002-09-26'], dtype='datetime64[ns]', length=1000, freq='D') Index(['A', 'B', 'C'], dtype='object') and produces a nice plot (as expected) However, when I execute the following code import datetime df = pd.read_csv(fullFileNameOutCSV, header=0, names=headerCSV,usecols=['SEK/EUR', 'SEK/DKK', 'SEK/NOK']) pd.Timedelta(datetime.timedelta(days=1)) df.index = pd.date_range('2000-01-01',periods=4888) df.index = pd.to_datetime(df.index) print (df) print (df.index) print (df.columns) df.plot() plt.show() SEK/EUR SEK/DKK SEK/NOK 2000-01-01 9.4696 7.4501 8.8550 2000-01-02 9.4025 7.4495 8.7745 2000-01-03 9.3050 7.4452 8.7335 2000-01-04 9.1800 7.4431 8.6295 2000-01-05 9.1650 7.4433 8.5900 2000-01-06 9.0985 7.4433 8.5585 ... ... 2013-05-14 9.8188 7.4444 9.5858 2013-05-15 9.8005 7.4428 9.5655 2013-05-…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48590409
has comment: http://stackoverflow.com/comment/84138099
has answer: http://stackoverflow.com/a/48574218
has comment: http://stackoverflow.com/comment/84138011
has comment: http://stackoverflow.com/comment/84142250
tagged with: plot
score: 0
answer count: 3

http://stackoverflow.com/q/48490280
tagged with: python
has title: Keras custom loss not calculated correctly
has body: I'm trying to use a custom loss function in Keras. My implementation looks something like: class LossFunction: ... def loss(self, y_true, y_pred): ... localization_loss = self._localization_loss() confidence_loss = self._object_confidence_loss() category_loss = self._category_loss() self.loc_loss = localization_loss self.obj_conf_loss = confidence_loss self.category_loss = category_loss tot_loss = localization_loss + confidence_loss + category_loss self.tot_loss = tot_loss return tot_loss I then define custom metrics to look at the stored tensors like: class MetricContainer: def __init__(self, loss_obj): self.loss = loss_obj def local_loss(self, y_true, y_pred): return self.loss.loc_loss def confidence_loss(self, y_true, y_pred): return self.loss.obj_conf_loss def category_loss(self, y_true, y_pred): return self.loss.category_loss def tot_loss(self, y_true, y_pred): return self.loss.tot_loss I then compile my model with this command: model.compile('adam', loss=loss_obj.loss, metrics=[metric_container.local_loss, metric_container.confidence_loss, metric_container.category_loss, metric_container.tot_loss]) When I train the model (on a very small training set) I get output like: Epoch 1/2 1/2 [==============&gt;...............] - ETA: 76s - loss: 482.6910 - category_loss: 28.1100 - confidence_loss: 439.9192 - local_loss: 13.1180 - tot_loss: 481.1472 2/2 [==============================] - 96s - loss: 324.6292 - category_loss: 18.1967 - confidence_loss: 296.0593 - local_loss: 8.8204 - tot_loss: 323.0764 - val_loss: 408.1170 - val_category_loss: 0.0000e+00 - val_confidence_loss: 400.0000 - val_local_loss: 6.5036 - val_tot_loss: 406.5036 For some reason tot_loss and loss don't match, even though I should be using the same value for them. Any idea why this might be happening? Does Keras do something to modify the loss after you return it?
has answer: http://stackoverflow.com/a/48490510
type: AnsweredQuestion
score: 3
tagged with: deep-learning
upvote count: 3
downvote count: 0
answer count: 1
tagged with: keras
accepted answer: http://stackoverflow.com/a/48490510
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: machine-learning

http://stackoverflow.com/comment/111488471
score: 0
has text: Works for me but one small correction or clarification. in filter_user_posts . the line should be username=graphene.String(). String is a class
type: Comment
comment on: http://stackoverflow.com/a/49830535
type: AnswerComment

http://stackoverflow.com/comment/84064555
type: QuestionComment
has text: If you have the analytic solution, what exactly is tripping you up?
comment on: http://stackoverflow.com/q/48529905
type: Comment
score: 0

http://stackoverflow.com/q/48542737
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/71663372
has title: Python Selenium element is not reachable by keyboard
tagged with: selenium
has answer: http://stackoverflow.com/a/48599044
has body: acc = self.wait.until(EC.visibility_of_element_located((By.XPATH,"//tr[@valign='top']/td[2]/input[@id='account']"))) acc.send_keys(user['userid']) time.sleep(1) pwd = self.wait.until(EC.visibility_of_element_located((By.XPATH, "//tr[@valign='bottom']/td/input[@id='passwordInput1']"))) pwd.send_keys(user['pwd']) I tried to login to a website and i can successfully input the account name--that is "acc" in the codes, but when it came the pwd, it will display an error message. And i tested that the pwd element can be fine, only the send_keys line went wrong. selenium.common.exceptions.ElementNotInteractableException: Message: Element &lt;input id="passwordInput1" class="inputField1" name="passwordInput1" type="text"&gt; is not reachable by keyboard It occurred in geckodriver and chromedrive, but was okay with phantomjs. Anyone knows what's happening?
favorite count: 0

http://stackoverflow.com/a/48578676
answers question: http://stackoverflow.com/q/48578627
has body: Most of the instance attributes that you define or the parent class (or object) does are going to behave the same and be for the most part indistinguishable. If you really want to distinguish them for whatever reason, you should yourself create a way to identify them, perhaps by using a dictionary instead. class A: def __init__(self): self.my_variables = {'a': 1} # Or maintain a list with their names, it seems ugly however self.my_variables = ['a'] With that said, I am not at all clear about why you want to do this. Maybe you should try looking for a simpler solution to the problem than overriding __setattr__. Update: It seems to me that you're trying to restrict updation of variables, perhaps in your attempt to create "real private variables". In my advice, don't. There's a reason that Python allows you to do a lot of things that might seem insane from point of view of Static languages. You should just start your variables with _ to mark them as private similar to what Python recommends. If people are going to access them anyway, then what's stopping them from finding a workaround to circumvent the "restrictions" that you're trying to enforce? Besides, sometimes there is a genuine justification for accessing private variables.
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/48604689
score: 5
answers question: http://stackoverflow.com/q/48604662
type: AcceptedAnswer
upvote count: 5
has body: There are a few things that you need to change but this works: class Stuff: def __init__(self, name): self.name = name def get_name(self): print(self.name) new_name = Stuff(name = "Richard") new_name.get_name() Besides a few syntax errors (class needs to be lowercase and some missing :) the main thing you were missing was accessing name by means of the self identifier. Since name is defined on the class you need to access it via self.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84206113
has comment: http://stackoverflow.com/comment/84205961
accepted answer of: http://stackoverflow.com/q/48604662
has comment: http://stackoverflow.com/comment/84206008
has comment: http://stackoverflow.com/comment/84205990

http://stackoverflow.com/comment/84172713
score: 0
type: Comment
type: QuestionComment
has text: Sorry, no, not easily, otherwise I would've done that already. (Zeppelin creates the `SparkSession` variable for you, and calls it `spark`. I'm not using `SQLContext`.) I'm just wondering if anyone else has seen behaviour like this in Spark and what they did to fix it. I believe I've already ruled out nested RDDs or sending `spark` to the executor nodes.
comment on: http://stackoverflow.com/q/48582698

http://stackoverflow.com/comment/84174633
has text: Thanks :) True, I assigned `plt.ylim` wrong with `plt.ylim=((0.95))` prior to trying the correct syntax and I forgot about it.
comment on: http://stackoverflow.com/a/48588695
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84212424
type: Comment
comment on: http://stackoverflow.com/a/48605638
has text: Perhaps simply `df.set_index('a').dot(df.columns[1:]).to_dict()`
type: AnswerComment
score: 1

http://stackoverflow.com/comment/84216862
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48610188
score: 0
has text: The question that ayhan gave as a duplicate is exactly your problem and shows how to solve it directly. The one I linked provides a better solution without using the `or` operator.

http://stackoverflow.com/q/48524459
type: AnsweredQuestion
has title: python enum.Enum _value_ vs value
answer count: 2
score: 5
accepted answer: http://stackoverflow.com/a/48537071
downvote count: 0
has body: from enum import Enum class Type(Enum): a = 1 b = 2 print Type.a.value, Type.a._value_ This prints 1 1 What is the difference between _ value_ and value?
favorite count: 0
type: Question
tagged with: enums
possible better answer: http://stackoverflow.com/a/48524795
upvote count: 5
has answer: http://stackoverflow.com/a/48524795
tagged with: python
has answer: http://stackoverflow.com/a/48537071

http://stackoverflow.com/a/48602842
type: Answer
has comment: http://stackoverflow.com/comment/84202499
score: 3
has comment: http://stackoverflow.com/comment/84202621
upvote count: 3
downvote count: 0
has body: Use pandas.DataFrame.apply df['cars_mentioned'] = df['twitts'].apply(lambda x: [c for c in list_of_car_makers if c in x])
answers question: http://stackoverflow.com/q/48602779
has comment: http://stackoverflow.com/comment/84202672

http://stackoverflow.com/q/48640935
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48641401
has comment: http://stackoverflow.com/comment/84279081
has title: OSError: [Errno 19] Failed to open the uinput device: No such device
tagged with: raspbian
score: 2
tagged with: linux
has comment: http://stackoverflow.com/comment/84279108
answer count: 1
tagged with: uinput
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
has body: I am pretty new to raspberry and Linux. I am trying to run basic example of python library uinput on Raspbian (r Pi 3 B) with following code: import uinput device = uinput.Device([ uinput.BTN_LEFT, uinput.BTN_RIGHT, uinput.REL_X, uinput.REL_Y, ]) for i in range(20): device.emit(uinput.REL_X, 5) device.emit(uinput.REL_Y, 5) I get the error: Traceback (most recent call last): File "/home/pi/Desktop/t1.py", line 7, in uinput.REL_Y, File "/home/pi/.local/lib/python3.5/site-packages/uinput/init.py", line 178, in init self.uinput_fd = fd or fdopen() File "/home/pi/.local/lib/python3.5/site-packages/uinput/__init.py", line 84, in fdopen return _libsuinput.suinput_open() File "/home/pi/.local/lib/python3.5/site-packages/uinput/init.py", line 70, in _open_error_handler raise OSError(code, msg) OSError: [Errno 19] Failed to open the uinput device: No such device What is wrong? What do I need to change and where?
tagged with: python
has answer: http://stackoverflow.com/a/48641401

regression
tags question: http://stackoverflow.com/q/48607884
tags question: http://stackoverflow.com/q/48612519
tag name: regression
tags question: http://stackoverflow.com/q/48598122
tags question: http://stackoverflow.com/q/48612869
type: Tag
tags question: http://stackoverflow.com/q/48624071
tags question: http://stackoverflow.com/q/48530785

http://stackoverflow.com/q/48491566
accepted answer: http://stackoverflow.com/a/48491729
has answer: http://stackoverflow.com/a/56326816
has title: name 'DataFrameSelector' is not defined
has answer: http://stackoverflow.com/a/49852214
linked to: http://stackoverflow.com/q/46162855
score: 14
has answer: http://stackoverflow.com/a/48491729
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69995561
upvote count: 18
has answer: http://stackoverflow.com/a/57078456
has body: I am currently reading the "Hands-On Machine Learning with Scikit-Learn &amp; TensorFlow". I get an error when I am trying to recreate the Transformation Pipelines code. How can I fix this? Code: from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler num_pipeline = Pipeline([('imputer', Imputer(strategy = "median")), ('attribs_adder', CombinedAttributesAdder()), ('std_scaler', StandardScaler()), ]) housing_num_tr = num_pipeline.fit_transform(housing_num) from sklearn.pipeline import FeatureUnion num_attribs = list(housing_num) cat_attribs = ["ocean_proximity"] num_pipeline = Pipeline([ ('selector', DataFrameSelector(num_attribs)), ('imputer', Imputer(strategy = "median")), ('attribs_adder', CombinedAttributesAdder()), ('std_scaler', StandardScaler()), ]) cat_pipeline = Pipeline([('selector', DataFrameSelector(cat_attribs)), ('label_binarizer', LabelBinarizer()), ]) full_pipeline = FeatureUnion(transformer_list = [("num_pipeline", num_pipeline), ("cat_pipeline", cat_pipeline), ]) # And we can now run the whole pipeline simply: housing_prepared = full_pipeline.fit_transform(housing) housing_prepared Error: --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-350-3a4a39e5bc1c&gt; in &lt;module&gt;() 43 44 num_pipeline = Pipeline([ ---&gt; 45 ('selector', DataFrameSelector(num_attribs)), 46 ('imputer', Imputer(strategy = "median")), 47 ('attribs_adder', CombinedAttributesAdder()), NameError: name 'DataFrameSelector' is not defined
favorite count: 0
type: Question
tagged with: pipeline
downvote count: 4
has answer: http://stackoverflow.com/a/68737495
possible better answer: http://stackoverflow.com/a/49852214
tagged with: scikit-learn
tagged with: python
answer count: 6

http://stackoverflow.com/comment/84214606
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48609096
has text: Use `max(mylist, key=int)` if you want your code to work, but ideally you should use a list of ints to begin with
score: 2

http://stackoverflow.com/a/48609345
has body: You can utilize the max function with key parameter: input_dict = {'A': 1963, 'B': 1963, 'C': 1964, 'D': 1964, 'E': 1964, 'F': 1965, 'G': 1965, 'H': 1966, 'I': 1967, 'J': 1967, 'K': 1968, 'L': 1969 ,'M': 1969, 'N': 1970} max_recurrence = max(input_dict.values(), key=lambda x:input_dict.values().count(x)) Output: 1964
upvote count: 0
answers question: http://stackoverflow.com/q/48606406
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/comment/84129510
score: 0
comment on: http://stackoverflow.com/q/48562960
type: Comment
type: QuestionComment
has text: Thank you so much, this works. While similar questions had been asked before, I had not seen an answer with 'transform' in it. That got it going. Thanks again.

http://stackoverflow.com/q/48589644
has body: I have a time critical component in my database and I am trying to make the retrieval of this information as fast as possible. My question is how to best implement it. I am using Flask-SQLalchemy and I have a helper table for a many-to-many relationship. I though I should index this table, but I thought since primary keys are always indexed I could just add a primary key like this category_selection = db.Table( 'category_selection', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('category_id', db.String(1000), db.ForeignKey('SocArxivCategory.id')), # The combination of the two foreign keys should be unique, since no user can # follow the same category twice. db.PrimaryKeyConstraint('user_id', 'category_id') ) However, I never access this table through this primary key, so does this make any sense? So when should I use index=True and when does it make sense to add a primary key to such a helper table? My underlying database is Postgresql and the helper table above is used as selection = db.relationship('Category', secondary=category_selection, lazy='dynamic')
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84177943
tagged with: python
tagged with: postgresql
has comment: http://stackoverflow.com/comment/84176777
has title: Optimal performance for many-to-many relationship table in sqlalchemy
has comment: http://stackoverflow.com/comment/84176533
score: 0
answer count: 0

http://stackoverflow.com/comment/84133175
type: Comment
type: QuestionComment
has text: @Jesperrekuh, if one of the below responses answer your question, feel free to accept (tick on left) so other users know it's been tested.
score: 0
comment on: http://stackoverflow.com/q/48567308

http://stackoverflow.com/a/48620450
answers question: http://stackoverflow.com/q/48616694
type: Answer
score: 0
has body: I guess my answer is similar to some others here, but this was what I fiddled together in parallel from itertools import combinations, product """ with help from https://stackoverflow.com/questions/374626/how-can-i-find-all-the-subsets-of-a-set-with-exactly-n-elements https://stackoverflow.com/questions/32438350/python-merging-two-lists-with-all-possible-permutations https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ def sub_without( S, m, forbidden ): out = [] allowed = [ s for s in S if s not in forbidden ] N = len( allowed ) for k in range( len( forbidden ) ): addon = [ list( x ) for x in combinations( forbidden, k) ] if N + k &gt;= m: base = [ list( x ) for x in combinations( allowed, m - k ) ] leveltotal = [ [ item for sublist in x for item in sublist ] for x in product( base, addon ) ] out += leveltotal return out val = sub_without( range(6), 4, [ 1, 3, 5 ] ) for x in val: print sorted(x) &gt;&gt; [0, 1, 2, 4] [0, 2, 3, 4] [0, 2, 4, 5] [0, 1, 2, 3] [0, 1, 2, 5] [0, 2, 3, 5] [0, 1, 3, 4] [0, 1, 4, 5] [0, 3, 4, 5] [1, 2, 3, 4] [1, 2, 4, 5] [2, 3, 4, 5]

http://stackoverflow.com/comment/84008369
score: 0
comment on: http://stackoverflow.com/a/48506837
has text: The string also needs a placeholder for `Time_zone`. Also, I think the number of placeholders does not match the number of values in the tuple.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84086867
type: QuestionComment
comment on: http://stackoverflow.com/q/48545255
score: 0
type: Comment
has text: My code works fine if built with /MDd.

http://stackoverflow.com/q/48536461
score: 4
has comment: http://stackoverflow.com/comment/84069704
has body: I am trying to split a large docx file into small files. For that when reading a file in python3.6 with the following code. with open('h.docx', 'r') as f: a = f.read() It throws this error. Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "/usr/local/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xea in position 10: invalid continuation byte h.docx is created using LibreOffice Calc with just 'hello world' in it as content. I can read this successfully in Python 2.7 without any errors. I tried with open('h.docx', 'r', encoding='latin-1') as f: a = f.read() In this I can read the file without any errors. But when written to another file, the original contents are lost. Also tried errors='surrogateescape', but when written to another file the original contents are lost.
has comment: http://stackoverflow.com/comment/84068195
tagged with: file
tagged with: utf-8
has comment: http://stackoverflow.com/comment/84067965
favorite count: 0
type: Question
upvote count: 4
tagged with: decode
has title: Python3 - Cannot read docx, odt file - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xea in position 10: invalid continuation byte
tagged with: encoding
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48538622
tagged with: python

http://stackoverflow.com/a/48624202
answers question: http://stackoverflow.com/q/48620803
score: 4
has comment: http://stackoverflow.com/comment/84245007
has comment: http://stackoverflow.com/comment/84248515
has comment: http://stackoverflow.com/comment/84248525
accepted answer of: http://stackoverflow.com/q/48620803
has comment: http://stackoverflow.com/comment/84245369
has comment: http://stackoverflow.com/comment/84245145
has comment: http://stackoverflow.com/comment/84245196
has comment: http://stackoverflow.com/comment/84245126
type: AcceptedAnswer
downvote count: 0
has body: I found a much nicer solution to the problem which uses the polygons defined by the coastlines in the map to produce a matplotlib.PathPatch that overlays the ocean areas. This solution has a much better resolution and is much faster: from matplotlib import pyplot as plt from mpl_toolkits import basemap as bm from matplotlib import colors import numpy as np import numpy.ma as ma from matplotlib.patches import Path, PathPatch fig, ax = plt.subplots() lon_0 = 319 lat_0 = 72 ##some fake data lons = np.linspace(lon_0-60,lon_0+60,10) lats = np.linspace(lat_0-15,lat_0+15,5) lon, lat = np.meshgrid(lons,lats) TOPO = np.sin(np.pi*lon/180)*np.exp(lat/90) m = bm.Basemap(resolution='i',projection='laea', width=1500000, height=2900000, lat_ts=60, lat_0=lat_0, lon_0=lon_0, ax = ax) m.drawcoastlines(linewidth=0.5) x,y = m(lon,lat) pcol = ax.pcolormesh(x,y,TOPO) ##getting the limits of the map: x0,x1 = ax.get_xlim() y0,y1 = ax.get_ylim() map_edges = np.array([[x0,y0],[x1,y0],[x1,y1],[x0,y1]]) ##getting all polygons used to draw the coastlines of the map polys = [p.boundary for p in m.landpolygons] ##combining with map edges polys = [map_edges]+polys[:] ##creating a PathPatch codes = [ [Path.MOVETO] + [Path.LINETO for p in p[1:]] for p in polys ] polys_lin = [v for p in polys for v in p] codes_lin = [c for cs in codes for c in cs] path = Path(polys_lin, codes_lin) patch = PathPatch(path,facecolor='white', lw=0) ##masking the data: ax.add_patch(patch) plt.show() The output looks like this: Original solution: You can use an array with greater resolution in basemap.maskoceans, such that the resolution fits the continent outlines. Afterwards, you can just invert the mask and plot the masked array on top of your data. Somehow I only got basemap.maskoceans to work when I used the full range of the map (e.g. longitudes from -180 to 180 and latitudes from -90 to 90). Given that one needs quite a high resolution to make it look nice, the computation takes a while: from matplotlib import pyplo…
has comment: http://stackoverflow.com/comment/84245238
has comment: http://stackoverflow.com/comment/84248678
upvote count: 4
has comment: http://stackoverflow.com/comment/84248615
has comment: http://stackoverflow.com/comment/84245569
has comment: http://stackoverflow.com/comment/84249867
has comment: http://stackoverflow.com/comment/84245057
has comment: http://stackoverflow.com/comment/84246762
type: Answer

http://stackoverflow.com/comment/84226024
type: QuestionComment
comment on: http://stackoverflow.com/q/48614440
has text: When you ask about an error, you should indicate where the error occurred. Sometimes it helps to see some or all of the traceback. But I'm guessing that you are trying to do some sort of math, maybe interpolation, that does work with dates. `np.datetime64` is an array dtype that handles date-times. It uses 64 bits, but I think that's an integer value, not a float.
score: 1
type: Comment

http://stackoverflow.com/a/54633621
answers question: http://stackoverflow.com/q/48572951
score: 0
type: Answer
has body: Try the following: def printDF(inputDF): newDF = inputDF.toPandas() from IPython.display import display, HTML return HTML(newDF.to_html()) You can also move the import statement so that it is imported globally, instead of importing it each time the function is called. Hope this helps.

keras
tags question: http://stackoverflow.com/q/48518434
tags question: http://stackoverflow.com/q/48556767
tags question: http://stackoverflow.com/q/48562099
tags question: http://stackoverflow.com/q/48590858
tags question: http://stackoverflow.com/q/48618525
tags question: http://stackoverflow.com/q/48621833
tags question: http://stackoverflow.com/q/48617771
tags question: http://stackoverflow.com/q/48559103
tags question: http://stackoverflow.com/q/48552002
tags question: http://stackoverflow.com/q/48547931
tags question: http://stackoverflow.com/q/48587696
tags question: http://stackoverflow.com/q/48505674
tags question: http://stackoverflow.com/q/48561909
tags question: http://stackoverflow.com/q/48610981
tags question: http://stackoverflow.com/q/48558085
tags question: http://stackoverflow.com/q/48624974
tags question: http://stackoverflow.com/q/48557250
tags question: http://stackoverflow.com/q/48539256
tags question: http://stackoverflow.com/q/48542473
tags question: http://stackoverflow.com/q/48568062
tags question: http://stackoverflow.com/q/48507679
tags question: http://stackoverflow.com/q/48593496
tags question: http://stackoverflow.com/q/48588507
tags question: http://stackoverflow.com/q/48536676
tags question: http://stackoverflow.com/q/48571259
tags question: http://stackoverflow.com/q/48611376
tags question: http://stackoverflow.com/q/48615667
tags question: http://stackoverflow.com/q/48576072
tags question: http://stackoverflow.com/q/48513777
tags question: http://stackoverflow.com/q/48634151
tags question: http://stackoverflow.com/q/48628041
tags question: http://stackoverflow.com/q/48580703
tags question: http://stackoverflow.com/q/48533216
tags question: http://stackoverflow.com/q/48553974
tags question: http://stackoverflow.com/q/48493755
tags question: http://stackoverflow.com/q/48498711
tags question: http://stackoverflow.com/q/48492613
tags question: http://stackoverflow.com/q/48567012
tags question: http://stackoverflow.com/q/48586429
tags question: http://stackoverflow.com/q/48524836
tags question: http://stackoverflow.com/q/48550201
tags question: http://stackoverflow.com/q/48519317
tags question: http://stackoverflow.com/q/48599464
tags question: http://stackoverflow.com/q/48555290
tags question: http://stackoverflow.com/q/48594888
tags question: http://stackoverflow.com/q/48557788
tags question: http://stackoverflow.com/q/48534517
tags question: http://stackoverflow.com/q/48508036
tag name: keras
tags question: http://stackoverflow.com/q/48641189
tags question: http://stackoverflow.com/q/48595625
tags question: http://stackoverflow.com/q/48626246
tags question: http://stackoverflow.com/q/48490280
tags question: http://stackoverflow.com/q/48490411
tags question: http://stackoverflow.com/q/48566821
tags question: http://stackoverflow.com/q/48525060
tags question: http://stackoverflow.com/q/48538404
tags question: http://stackoverflow.com/q/48619774
tags question: http://stackoverflow.com/q/48489669
tags question: http://stackoverflow.com/q/48610669
tags question: http://stackoverflow.com/q/48551158
tags question: http://stackoverflow.com/q/48612170
type: Tag
tags question: http://stackoverflow.com/q/48564959
tags question: http://stackoverflow.com/q/48624592
tags question: http://stackoverflow.com/q/48558990
tags question: http://stackoverflow.com/q/48620057
tags question: http://stackoverflow.com/q/48608501
tags question: http://stackoverflow.com/q/48519761
tags question: http://stackoverflow.com/q/48622444
tags question: http://stackoverflow.com/q/48530232
tags question: http://stackoverflow.com/q/48617167
tags question: http://stackoverflow.com/q/48598402
tags question: http://stackoverflow.com/q/48491737
tags question: http://stackoverflow.com/q/48507546
tags question: http://stackoverflow.com/q/48566552

http://stackoverflow.com/q/48538314
has answer: http://stackoverflow.com/a/48542148
accepted answer: http://stackoverflow.com/a/48542148
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
score: 1
tagged with: rpy2
tagged with: python
type: Question
has title: Passing python objects to R functions in rpy2
answer count: 1
downvote count: 0
upvote count: 1
has body: I'm working in a Jupyter notebook with Python 2 and want to use rpy2 to plot a heatmap. import numpy as np from rpy2 import robjects from rpy2.robjects import r, pandas2ri from rpy2.robjects import Formula, Environment from rpy2.robjects.vectors import IntVector, FloatVector from rpy2.robjects.lib import grid from rpy2.robjects.packages import importr, data from rpy2.rinterface import RRuntimeError import warnings a = np.array([1.5,2.3]) b = np.array([4.2,5.1]) c = np.array([[0.3, 0.6],[0.6, 0.3]]) r.image.plot(a,b,c) gives me the error AttributeError: 'SignatureTranslatedFunction' object has no attribute 'plot' How do I properly pass the parameters into this function? Specs: rpy2 2.5.6 with R3.3.3 and Python 2.7
favorite count: 0

http://stackoverflow.com/comment/83999210
has text: Thank you for your comment. Yes, I had this in mind but even without the PCA the program did not finish for 460 images within 30 minutes.
comment on: http://stackoverflow.com/q/48502667
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84023290
type: Comment
type: QuestionComment
has text: The solution to your problem is Javascript, not Python. Push all the processing to the client, not the server
comment on: http://stackoverflow.com/q/48514389
score: 0

http://stackoverflow.com/comment/84149194
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48575718
has text: `np.fromfunction` is Python code that you can read and test for yourself. Looks like it does `your_func(*np.indices((3,)))`. I don't think it is used very often. I haven't used it.
score: 0

http://stackoverflow.com/comment/84185346
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48594086
type: QuestionComment
has text: Probably your text editor is wrong. How are you viewing the file content?

http://stackoverflow.com/comment/84194164
has text: Thank you, it certainly helped alot
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48598649

http://stackoverflow.com/q/48603744
tagged with: beautifulsoup
type: Question
possible better answer: http://stackoverflow.com/a/48603807
accepted answer: http://stackoverflow.com/a/48606518
upvote count: 2
has title: Pulling table from site using Python
has answer: http://stackoverflow.com/a/48603807
has comment: http://stackoverflow.com/comment/84204901
has answer: http://stackoverflow.com/a/48606518
has answer: http://stackoverflow.com/a/48604531
tagged with: python
linked to: http://stackoverflow.com/q/60486625
score: 2
type: AnsweredQuestion
answer count: 3
has body: I am attempting to visit this site and pull the information from the table. I'm totally new to this and this is the furthest I could get. Most guides I find aren't really helping me get the end result I wanted and I was hoping to see if someone was able to help. import requests from bs4 import BeautifulSoup source_code = requests.get('blank.com').text soup = BeautifulSoup(source_code, "lxml") table = soup.find_all('table')[7] print(table) this code outputs the following: Process finished with exit code 0 What is my next step in tidying up this information to be used by other python methods? I am looking to format it into a nice table with columns preferably. Thanks!
downvote count: 0
tagged with: python-requests
tagged with: import
favorite count: 0

http://stackoverflow.com/comment/84108434
has text: Does it really matter?
type: QuestionComment
comment on: http://stackoverflow.com/q/48556205
type: Comment
score: 0

http://stackoverflow.com/comment/84064012
has text: For example, the list is defined as a and y would be holding the current y position. If the y position is already in the list I am trying to move to the next largest integer that is not in the list, or else I would add y to the list and continue until reaching the bounds. Based on performance, my current program is acceptable i'm just curious to whether this idea of skipping to the next largest integer rather than incrementing by one would prove to be faster.
comment on: http://stackoverflow.com/q/48534034
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84001894
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48503994
has text: I am more interested in why my current approach does not work that how I can improve it. I will check the link anyways, thanks :)

http://stackoverflow.com/q/48626852
type: Question
has body: I often need to work with dataframes where the rownames (index in pandas) are like of the type [a-z][0-9]+ (e.g. 'a20','a21',... or 'b1','b11','b2',...) I would like to be able to sort the rows based on the number alone. From what I can gather of the API, df.sort_index() does not take a function argument where I can define the sorting function. Is there a neat way of achieving this without resorting to removing the initial characters when creating the dataframe?
has answer: http://stackoverflow.com/a/48626951
has comment: http://stackoverflow.com/comment/84252066
has answer: http://stackoverflow.com/a/48626948
answer count: 3
has title: pandas sort rows by index using a custom function
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84251707
has comment: http://stackoverflow.com/comment/84250561
tagged with: python
linked to: http://stackoverflow.com/q/17901218
has comment: http://stackoverflow.com/comment/84250654
score: 2
tagged with: pandas
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48627542
favorite count: 0

http://stackoverflow.com/comment/84184161
type: AnswerComment
score: 0
has text: Very cool. This work great. Also, thanks for mentioning the token-by-token limitations.
type: Comment
comment on: http://stackoverflow.com/a/48492759

http://stackoverflow.com/a/48562157
downvote count: 0
has comment: http://stackoverflow.com/comment/84125225
answers question: http://stackoverflow.com/q/48560345
has body: User has its own autogenerated id user.id which is ObjectId. You need custom json encoder to encode ObjectId field. import json, bson def json_response(obj, cls=None): response = make_response(json.dumps(obj, cls=cls)) response.content_type = 'application/json' return response class MongoJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bson.ObjectId): return str(obj) return json.JSONEncoder.default(self, obj) Now try to call return json_response(new_user, cls=MongoJsonEncoder)
score: 3
has comment: http://stackoverflow.com/comment/84125489
has comment: http://stackoverflow.com/comment/87870347
type: Answer
has comment: http://stackoverflow.com/comment/84125885
upvote count: 3

http://stackoverflow.com/q/48566418
downvote count: 1
has comment: http://stackoverflow.com/comment/84128879
tagged with: python
has answer: http://stackoverflow.com/a/48566867
has comment: http://stackoverflow.com/comment/84128944
answer count: 4
has title: replacing a string in python list with another string
has comment: http://stackoverflow.com/comment/84128938
favorite count: 0
type: Question
has body: currently my loops stops at replacing 1 with the answer. how do i loop it so it replaces all 4 blanks with the 4 answers? easyQuiz = "There are ___1___ countries in the world. The countries with the biggest landmass is ___2___. The coldest continent in the world is ___3___. ___4___ is the capital of China" blanks = ["___1___","___2___","___3___","___4___"] easyAnswer = ["195","Russia","Antartica","Beijing"] #asks users to choose difficulty level question = raw_input("Shall we start? Easy, Medium, Hard?") if question == "Easy" or question == "easy": answerChoice = easyAnswer answerChoice = answerList(question) newprompt = [] newlist = [] index = 0 maxblanks = 3 for quizwords in difficulty(question).split(): if quizwords == "1" : quizwords = quizwords.replace("1",answerChoice[index]) elif quizwords == "2" : quizwords = quizwords.replace("2",answerChoice[index]) index = index + 1 newlist.append(quizwords) joinedlist = " ".join(newlist)
has comment: http://stackoverflow.com/comment/84128950
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48566580
score: 0
linked to: http://stackoverflow.com/q/2238355
has answer: http://stackoverflow.com/a/48566601
upvote count: 1
has answer: http://stackoverflow.com/a/48566631

http://stackoverflow.com/a/54467310
answers question: http://stackoverflow.com/q/48598324
upvote count: 4
has body: You can convert G.nodes() into a list format compatible with random.choice() by passing list(G.nodes()) instead of just G.nodes(). import networkx as nx import matplotlib.pyplot as plt from random import choice G=nx.Graph() city_set=['a','b','c','d','e','f','g','h'] for each in city_set: G.add_node(each) ab= choice(list(G.nodes())) print(ab)
downvote count: 0
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/95743825

http://stackoverflow.com/a/48570378
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48569965
has comment: http://stackoverflow.com/comment/84138753
has comment: http://stackoverflow.com/comment/84140710
has body: The first problem you have is the way the lists are structured. There needs to be a comma separation between each list. sysusers = [['user1'],[7972], ['user2'],[2121], ['hacker'],[2132], ['hacker2'],[1232]] users = [['user1'],[7972], ['user2'],[2121]] Once this is correct, accessing the data you require is simple. goodusers = [] for i in users: for j in i: for k in sysusers: for l in k: if l == j: goodusers.append(k) badusers = [x for x in sysusers if x not in goodusers] print(badusers) [['hacker'], [2132], ['hacker2'], [1232]]
type: Answer
accepted answer of: http://stackoverflow.com/q/48569965
score: 1

http://stackoverflow.com/comment/84173333
comment on: http://stackoverflow.com/q/48588049
score: 0
type: Comment
type: QuestionComment
has text: When dealing with dictionaries, you are implicitly accessing the keys when you iterate over the dict, the same as doing `dict.keys()`. You might try `dict.values()` for just the values or dict.`iteritems()` for the key value pairs.

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

http://stackoverflow.com/a/48546541
has comment: http://stackoverflow.com/comment/84090160
type: Answer
has body: Here is another way: from collections import Counter def hasOnlyOneDuplicate(s): return len([c for c,v in Counter(s).items() if v &gt; 1]) == 1 Using a comprehension rather than filter and lambda is more pythonic.
answers question: http://stackoverflow.com/q/48546347
downvote count: 0
has comment: http://stackoverflow.com/comment/84089752
score: 1
upvote count: 1

http://stackoverflow.com/comment/84050462
score: 0
comment on: http://stackoverflow.com/q/48527629
has text: I find using `containers[8].p` kind of weird, that really works ? I'd use find : `containers[8].find('p')`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48643181
answer count: 2
has body: I used Perceptron from sklearn.linear_model for the first time and I got this message "DeprecationWarning: n_iter parameter is deprecated in 0.19 and will be removed in 0.21. Use max_iter and tol instead. DeprecationWarning" while using the following code. from sklearn.linear_model import Perceptron ppn=Perceptron(n_iter=40, eta0= 0.1, random_state=1) ppn.fit(X_train_std, y_train) y_pred = ppn.predict(X_test_std) Could somebody tell me what is the issue here ? Thank you
downvote count: 4
possible better answer: http://stackoverflow.com/a/48643242
has answer: http://stackoverflow.com/a/48643242
tagged with: machine-learning
favorite count: 0
linked to: http://stackoverflow.com/q/44944208
type: Question
accepted answer: http://stackoverflow.com/a/48643356
has comment: http://stackoverflow.com/comment/84282914
has title: Please what is the meaning of the Deprecation_Warning message?
has comment: http://stackoverflow.com/comment/104690949
has answer: http://stackoverflow.com/a/48643356
duplicate of: http://stackoverflow.com/q/44944208
tagged with: python
upvote count: 4
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/84023996
comment on: http://stackoverflow.com/q/48514653
score: 0
has text: "How do I dynamically create variables" is a very common beginner question, but the sane answer is almost always "use a dict" or "use a list". Search for duplicates.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48934138
downvote count: 0
upvote count: 1
has body: Your network might be taking a long time to compute the forward and backward passes through the data. I tracked down the perceived unresponsiveness to the acc.update call (a little later than neural_net(...)). Digging deeper into this function, we're waiting for nd.asnumpy to resolve. Confusion lies with the fact that MXNet NDArray computations are asynchronous. All the training forward/backward pass operations appear to resolve instantly but are in fact added to a queue to processing. It's only when data is brought back into the python process (via nd.asnumpy) that you have to wait for the relevant operations to finish. And this happens for the first time in acc.update. Another way of benchmarking performance of certain code blocks is to use mx.nd.waitall() which blocks the code until the computation queue is empty. Adding this to your training cycle, you can see that it takes much longer than it initially appears. Using a GPU would likely help this apparent unresponsiveness.
answers question: http://stackoverflow.com/q/48541652
accepted answer of: http://stackoverflow.com/q/48541652
has comment: http://stackoverflow.com/comment/85212150
type: Answer
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48552103
score: 1
has comment: http://stackoverflow.com/comment/84304929
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84195402
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
has title: Why does the TensorFlow tf.data.Dataset.shuffle function's reshuffle_each_iteration boolean argument default to None, as opposed to True?
type: Question
has body: The documentation for the tf.Dataset.data.shuffle function states the following: reshuffle_each_iteration: (Optional.) A boolean, which if true indicates that the dataset should be pseudorandomly reshuffled each time it is iterated over. (Defaults to True.) However, the default value in the function is None, as mentioned on the same page and in the actual code: def shuffle(self, buffer_size, seed=None, reshuffle_each_iteration=None): The function calls the ShuffleDataset class, whose __init__ function also sets the same argument to None by default, and uses the following logic to set the default value of the argument to True: if reshuffle_each_iteration is None: self._reshuffle_each_iteration = True else: self._reshuffle_each_iteration = reshuffle_each_iteration Why isn't the argument just set to True by default in both the function and the class? This would make the above code block redundant and allow replacing it with only self._reshuffle_each_iteration = reshuffle_each_iteration.
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48673870
has answer: http://stackoverflow.com/a/48673870
type: AnsweredQuestion

http://stackoverflow.com/a/48639379
downvote count: 0
has body: The round() function is focused on rounding to tenths, hundredths, thousandths and so on - essentially rounding to some negative exponent of 10. So, as 0.0125 is not such a number that the round() can handle, you can either apply a multiplication to your input number before giving it to round, so that it can do a rounding for which it is designed, and afterwards you correct for the initial multiplication. One of the other answers does it like this. or you can, if you think the first approach looks complicated, solve the problem with pure mathematics. The code below essentially looks how much there is actually "too much" above a multiple of 0.0125. This "too much" amount is a remainder (modulus) of a division. This division is done on integers, so there is an initial multiplication and correction afterwards, just like in the first approach. Code for the second approach: def round_0125(number): mult_number = number * 10000 remainder = mult_number % 125 return (mult_number - remainder) / 10000 round_0125(167.1131) #167.1125 round_0125(167.5738) #167.5625
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48638805
score: 2

http://stackoverflow.com/q/48624223
tagged with: django-taggit
tagged with: django
tagged with: keyword-argument
has title: Django-taggit kwargs understanding
accepted answer: http://stackoverflow.com/a/48639500
type: Question
possible better answer: http://stackoverflow.com/a/48625785
tagged with: python
has answer: http://stackoverflow.com/a/48625785
type: AnsweredQuestion
answer count: 2
has body: I'm using-django taggit and it works fine. But there are need to make some changes to extend DetailView url and after them TagListView chushed with 404 error. So i'm undestand that problem with kwargs in get_absolute_url function, but i can't understand how to fix it. So, work fine: models.py def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) urls.py: url(r'^(?P&lt;slug&gt;[\w-]+)/$', Detail.as_view(), name='detail'), url(r'^tag/(?P&lt;slug&gt;[\w-]+)/$', TagListView.as_view(), name='tagged'), views.py: class TagListView(ListView): template_name = "posts/postlist.html" paginate_by = "3" def get_queryset(self): return Post.objects.filter(tags__slug=self.kwargs.get("slug")).all() def get_context_data(self, **kwargs): context = super(TagListView, self).get_context_data(**kwargs) context["tag"] = self.kwargs.get("slug") return context And when I add "category": self.category to get_absolute_url and urls it crush: models.py: def get_absolute_url(self): return reverse("posts:detail", kwargs={"category": self.category, "slug": self.slug}) urls.py: url(r'^(?P&lt;category&gt;[\w-]+)/(?P&lt;slug&gt;[\w-]+)/$', Detail.as_view(), name='detail'), url(r'^tag/(?P&lt;slug&gt;[\w-]+)/$', TagListView.as_view(), name='tagged'), I suppose that there shoulb be changes in get_context_data func, but can't see what exactly. Any ideas or advices please?
has answer: http://stackoverflow.com/a/48639500
score: 0

http://stackoverflow.com/q/48601038
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/105521172
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84201757
type: UnansweredQuestion
tagged with: python
tagged with: boto3
score: 4
tagged with: amazon-web-services
upvote count: 4
has body: SCENARIO I have two AWS accounts linked to a third aws account, main account. The accounts names, for instance, are aws_acc_main, aws_acc_1, aws_acc_2 aws_main is used to maintain the users, groups and roles for the other two accounts. however, except IAM no other services are used in the main account. Using boto3 and Python I want to get ec2 instances for the account-1 and account-2 Thr AWS configuration looks like: .aws/credentials file [aws_acc_main] aws_access_key_id=AKJFJHNUCTYUUAPW aws_secret_access_key = 2uldfr94tuowjuHUKbnBIby8jhfdgjh .aws/config [aws_acc_main] output = json region = eu-west-2 [profile aws_acc_1] source_profile = aws_acc_main output = json region = eu-west-2 role_arn = arn:aws:iam::111111111111:role/ACC1_ROLE mfa_serial = arn:aws:iam::111111111110:mfa/ABCD [profile aws_acc_2] source_profile = aws_acc_main output = json region = eu-west-2 role_arn = arn:aws:iam::111111111112:role/ACC2_ROLE mfa_serial = arn:aws:iam::111111111110:mfa/ABCD Now the python files. test1.py sessions = ['aws_acc_1', 'aws_acc_2'] for session_name in sessions: session = boto3.Session(profile_name=session_name) ec2 = session.client('ec2', region_name='eu-west-2') resources = ec2.describe_instances() test2.py mfa_code = raw_input("Enter the MFA code: ") client = boto3.client('sts') response = client.get_session_token( DurationSeconds=3600, SerialNumber='arn:aws:iam::111111111110:mfa/ABCD', TokenCode=mfa_code ) credentials = response['Credentials'] for session_name in sessions: session = boto3.Session(profile_name=session_name, aws_access_key_id = credentials['AccessKeyId'], aws_secret_access_key = credentials['SecretAccessKey'], aws_session_token = credentials['SessionToken'], ) ec2Client = session.client('ec2', region_name='eu-west-2') resources = ec2.describe_instances() PROBLEM The first (test1.py) works OK but I have to provide MFA for each account in every iteration. The second file (test2.py) does not give any errors either but it does not read the EC2 service of a…
has title: using boto3 and Python how to create AWS MFA authorized session which can be used by other roles
tagged with: boto
has comment: http://stackoverflow.com/comment/84203743

http://stackoverflow.com/a/48540325
has comment: http://stackoverflow.com/comment/84075815
has comment: http://stackoverflow.com/comment/84076370
answers question: http://stackoverflow.com/q/48540174
type: AcceptedAnswer
downvote count: 0
has body: try localhost:8000/apidocs/index.html Explanation This is the default endpoint of Swagger. What you were trying to do is accessing one endpoint of your API and expecting it to render the Swagger UI. Swagger UI is an ADDITIONAL endpoint to your API which lists and lets you try all other endpoints. Hope that helps!
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48540174
score: 1
type: Answer

http://stackoverflow.com/comment/84072472
score: 0
has text: Possible duplicate of [Python CSV to JSON](https://stackoverflow.com/questions/19697846/python-csv-to-json)
comment on: http://stackoverflow.com/q/48538663
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84028918
type: QuestionComment
score: 5
has text: What have you actually tried?
comment on: http://stackoverflow.com/q/48517177
type: Comment

http://stackoverflow.com/comment/84168369
has text: upvoted. generator expressions are ideal for, well, generatable collections.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48585737

http://stackoverflow.com/comment/84176234
comment on: http://stackoverflow.com/a/48583765
score: 0
has text: Yes. the `#!/usr/bin/env python` and the utf-8 thing are before everything in the code. `apt-get install python3-pip` did not work. I have no need for `sudo`, i'm running Kali.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48604116
type: Question
has comment: http://stackoverflow.com/comment/84205071
type: UnansweredQuestion
has title: Python cumulative and semester GPA calculator methods
has comment: http://stackoverflow.com/comment/84204944
has comment: http://stackoverflow.com/comment/84205116
tagged with: python
has answer: http://stackoverflow.com/a/48604419
has comment: http://stackoverflow.com/comment/84205060
has body: I am trying to write a method that calculates GPA. I want to calculate semester and cumulative. The code below is supposed to calculate the cumulative GPA (I have more options for other grades too). This is not producing values like 3.4, 3.5, as it should. And I am unsure how to calculate the semester grade using what I have. Any help is appreciated! class GPA(object): def __init__(self, grade, hours): self.grade = grade self.hours = hours def cumGPA(self, grade, hours): totPoint = 0 totCred = 0 if self.grade == 'A': totPoint = float(totPoint) + float(self.hours*4) totCred = float(totCred) +float(self.hours) if self.grade == 'B': totPoint = float(totPoint) + float(self.hours*3) totCred = float(totCred) +float(self.hours) if self.grade == 'C': totPoint = float(totPoint) + float(self.hours*2) totCred = float(totCred) +float(self.hours) if self.grade == 'D': totPoint = float(totPoint) + float(self.hours*1) totCred = float(totCred) +float(self.hours) else: totPoint = float(totPoint) + float(self.hours*0) totCred = float(totCred) +float(self.hours) return (totPoints / totCred) I ran the following: test = GPA('A',12) test.cumGPA('A',12) and I get 1010101.0
has comment: http://stackoverflow.com/comment/84204960
has comment: http://stackoverflow.com/comment/84205172
tagged with: class
has comment: http://stackoverflow.com/comment/84205323
has comment: http://stackoverflow.com/comment/84205107
has comment: http://stackoverflow.com/comment/84205166
score: 0
has comment: http://stackoverflow.com/comment/84205177
answer count: 1
has comment: http://stackoverflow.com/comment/84205043
tagged with: methods
has comment: http://stackoverflow.com/comment/84205208

http://stackoverflow.com/a/55862350
answers question: http://stackoverflow.com/q/48632882
type: Answer
has body: Check your conda version conda -V Create virtual environment for your project conda create -n yourenvname python=x.x anaconda To activate your virtual environment source activate yourenvname
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84209605
has text: average of what exactly?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48606567
type: Comment

http://stackoverflow.com/a/48648029
accepted answer of: http://stackoverflow.com/q/48640667
has body: bokeh.pallettes.BuGn8 is not a color, it's a list of colors. And, as the error states, you can't mix lists and a data source when using glyph methods. If you need a different color for each line, you can add another column to your data source and pass the name of the column to the color attribute of multi_line glyph function. A small example: from bokeh.io import output_file, show from bokeh.models import ColumnDataSource from bokeh.plotting import figure from bokeh.palettes import BuGn8 p = figure() ds = ColumnDataSource(data=dict(xs=[[1, 2, 3], [2, 3, 4]], ys=[[3, 2, 1], [4, 3, 2]], color=[BuGn8[0], BuGn8[-1]])) p.multi_line(xs='xs', ys='ys', color='color', source=ds, line_width=10) output_file("test.html") show(p)
answers question: http://stackoverflow.com/q/48640667
has comment: http://stackoverflow.com/comment/84306404
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84325150
score: 0
has comment: http://stackoverflow.com/comment/84393421

http://stackoverflow.com/q/48574201
has answer: http://stackoverflow.com/a/48574306
type: AnsweredQuestion
downvote count: 2
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/84145452
tagged with: function
has comment: http://stackoverflow.com/comment/84145169
has comment: http://stackoverflow.com/comment/84145517
favorite count: 0
has comment: http://stackoverflow.com/comment/84145259
has comment: http://stackoverflow.com/comment/84145199
type: Question
has body: I want to change the value of a variable through a function but python functions do not modify a variable when run. For example: import random as r x=2 def add(x): x=x+r.randint(5,10) print x add(x) print x the function variable x, shows something like 8 while the other x is 2. Adding the line: x=add() will cause the two to be nonequivalent. How can i save the variable from a function, modifying the old.
has title: Saving the output of a function
has comment: http://stackoverflow.com/comment/84145260
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/48574306
has answer: http://stackoverflow.com/a/48574280
accepted answer: http://stackoverflow.com/a/48574280

http://stackoverflow.com/a/48560587
answers question: http://stackoverflow.com/q/48560319
has body: if you can use the dateutil module from dateutil import parser dt = parser.parse("31/3/2017") print dt.strftime('%Y-%m-%d') Output: 2017-03-31 Using datetime import datetime A = datetime.datetime.strptime('31/3/2017','%d/%m/%Y') print A.strftime('%Y-%m-%d')
type: Answer
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84116770
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48560319
score: 2

http://stackoverflow.com/comment/84254198
comment on: http://stackoverflow.com/q/48625138
type: QuestionComment
has text: Possible duplicate of [Python Windows Authentication username and password is not working](https://stackoverflow.com/questions/45328654/python-windows-authentication-username-and-password-is-not-working)
type: Comment
score: 0

http://stackoverflow.com/a/48512059
answers question: http://stackoverflow.com/q/48512003
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84019099
accepted answer of: http://stackoverflow.com/q/48512003
has comment: http://stackoverflow.com/comment/84019321
has comment: http://stackoverflow.com/comment/84019042
type: Answer
has comment: http://stackoverflow.com/comment/84019061
has comment: http://stackoverflow.com/comment/84019255
has body: You could loop over the lists in order to get the totals. irish_total = 0 mountaineers_total = 0 for quarter in (my_scores1, my_scores2, my_scores3, my_scores4): mountaineers_total += quarter[1] irish_total += quarter[2]
score: 0

http://stackoverflow.com/q/48581455
answer count: 1
upvote count: 1
favorite count: 0
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/48579982
accepted answer: http://stackoverflow.com/a/48582418
tagged with: windows
downvote count: 0
has answer: http://stackoverflow.com/a/48582418
tagged with: python
has comment: http://stackoverflow.com/comment/84160577
has comment: http://stackoverflow.com/comment/84159261
has body: Based on this answer, I'd like to run this multiprocessing job with Python 2.7 / Windows: def main(): import itertools as it from multiprocessing import Pool def dothejob(i, j, k): print i, j, k the_args = it.product(range(100), range(100), range(100)) pool = Pool(4) def jobWrapper(args): return dothejob(*args) res = pool.map(jobWrapper, the_args) if __name__ == '__main__': main() The main() and the last two lines are necessary because without them, there's the well known bug: This probably means that you are on Windows and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': .... But even with that, I get this error: File "C:\Users\User\Desktop\test.py", line 14, in main res = pool.map(jobWrapper, the_args) File "C:\Python27\lib\multiprocessing\pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "C:\Python27\lib\multiprocessing\pool.py", line 558, in get raise self._value cPickle.PicklingError: Can't pickle : attribute lookup >builtin.function failed Where is there a cPickle involved here and why this error / how to solve it?
linked to: http://stackoverflow.com/q/8804830
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/27318290
has title: Run a multiprocessing job with Python 2.7 / Windows

http://stackoverflow.com/q/48630171
score: 6
has comment: http://stackoverflow.com/comment/84258893
favorite count: 0
type: Question
has title: How to document simple Python script using Sphinx?
has body: I have gone through numerous Sphinx tutorials, but I still can't figure out how to make Sphinx document a simple Python script like this one: def addNumbers(a): """This function adds one to the given number. :param a: The name to use :type a: int """ b = a + 1 print b addNumbers(5) Below are the steps that I make. What am I missing? Install Sphinx: pip install sphinx Create a documentation directory within my project directory: mkdir docs Run sphinx-quickstart from inside of the new doc directory and hit Enter to answer every question except for these two: Separate source and build directories (y/n) [n]: y autodoc: automatically insert docstrings from modules (y/n) [n]: y This makes my project directory structure become this: myproject/ |-- docs/ |-- build/ |-- source/ make.bat Makefile |-- mycode/ myscript.py Open conf.py, uncomment the following lines, and add the path of the folder where my code is located: import os import sys sys.path.insert(0, os.path.abspath('C:\myproject\mycode')) Run the following command from my docs directory: make html Which gave me the following confirmation with no errors: Now when I open C:\myproject\docs\build\html\index.html, all I see is the following and no info from the docstrings that I inserted in my original script. Clicking on Module Index gives a file not found error. Why is that? EDIT: After doing all the above steps, I added a folder mypackage and copied the file with my code in there making the directory content look like this: myproject/ |-- docs/ |-- build/ |-- source/ make.bat Makefile |-- mycode/ myscript.py |-- mypackage/ myscript.py I then ran the following commands from doc directory: sphinx-apidoc -f -o source/ ../mypackage/ make html Now clicking through Module Index gives me the following: And clicking on myscript gives this: Now the question is why is my main script myscript.py is listed under modules and not listed on the home page of the documentations?
has comment: http://stackoverflow.com/comment/84258810
has comment: http://stackoverflow.com/comment/84259306
tagged with: python-sphinx
has comment: http://stackoverflow.com/comment/84263881
has comment: http://stackoverflow.com/comment/84259605
has answer: http://stackoverflow.com/a/48638434
tagged with: python
upvote count: 6
answer count: 1
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84259688
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84257818
downvote count: 0

http://stackoverflow.com/comment/84015858
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48510399
type: Comment
has text: @jpaugh Its video files, I'm parsing the file so I can get the Name;Year;Extension and store that to a local database. Is there another way to monitor Windows to get what files are being opened? Then I can compare if its a valid video file then proceed the program.

http://stackoverflow.com/a/48525736
type: Answer
has body: Rather than grouping, how about: for feat1 in data.columns.levels[0]: print(list(data.columns.levels[1])) [0, 1, 2, 3, 4] [0, 1, 2, 3, 4] [0, 1, 2, 3, 4]
answers question: http://stackoverflow.com/q/48522952
has comment: http://stackoverflow.com/comment/84049992
score: 0

node.js
tags question: http://stackoverflow.com/q/48609484
tags question: http://stackoverflow.com/q/48600583
tags question: http://stackoverflow.com/q/48606817
type: Tag
tag name: node.js
tags question: http://stackoverflow.com/q/48563969
tags question: http://stackoverflow.com/q/48637327
tags question: http://stackoverflow.com/q/48536410
tags question: http://stackoverflow.com/q/48607636

http://stackoverflow.com/comment/84281455
score: 0
has text: The magic number is to check if is actually a Zip file, right? It matches the following which means it is ZIP: \x50\x4b\x03\x04
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48639646

http://stackoverflow.com/comment/83996564
comment on: http://stackoverflow.com/q/48500092
has text: Try to follow these steps: https://stackoverflow.com/a/27650735/9202856
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85403427
type: AnswerComment
score: 0
type: Comment
has text: There are already some answers on SO which show how to use blitting. So it is questionable if this answer has actually anything to add to those.
comment on: http://stackoverflow.com/a/49196469

http://stackoverflow.com/q/48551674
type: UnansweredQuestion
tagged with: django
tagged with: javascript
tagged with: python
has title: How do I link to Django static assets from my JavaScript files?
score: 0
answer count: 1
has body: I'm trying to load a specific file but failing due to the way Django manages relative paths. Here's the structure of my app: mysite |-- manage.py |-- mysite |-- __init__.py |-- settings.py |-- urls.py |-- wsgi.py |-- app |-- __init__.py |-- models.py |-- tests.py |-- views.py |-- static |-- JS |-- myScript.js |-- data |-- myData.geojson |-- templates |-- app |-- index.html In other words, pretty standard. The two key parts are that I load myScript.js in to my index.html like so: &lt;script type='text/javascript' src="{% static '/JS/myScript.js' %}"&gt;&lt;/script&gt; The issue is that, within myScript.js, I want to load in myData.geojson. This doesn't work: ... 'url': '/static/data/myData.geojson' ... nor does 'url': '{% static /data/myData.geojson %}' #this throws an error I just want a project setup where I can use relative path to do this: 'url': '../data/myData.geojson' Is that possible? My current settings are this: STATIC_URL = '/static/' STATIC_ROOT = '/var/www/mysite/static'
type: Question
has answer: http://stackoverflow.com/a/48552277

http://stackoverflow.com/a/48544877
has body: You have a faulty/personal version of subprocess in your PYTHONPATH. username = str(raw_input('username: ')) does not exist in any python distribution of subprocess.py I'm familiar with. Delete/rename that file, or better yet, remove /home/flira/Downloads/ from your PYTHONPATH. The way to install any library is through apt-get, not by downloading it manually (if you're not sure of what you're doing). Further investigation I now noticed your terminal screenshot - you're running from Downloads, hence the file is in you path. Get rid of it.
has comment: http://stackoverflow.com/comment/84085249
accepted answer of: http://stackoverflow.com/q/48541726
has comment: http://stackoverflow.com/comment/84085213
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84085387
answers question: http://stackoverflow.com/q/48541726
downvote count: 0
has comment: http://stackoverflow.com/comment/84085332
type: Answer

http://stackoverflow.com/a/69000412
score: 0
has body: include these lines: from plotly.offline import plot, iplot, init_notebook_mode import plotly.graph_objs as go init_notebook_mode(connected=True) works for me
answers question: http://stackoverflow.com/q/48560138
type: Answer

http://stackoverflow.com/a/48550836
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84298861
has comment: http://stackoverflow.com/comment/84381401
has comment: http://stackoverflow.com/comment/84301137
has body: Here is one solution that assumes that the original data frame is named df: import pandas as pd # Group by id and find minimum value df1 = df.groupby('search_id').min() # Keep only id with changes_airport == False df1 = df1[df1['changes_airport'] == False].reset_index() # Merge the two data frames - creates additional columns in df2 df2 = pd.merge(df, df1, how='outer', on=['search_id']) # Fill the new column based on the difference between current cell total_fare # and the minimum fare for the respective search_id df2['alternatives'] = (df2['total_fare_x'] - df2['total_fare_y']) &lt; 10 # Drop auxiliary columns del df2['changes_airport_y'], df2['total_fare_y'] print(df2) changes_airport_x search_id total_fare_x alternatives 0 False abc 101 True 1 True abc 121 False 2 True abc 105 True 3 True abd 120 False
score: 1
accepted answer of: http://stackoverflow.com/q/48548187
has comment: http://stackoverflow.com/comment/84298837
answers question: http://stackoverflow.com/q/48548187
type: AcceptedAnswer

http://stackoverflow.com/comment/84129420
score: 0
has text: @duhaime, yes, it did. I guess Robin re-did the website design and push the wxPython to the PyPI place. What problem(s) did you encounter trying to install from the SF? Did you report it to the wxPython ML?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48533589

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

http://stackoverflow.com/comment/84253833
type: Comment
type: QuestionComment
has text: You can't control the time between operations. It happens as fast as possible (commonly with milliseconds between them). Further, this is to allow other developers to run open ended scripts, not things that I control or want to be trying to programmatically manipulate. In sql scripts you can freely change how your subsequent statements will be parsed even. It's very common to change statement delimiters. It would be a horrible mess to try and parse or inject into the source scripts, or to parse the combined results.
score: 0
comment on: http://stackoverflow.com/q/48610767

http://stackoverflow.com/comment/84211466
type: AnswerComment
comment on: http://stackoverflow.com/a/48606217
has text: Ok, but translation must compile after change and django server reload to new translations applied. by this reasons i think you cant find any django app that made for this aim.
score: 0
type: Comment

http://stackoverflow.com/comment/84185961
type: Comment
score: 4
comment on: http://stackoverflow.com/q/48591134
type: QuestionComment
has text: One solution for any specific site will not work for another unless they are identically structured. What is it you are trying to collect from that page?

transpose
tags question: http://stackoverflow.com/q/48632756
tags question: http://stackoverflow.com/q/48509674
tag name: transpose
tags question: http://stackoverflow.com/q/48535282
type: Tag

http://stackoverflow.com/q/48501676
answer count: 2
has comment: http://stackoverflow.com/comment/83999811
has answer: http://stackoverflow.com/a/48502260
possible better answer: http://stackoverflow.com/a/48502260
upvote count: 0
downvote count: 1
has answer: http://stackoverflow.com/a/48502285
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48502285
tagged with: python-3.x
has title: Logs not printing in file in python
has body: I am trying to print logs using logger module in python. Following is the code I am keeping on the top of file. if __name__ == '__main__': LOG_FILENAME = '/home/akash/exdion-pdf-extracter/doc/epod.log' logging.basicConfig( filename=LOG_FILENAME, level=logging.DEBUG, ) There are different files with function calls from one another. I have used the following line to display a line in the logger. @staticmethod def initiate_pdf_processing(ct_doc, pt_doc, feature, startAndEndKeyList): logging.info("testing logger") ... There are multiple instances of the similar above logger function. But I can't receive the logger output in the designated file. The code and files are huge. However there are a few error generated by the code which are getting printed in the log file.
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83997078
tagged with: logging
has comment: http://stackoverflow.com/comment/84000142
type: AnsweredQuestion

http://stackoverflow.com/comment/84183378
has text: Then use `eval` to convert it to `list` of `dict`
type: QuestionComment
comment on: http://stackoverflow.com/q/48593007
type: Comment
score: 0

http://stackoverflow.com/q/48553384
tagged with: python
type: UnansweredQuestion
has title: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)
has body: i know there is a few questions related to this, but i cant seem to find a specific answer or solution i need my python django on an aws instance gives me this 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128) error but in my local it is working perfectly fine, i installed the same requirements needed to run it, it has the same virtual environment, the same version of everything. and i cant seem to find where is the error specially since it is working 100% fine and not on the server im using. the whole thing error it gives is this: error (appearently im not allowed to post images) i realize its a country with a weird name
tagged with: encoding
score: 0
answer count: 0
tagged with: amazon-ec2
tagged with: django
has comment: http://stackoverflow.com/comment/84103704
has comment: http://stackoverflow.com/comment/84128163
type: Question

http://stackoverflow.com/comment/84034266
type: QuestionComment
comment on: http://stackoverflow.com/q/48518891
score: 0
type: Comment
has text: @CristiFati - gs is working, but can not execute the command at the end of the trackback because the files in the path in that command is temporary file.

http://stackoverflow.com/comment/84271156
has text: Also on PyTorch forum https://discuss.pytorch.org/t/unable-to-learn-xor-representation-using-2-layers-of-multi-layered-perceptron-mlp/13287/6
score: 0
comment on: http://stackoverflow.com/q/48619928
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83981039
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48493838
has text: Yes, `game` as you defined it is in global scope. I'm a bit confused because I thought you said you were trying to get *rid* of globals! :-) Anyway, I don't know how VS does its autocompletion.

http://stackoverflow.com/comment/84006339
type: Comment
type: AnswerComment
score: 0
has text: Yeah, or I'm discovering how sad of a python community Stack Overflow has. I read about the python community being really negative and I didn't really believe it, but apparently it's true. "unpythonic" is possibly the stupidest idea I've ever heard. (This isn't aimed at you, unless you're one of the 4 downvoters)
comment on: http://stackoverflow.com/a/48505255

http://stackoverflow.com/a/48622589
accepted answer of: http://stackoverflow.com/q/48622500
score: 3
answers question: http://stackoverflow.com/q/48622500
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Try to implement below line driver.execute_script('document.querySelector("#image_sec&gt;img").src="new_city.png";') or driver.execute_script('document.querySelector("#image_sec&gt;img").setAttribute("src", "new_city.png");')

http://stackoverflow.com/comment/84268009
type: QuestionComment
comment on: http://stackoverflow.com/q/48635316
has text: https://docs.python.org/3.6/howto/curses.html
score: 0
type: Comment

http://stackoverflow.com/comment/84263359
comment on: http://stackoverflow.com/a/48632824
type: AnswerComment
has text: Do you know why there are duplicated lists in the array?
score: 1
type: Comment

http://stackoverflow.com/q/48538404
tagged with: python
has comment: http://stackoverflow.com/comment/84143262
has comment: http://stackoverflow.com/comment/84076229
type: Question
has title: Tensorflow cannot decode csv
has comment: http://stackoverflow.com/comment/84073289
has body: I have the following code taken from the book "TensorFlow 1.x Deep Learning Cookbook", where the dataset has been taken from http://lib.stat.cmu.edu/datasets/boston import tensorflow as tf # Global Parameters DATA_FILE = 'boston_housing.csv' BATCH_SIZE = 10 NUM_FEATURES = 14 # Define function thaat takes the file name and returns # tensors in batches of size equal to batch_size def data_generator(filename): ''' Generates Tensors in batches of size BATCH_SIZE. Args: String Tensor Filename from which data is to be read Returns: Tensors feature_batch and label_batch ''' # Define the filename that is "f_queue" and "reader" f_queue = tf.train.string_input_producer(filename) reader = tf.TextLineReader(skip_header_lines=1) # Skips the first line _, value = reader.read(f_queue) # Specify data to use in case of missing data. Decode the csv and select the features we need. For instance # We choose RM, PTRATIO, LSTAT. record_defaults = [ [0.0] for _ in range(NUM_FEATURES)] data = tf.decode_csv(value, record_defaults = record_defaults) features = tf.stack(tf.gather_nd(data, [[5], [10], [12]])) label = data[-1] # Define parameters to generate batch and use tf.train.shuffle_batch() for randomly # shuffling tensors. The function returns the tensors-- feature_batch and label_batch # Minimum number of elements in the queue after a dequeue min_after_dequeue=10*BATCH_SIZE # Maximum number of element in the queue capacity = 20 * BATCH_SIZE # Shuffle the data to generate BATCH_SIZE sample pairs feature_batch, label_batch = tf.train.shuffle_batch([features, label], batch_size = BATCH_SIZE, capacity = capacity, min_after_dequeue = min_after_dequeue) return feature_batch, label_batch # Function that generate the batches in the session def generate_data(feature_batch, label_batch): with tf.Session() as sess: # initialize the queue threads coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for _ in range(5): # generate 5 batches features, labels = sess.run([fe…
answer count: 0
tagged with: deep-learning
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84076161
tagged with: machine-learning
tagged with: keras
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/84143229
score: 0

http://stackoverflow.com/comment/83983167
type: AnswerComment
comment on: http://stackoverflow.com/a/48494938
type: Comment
has text: I am sorry, the comment got posted without completion. Here it is How do you suggest running this script using parallel? `date && time /opt/app/python-2.7.9/bin/python2.7 /opt/app/busco-master/scripts/run_BUSCO.py -i v.umbellata_final_assembly_master_datastore_index.maker.transcripts1000.fasta -o v.umbellata_final_assembly_maker -l embryophyta_odb9/ -m genome --long -sp tomato -z --augustus_parameters='--progress=true'`
score: 0

http://stackoverflow.com/q/48555768
has answer: http://stackoverflow.com/a/48556253
has title: how to create a url pattern on path(django 2.0) for a *item*_id in django
tagged with: django
tagged with: python
answer count: 3
has body: Here's my code from django.urls import path urlpatterns = [ # /audios/ path('', views.audio ), # /audios/4344/ path('(&lt;record_id&gt;[0-9]+)/', views.record_detail), ] Please can someone help out
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48556138
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48556177
favorite count: 0
type: Question

http://stackoverflow.com/comment/84181848
has text: @Alexis.Rolland yes that would work because it's filtering my_huge_list. This is what I'm trying to achieve here with the list comprehension. A Filter on my_huge_list that reduced the size of the for loop itterable in-place.
comment on: http://stackoverflow.com/q/48591755
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48590189
has answer: http://stackoverflow.com/a/48591109
has answer: http://stackoverflow.com/a/48592336
downvote count: 1
score: -1
has title: python range from data frame to generate extra rows
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
answer count: 2
upvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84178116
has body: I have a table that looks like this: How can I convert it to: ID mapping_value RANGE 10 A 001 10 A 002 10 A 003 10 A 004 10 A 212 20 C 001 20 C 002 20 C 003 20 C 004 20 C 005 20 C 006 20 C 007 this is in order to make a relationship database easier to join on afterwards
tagged with: list
tagged with: pandas

http://stackoverflow.com/comment/84005128
score: 0
comment on: http://stackoverflow.com/q/48505502
type: Comment
has text: Why in column B ? Anything there in Column A ?
type: QuestionComment

http://stackoverflow.com/q/48613828
has comment: http://stackoverflow.com/comment/84224541
has body: How can I convert the Numpy array into a string? data = rawTrainingData[0:25010,0:10] labels = rawTrainingData[0:25010,10] stringData = np.array(map(str,data)) print data[1] print stringData[1]
score: 0
answer count: 1
upvote count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/84224527
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84224764
has comment: http://stackoverflow.com/comment/84224969
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/48614070
has title: How to convert a Numpy array of int to string in Python?
has comment: http://stackoverflow.com/comment/84224704
tagged with: int

http://stackoverflow.com/q/48525383
downvote count: 0
has answer: http://stackoverflow.com/a/48525665
has comment: http://stackoverflow.com/comment/84045889
favorite count: 0
has body: I need to find all elements as 1.204 in my html code. I can't send all the html code because it is confidential information. I'm trying with this code: # encoding=utf8 # -*- coding: utf-8 -*- import random import requests from requests.auth import HTTPBasicAuth import sys import csv from bs4 import BeautifulSoup reload(sys) sys.setdefaultencoding('utf-8') lista = [] number = str(random.random()) user = '' passwd = '' url = '' login = requests.get(url, auth=HTTPBasicAuth(user, passwd)) url_sitios = '' sitios = requests.get(url_sitios, auth=HTTPBasicAuth(user, passwd)) sitios2 = sitios.text html = sitios2 soup = BeautifulSoup(html) for item in soup.find_all("td", {"class": " es_numero cell_imps24ad"}): print item.text, item.next_sibling And the output I want is something like this: es_numero cell_imps24ad : 1.204
tagged with: beautifulsoup
type: Question
upvote count: 2
type: UnansweredQuestion
has title: Find elements with BeautifulSoup in a HTML
has comment: http://stackoverflow.com/comment/84045769
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 2
answer count: 1

http://stackoverflow.com/comment/84137379
score: 0
comment on: http://stackoverflow.com/q/48570385
type: Comment
has text: Yeah, I doubt there are any speed benefits here. Your `numpy.ndarray` will require an `object` dtype, which is pretty much a less useful python `list`
type: QuestionComment

http://stackoverflow.com/q/48640959
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52241152
type: UnansweredQuestion
has title: No root path can be found for the provided module "builtins" in Flask
downvote count: 0
tagged with: python
upvote count: 7
tagged with: flask
has body: I have python3.5.2 as my default python and i installed flask. Then i wrote a basic flaskapp.py to try and i have encountered this error: RuntimeError: No root path can be found for the provided module "builtins". This can happen because the module came from an import hook that does not provide file name information or because it's a namespace package. In this case the root path needs to be explicitly provided. Here is my flaskapp.py: from flask import Flask from flask import request,render_template app = Flask(__name__) @app.route('/') def home(): return render_template('pages/pages/home/home.html') if __name__ == '__main__' : app.run() Traceback: Traceback (most recent call last): File "&lt;input&gt;", line 6, in &lt;module&gt; File "C:\....\flask\app.py", line 345, in init root_path=root_path) File "C:\...\flask\helpers.py", line 843, in init root_path = get_root_path(self.import_name) File "C:\...\flask\helpers.py", line 721, in get_root_path 'provided.' % import_name) RuntimeError:
score: 7
has answer: http://stackoverflow.com/a/49426867
favorite count: 0

http://stackoverflow.com/q/48520877
type: UnansweredQuestion
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/48522029
has body: I'm newbie python programmer here I suppose. I want to extract only the related keywords if we were given any list/array in python. Ex: Extract only food related words in a list of strings A user for example can input a list. [0] I want to buy some apple. [1] Oranges are good for the health. [2] I bought 2 blueberries yesterday. [3] John is eating some grapes. [4] My crush did not like me back. Expected output would be: [0] apple [1] oranges [2] blueberries [3] grapes [4] None I would appreciate if anyone could point out to me how I could achieve something like this. I'm still new to programming and found out how to extract words recently but ONLY if I have a list of categorized food for reference. I could just compare and extract Yaayyy!! :D But assuming that the user can input any items he/she wants, how would I go about approaching a solution for this? Would it be practical to copy all the foods in the whole world and store them in a list for reference? I've looking for a solution. Maybe I might have missed it for some reason. If anyone could point me to a link or topic that would be great if this is a duplicate! Btw a shoutout and thank you to all the people in StackOverFlow really helped me a lot! :)
upvote count: 0
downvote count: 2
has title: Extract a specific words from a list of strings using Python
has comment: http://stackoverflow.com/comment/84038395
has answer: http://stackoverflow.com/a/48522092
tagged with: string
has comment: http://stackoverflow.com/comment/84038248
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84047550
linked to: http://stackoverflow.com/q/19626737
has comment: http://stackoverflow.com/comment/84036447
answer count: 2
tagged with: extract

http://stackoverflow.com/comment/84274613
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48638398
has text: Might be interesting: `np.float64.__round__ == np.float32.__round__` and `np.float.__round__ == float.__round__` **but** `np.float64.__round__ != float.__round__`! Thus, `round(a)` and `round(np.float64(a))` are executing different code.
type: Comment

http://stackoverflow.com/comment/84214604
comment on: http://stackoverflow.com/a/48604817
score: 1
has text: Thank you har07 - for the solution and the back ground Infos. People like you make stack overflow to what it is. Happy weekend
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48566333
score: 0
has comment: http://stackoverflow.com/comment/84150479
has body: I have a df that looks like this: Time_Start CODE time 0 2018-01-31 16:45:04.263 B76 2018-01-31 16:48:06 1 2018-01-31 16:10:26.000 974 2018-01-31 16:50:06 I am subtracting time from Time_Start. For the second one I get 39:49 which is the expected output but for the first one I get a number like 2.737000 (not what I want). Time_Start is datetime64[ns] and time is object. This is how I am doing the conversion and subtracting: waiting['time'] = pd.to_datetime(waiting['time']) waiting['Duration'] = waiting['time'] - waiting['Time_Start'] waiting['Duration'] = waiting['Duration'].apply(lambda x: str(x)[-8:]) I am rather new to python so can someone tell me what am I doing wrong and why I am getting the 2 different outputs? I am using python 2.x. Full code: query that returns the dataframe ....... end_time = np_server_date.ix[0]['data'] """current time""" end_time = end_time.strftime('%Y-%m-%d %H:%M:%S') waiting['time'] = end_time """it's now the current time""" waiting['time'] = pd.to_datetime(waiting['time']) waiting['Duration'] = waiting['time'] - waiting['Time_Start'] waiting['Duration'] = waiting['Duration'].apply(lambda x: str(x)[-8:])
has comment: http://stackoverflow.com/comment/84129073
answer count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84170360
has comment: http://stackoverflow.com/comment/84206933
accepted answer: http://stackoverflow.com/a/48630184
tagged with: python
has answer: http://stackoverflow.com/a/48630184
has comment: http://stackoverflow.com/comment/84150446
has title: Python subtracting with time format

http://stackoverflow.com/a/48530947
has body: Change: psw = line.strip()("\n") To psw = line.strip("\n") Note, line.strip() returns a string which you then try to call, so it's something like: &gt;&gt;&gt; "I'm a string"() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'str' object is not callable Or perhaps more clearly: &gt;&gt;&gt; string_object = "I'm a string" &gt;&gt;&gt; string_object() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'str' object is not callable
score: 3
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48530930

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

http://stackoverflow.com/comment/84182171
comment on: http://stackoverflow.com/q/48591722
score: 0
has text: This is still not a [MCVE]. You claim `split[0]` doesn't work while `split0`, created with (if I'm reading correctly) `split0 = split[0]` works, but in the code as written, that's impossible. Using `split[0]` would be exactly equivalent, so what you've provided isn't reproducible by anyone.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48721286
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89309762
has body: The height of alls row can be modified with this code. root = Tk() style = ttk.Style(root) style.configure('Treeview', rowheight=45) It would be very nice to know if each row in a Treeview can have it's own style to defined individual rowheight (depending on newline characters).
type: Answer
answers question: http://stackoverflow.com/q/48597830
downvote count: 0

http://stackoverflow.com/comment/83997712
score: 0
type: Comment
type: QuestionComment
has text: I'm not a downvoter, but I think you could improve the question by providing a better explanation of what you are computing (even though we can, in principle, figure it out from the code, assuming the code is correct). Saying "... the index of the middle value sum(x)/2 of an array x" doesn't quite match what the code is doing. For the example you show, `sum(x)/2` is 117.5, and that value does not show up in `x`, so what does it mean to find the index of that value?
comment on: http://stackoverflow.com/q/48501465

http://stackoverflow.com/comment/84058362
comment on: http://stackoverflow.com/q/48531422
type: QuestionComment
score: 0
has text: client is on linux ....
type: Comment

http://stackoverflow.com/q/48551557
tagged with: loss-function
tagged with: python
has body: I have build a model using the low-level tensorflow API that has only a couple of variables (about 10) that I want to optimize. Therefore I want to implement a custom loss function that produces noisy loss values (kind of like a simulation based optimization approach). Usually I would a derivative free optimizer like the SPSA optimizer. Is there a way to implement a loss function that is not differentiable and an optimizer like SPSA with the low-level tensorflow API? PS: One might ask why use tensorflow for this? This is because I want to use tensorflow for convenient saving of the model and tensorboard for convenient and comprehensive visualization. Also I want to be able to switch and compare different models in a standardized framework.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55039917
accepted answer: http://stackoverflow.com/a/55039917
downvote count: 0
answer count: 1
tagged with: tensorflow
tagged with: optimization
type: AnsweredQuestion
upvote count: 3
score: 3
has title: Custom Tensorflow optimizer for noisy non-differentiable loss function

http://stackoverflow.com/comment/84240917
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48622150
has text: @astro No problem. I've posted it as an answer, below.

http://stackoverflow.com/comment/84194335
type: Comment
comment on: http://stackoverflow.com/q/48595792
type: QuestionComment
has text: Look at the answer from alien_frog for how to close a tab.
score: 0

http://stackoverflow.com/q/48574743
has comment: http://stackoverflow.com/comment/84146233
downvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48574810
favorite count: 0
type: Question
upvote count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84146247
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84146205
answer count: 1
has body: I have a list of numbers, i'm supposed to find the largest number in that list and output its index, not the actual value. the list is called numbers. this is what i have: N = 0 for i in numbers: if i &gt; N: N=i for N in numbers: print (numbers.index[N]) this returns this error TypeError: 'builtin_function_or_method' object is not subscriptable I would prefer not use the 'max' function. the code will return the largest number, how do i get it to return the index?
has title: finding index for a specific number in python

http://stackoverflow.com/a/48595438
accepted answer of: http://stackoverflow.com/q/48575815
has body: It's interesting to think about simulating a systolic array in Python, but I think there are some significant difficulties in doing this along the lines you've sketched out above. Most importantly there are the issues about Python's limited scope for true parallelism caused by the Global Interpreter Lock. This means that you won't get any significant parallelism for compute-limited tasks, and its threads are probably best suited to handling I/O limited tasks such as web-requests or filesystem accesses. The nearest Python can get to this is probably via the multiprocessing module, but that would require separate process for each node. Secondly, even if you were going to get parallelism in the numerical operations within your systolic array, you'd need to have some locking mechanisms to allow different threads to exchange data (or messages) without corrupting each other's memory when they try to read and write data at the same time. As regards the datastructures in your example, I think you might be better off having each node in the systolic array having a reference to its upstream nodes, rather than knowing that it lies at a particular location in an NxM grid. I don't think there's any reason why a systolic array needs to be a rectangular grid, and any from of Directed Acyclic Graph (DAG) would still have the potential for efficient distributed computation. Overall, I'd expect the computational overheads of doing this simulation in Python to be enormous relative to what could be achieved by lower-level languages such as Scala or C++. Even then, unless each node in the systolic array is doing a lot of computation (i.e. much more than a few multiply-adds), then the overheads of exchanging messages between nodes will be substantial. So, I presume your simulation is mainly to get an understanding of the data flows, and the high-level behaviour of the array, rather than to get anywhere close to what could be provided by custom DSP (Digital Signal Processing) hardware. If…
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84217925
answers question: http://stackoverflow.com/q/48575815
type: Answer

http://stackoverflow.com/q/48581648
answer count: 3
downvote count: 0
has body: I have installed apache-airflow (version v1.9.0) along with python 2.7. To test whether its installed properly I tried to trigger a tutorial DAG from the interactive view in browser. The interface shows that the DAG is running, but the scheduler doesn't show any activity. Below are the steps I tried Install airflow pip install apache-airflow Install crypto for setting encryption using fernet key pip install apache-airflow[crypto] Generate a fernet_key and add in airflow.cfg file: from cryptography.fernet import Fernet fernet_key= Fernet.generate_key() print(fernet_key) Initialise a airflow sqlite db airflow initdb Start the airflow webserver airflow webserver -p 8080 Start the airflow scheduler in a different window airflow scheduler Trigger the tutotial DAG on the Airflow page at localhost:8080 After following these steps, I am not able to see any movement in my scheduler window, which just keeps me showing INFO - Heartbeating the process manager INFO - Heartbeating the executor I have tried it running in the local environment as well as in a virtual environment. I have also tried running through SequentialExecutor and LocalExecutor the task is not triggered even when I try to trigger it through the terminal by airflow trigger_dag tutorial I am working on mac OS High Sierra Version 10.13.3
has comment: http://stackoverflow.com/comment/88488312
has answer: http://stackoverflow.com/a/58447354
favorite count: 0
tagged with: macos-high-sierra
type: Question
has comment: http://stackoverflow.com/comment/93967604
tagged with: airflow
has comment: http://stackoverflow.com/comment/88488260
type: UnansweredQuestion
tagged with: python
has title: Apache Airflow not scheduling tasks
tagged with: airflow-scheduler
upvote count: 6
score: 6
tagged with: python-2.7
has answer: http://stackoverflow.com/a/59327275
has answer: http://stackoverflow.com/a/57541445

http://stackoverflow.com/comment/84393072
type: Comment
score: 0
has text: Not that I know of, here is [a good idea](https://stackoverflow.com/questions/30647844/how-to-automate-amazon-aws-ec2-for-scraping) though.
type: QuestionComment
comment on: http://stackoverflow.com/q/48614548

http://stackoverflow.com/q/48613151
has answer: http://stackoverflow.com/a/48613514
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48812198
has body: I wrote some code to build my own EMA/MACD, but have decided to give Pandas a try instead. I am using this website below as a basic understanding of EMA and trying to get pandas to give me the same answers to be sure I am using pandas correctly: http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages And here is the chart with the data that Im working with. Here is the code I'm trying to get to work, but it gives me different output than the 10-day EMA column import pandas as pd data=[22.27,22.19,22.08,22.17,22.18,22.13,22.23,22.43,22.24,22.29,22.15,22.39,22.38,22.61,23.36,24.05,23.75,23.83] df=pd.Series(data) pd.ewma(df, span=10) I've also tried this with no luck. pd.ewma(df, span=10, min_periods=10) Any help is appreciated.
tagged with: pandas
score: 3
upvote count: 3
has title: Simple Python Pandas EMA (ewma)?
downvote count: 0
has answer: http://stackoverflow.com/a/49920803
favorite count: 0
has comment: http://stackoverflow.com/comment/84223696
type: Question
linked to: http://stackoverflow.com/q/37924377
answer count: 2

http://stackoverflow.com/comment/84110259
has text: @eryksun your recommendation as along the lines with the third solution from my list, except that it's 'r+b', and you need to write bytes to file, not string. I myself was hoping that it is the right way to go, and indeed managed to establish communication with a named pipe this way. My previous mistake with it was that I sent ascii control codes the wrong way.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48542644

http://stackoverflow.com/comment/84273853
score: 1
type: QuestionComment
type: Comment
has text: @Ev.Kounis - It looks like the description is wrong, it states it wants to print hi if the user *doesn't* type in one of those numbers
comment on: http://stackoverflow.com/q/48638720

http://stackoverflow.com/a/48530649
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84105425
has body: You could just do variable = int(variable + 1)
answers question: http://stackoverflow.com/q/48530585
type: Answer

http://stackoverflow.com/q/48632372
answer count: 0
has title: Python: Non Maximum Suppression
downvote count: 0
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I'm currently looking for a 3D Non Maximum Suppression Filter. Is there anything like this? There is a cannyEdgeDetection Filter in sitk, which should include the non maximum suppression, but I need it as standalone. EDIT: I found this 2D implementation of NonMaximumSuppression but I don't know how to do it in 3D: def gradient(im): # Sobel operator op1 = np.array([[-1, 0, 1],[-2, 0, 2],[-1, 0, 1]]) op2 = np.array([[-1, -2, -1],[ 0, 0, 0],[ 1, 2, 1]]) kernel1 = np.zeros(im.shape) kernel1[:op1.shape[0], :op1.shape[1]] = op1 kernel1 = np.fft.fft2(kernel1) kernel2 = np.zeros(im.shape) kernel2[:op2.shape[0], :op2.shape[1]] = op2 kernel2 = np.fft.fft2(kernel2) fim = np.fft.fft2(im) Gx = np.real(np.fft.ifft2(kernel1 * fim)).astype(float) Gy = np.real(np.fft.ifft2(kernel2 * fim)).astype(float) G = np.sqrt(Gx**2 + Gy**2) Theta = np.arctan(Gy, Gx) * 180 / np.pi return G, Theta def nonMaximumSuppression(image): det, phase = self.gradient(image) gmax = np.zeros(det.shape) for i in range(gmax.shape[0]): for j in range(gmax.shape[1]): if phase[i][j] &lt; 0: phase[i][j] += 360 if ((j+1) &lt; gmax.shape[1]) and ((j-1) &gt;= 0) and ((i+1) &lt; gmax.shape[0]) and ((i-1) &gt;= 0): # 0 degrees if (phase[i][j] &gt;= 337.5 or phase[i][j] &lt; 22.5) or (phase[i][j] &gt;= 157.5 and phase[i][j] &lt; 202.5): if det[i][j] &gt;= det[i][j + 1] and det[i][j] &gt;= det[i][j - 1]: gmax[i][j] = det[i][j] # 45 degrees if (phase[i][j] &gt;= 22.5 and phase[i][j] &lt; 67.5) or (phase[i][j] &gt;= 202.5 and phase[i][j] &lt; 247.5): if det[i][j] &gt;= det[i - 1][j + 1] and det[i][j] &gt;= det[i + 1][j - 1]: gmax[i][j] = det[i][j] # 90 degrees if (phase[i][j] &gt;= 67.5 and phase[i][j] &lt; 112.5) or (phase[i][j] &gt;= 247.5 and phase[i][j] &lt; 292.5): if det[i][j] &gt;= det[i - 1][j] and det[i][j] &gt;= det[i + 1][j]: gmax[i][j] = det[i][j] # 135 degrees if (phase[i][j] &gt;= 112.5 and phase[i][j] &lt; 157.5) or (phase[i][j] &gt;= 292.5 and phase[i][j] &lt; 337.5): if det[i][j] &gt;= det[i - 1][j - 1] an…
score: 2
tagged with: itk

http://stackoverflow.com/comment/84052529
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48528206
has text: But are they symlinks? Or just plain subdirectories?
score: 0

http://stackoverflow.com/a/48614090
accepted answer of: http://stackoverflow.com/q/48613865
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48613865
has body: I think you should use 'r+' mode. ‘r+’ is special read and write mode, which is used to handle both actions when working with a file. Try something like this: with open("file.txt", "r+") as f: d = f.read() print d f.seek(0) f.write("some data") f.truncate()
type: Answer

http://stackoverflow.com/q/48532844
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84061937
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48532857
upvote count: 0
type: UnansweredQuestion
has body: I have a DataFrame, where I want to apply filter in first column and then replace a number in 6th column with np.nan. I also want to do these changes without taking the filter out of DataFrame. because I want the changes to be part of same DataFrame. For example. if ID=1, I want to replace "f" with np.nan
has title: Conditional Substitution-Python
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/31511997
tagged with: conditional-statements
tagged with: pandas

http://stackoverflow.com/comment/84098948
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48549204
has text: If you don't want "BANANA" substituted for, then why would you substitute in #1?

http://stackoverflow.com/comment/84195006
has text: in this method def test_login(self): Login.with_("username", "password") assert Login.login_succesfull_()
score: 0
comment on: http://stackoverflow.com/q/48599095
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83990743
type: Comment
type: QuestionComment
has text: Can you put your `index.html` here ?
comment on: http://stackoverflow.com/q/48498668
score: 0

http://stackoverflow.com/q/48552406
tagged with: python
has comment: http://stackoverflow.com/comment/84101196
has title: How to use pandas isin() with IF statement
has comment: http://stackoverflow.com/comment/84101548
score: 0
has comment: http://stackoverflow.com/comment/84101296
tagged with: pandas
has answer: http://stackoverflow.com/a/48552544
answer count: 1
has body: I have a column(INT_STATUS) in a data frame(file1) and INT_STATUS has values from A to Z and 1 to 9. If INT_STATUS columns has values in this list ['B','C','F','H','P','R','T','X','Z','8','9'] then I want to create a new column "rcut" and give a value '01' file1['rcut'] == '01'.
type: Question
tagged with: if-statement
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84101232

http://stackoverflow.com/a/48629022
accepted answer of: http://stackoverflow.com/q/48625353
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/84285598
answers question: http://stackoverflow.com/q/48625353
has body: Indeed, TPOT is supposed to work with multiclass data, too - the example in the docs is with the MNIST dataset (10 classes). The error is related to the f1_score; keeping your code with n_classes=3, and asking for tpot = TPOTClassifier(generations=10, population_size=20, verbosity=2) (i.e. using the default scoring='accuracy') works OK: Warning: xgboost.XGBClassifier is not available and will not be used by TPOT. Generation 1 - Current best internal CV score: 0.7447422496202984 Generation 2 - Current best internal CV score: 0.7447422496202984 Generation 3 - Current best internal CV score: 0.7454927186634503 Generation 4 - Current best internal CV score: 0.7454927186634503 Generation 5 - Current best internal CV score: 0.7706334316090413 Generation 6 - Current best internal CV score: 0.7706334316090413 Generation 7 - Current best internal CV score: 0.7706334316090413 Generation 8 - Current best internal CV score: 0.7706334316090413 Generation 9 - Current best internal CV score: 0.7757616367372464 Generation 10 - Current best internal CV score: 0.7808898418654516 Best pipeline: LogisticRegression(KNeighborsClassifier(DecisionTreeClassifier(input_matrix, criterion=entropy, max_depth=3, min_samples_leaf=15, min_samples_split=12), n_neighbors=6, p=2, weights=uniform), C=0.01, dual=False, penalty=l2) TPOTClassifier(config_dict={'sklearn.linear_model.LogisticRegression': {'penalty': ['l1', 'l2'], 'C': [0.0001, 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'dual': [True, False]}, 'sklearn.decomposition.PCA': {'iterated_power': range(1, 11), 'svd_solver': ['randomized']}, 'sklearn.feature_selection.Se...ocessing.PolynomialFeatures': {'degree': [2], 'interaction_only': [False], 'include_bias': [False]}}, crossover_rate=0.1, cv=5, disable_update_check=False, early_stop=None, generations=10, max_eval_time_mins=5, max_time_mins=None, memory=None, mutation_rate=0.9, n_jobs=1, offspring_size=20, periodic_checkpoint_folder=None, population_size=20, random_state=None, sc…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84286961
score: 5

http://stackoverflow.com/q/48603517
tagged with: python
tagged with: qtableview
has body: The code below creates a single dialog with a QTableView view. On left-click the onLeftClickfunction gets an QModelIndex index. This QModelIndex is used later to print the row and column numbers of the left-clicked cell. How to get the QModelIndex index of the cell that was right-clicked? from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * app = QApplication([]) class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setLayout(QVBoxLayout()) self.view = QTableView(self) self.view.setSelectionBehavior(QTableWidget.SelectRows) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect(self.onRightClick) self.view.clicked.connect(self.onLeftClick) self.view.setModel(QStandardItemModel(4, 4)) for each in [(row, col, QStandardItem('item %s_%s' % (row, col))) for row in range(4) for col in range(4)]: self.view.model().setItem(*each) self.layout().addWidget(self.view) self.resize(500, 250) self.show() def onRightClick(self, qPoint): sender = self.sender() for index in self.view.selectedIndexes(): print 'onRightClick selected index.row: %s, selected index.column: %s' % (index.row(), index.column()) def onLeftClick(self, index): print 'onClick index.row: %s, index.row: %s' % (index.row(), index.column()) dialog = Dialog() app.exec_()
has answer: http://stackoverflow.com/a/48603641
score: 2
type: AnsweredQuestion
has title: How to get QTableView right clicked index
tagged with: pyqt
answer count: 1
downvote count: 0
tagged with: pyqt5
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/48603641

http://stackoverflow.com/q/48635810
type: Question
has answer: http://stackoverflow.com/a/48635838
has body: I read in a Dataframe from a CSV file df = pd.read_csv("data.csv") df Match teamA teamB 0 3 2 1 4 3 2 2 4 3 4 2 4 3 4 Now I want only row 0,1,3 because those are the rows that teamA won. I want to know how I can take these rows and easily put them into a new DF. like newdf = df(row0,row1,row3) Match teamA teamB 0 3 2 1 4 3 3 4 2 EDIT: I need a solution that can work in all cases. Not just inequality arguments. I used this as a crude example but I need to grab specific arbitrary rows that otherwise have no relation to each other, etc.
upvote count: 1
tagged with: python
has title: How to append arbitrary rows into a new data frame in pandas python?
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/48635838
favorite count: 0

http://stackoverflow.com/q/48645846
tagged with: xgboost
has answer: http://stackoverflow.com/a/69504092
favorite count: 0
upvote count: 17
has answer: http://stackoverflow.com/a/50633571
has comment: http://stackoverflow.com/comment/84324017
has comment: http://stackoverflow.com/comment/84318165
type: Question
has answer: http://stackoverflow.com/a/56211072
tagged with: pandas
has answer: http://stackoverflow.com/a/76502713
tagged with: python
answer count: 5
score: 17
tagged with: numpy
possible better answer: http://stackoverflow.com/a/56211072
has title: Python's Xgoost: ValueError('feature_names may not contain [, ] or <')
has comment: http://stackoverflow.com/comment/84324268
has answer: http://stackoverflow.com/a/76768191
type: AnsweredQuestion
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50633571
has body: Python's implementation of XGBClassifier does not accept the characters [, ] or &lt;' as features names. If that occurs, it raises the following: ValueError('feature_names may not contain [, ] or &lt;') It would seem that the obvious solution would be to pass the equivalent numpy arrays, and get rid of the column names altogether, but if they haven't done it that must be for a reason. What use does XGBoost have for the feature names, and what is the downside of simply passing it Numpy Arrays instead of Pandas DataFrames? Edit: this is not a question about workarounds (those are obvious and in the question), but about why it is implemented this way

http://stackoverflow.com/q/48585637
favorite count: 0
has answer: http://stackoverflow.com/a/48586265
has comment: http://stackoverflow.com/comment/84169313
tagged with: beautifulsoup
tagged with: lxml
score: 1
tagged with: python
has title: Beautifulsoup how to parse h2 and underlying h3
type: Question
tagged with: python-3.x
has body: I'm new (started this afternoon) to parsing lxml so bear with me. I'm trying to parse a csv with super hero data with lxml markup with beautiful soup. I want to get the text inside of two h2 tags Powers and Abilities & Weapons and Equipment soup.find_all("h2") >> [ Origin , Creation , Character Evolution , Major Story Arcs , Powers and Abilities , Weapons and Equipment , Character Profile , Alternate Realities , Other Media , Merchandising , Depiction and the Iconic Costume , Popular Recognition ] when I look at the next sibling of h2 (the text is in a h3 tag) for Weapons and equipment I only get one item something back (should be more). And when I change the header.text to Weapons and Equipment I get no results. for header in soup.find_all('h2'): if header.text == "Weapons and Equipment": nextNode = header.nextSibling print(nextNode.text) if nextNode is None: break >> Lasso of Truth The Powers and Abilities + Weapons do show up in the findall('h3') results (together with other stuff that I do not want) soup.find_all("h3", text=True) >> [ Challenge of the Gods , First clash with Circe , The New 52 , Meeting Zeus Other Children , Meeting First Born , Superhuman Strength , Superhuman Speed , Invulnerability/Durability , Flight , Healing Factor , Divine Wisdom , Super Stamina/Agility , Great Beauty , Enhanced Sense , Other Assorted Divine Powers , God of War Powers , Martial Combat , Lasso of Truth , Bracelets of Victory , Royal Tiara , The Invisible Plane , Battle Armour , Martial Weapons , Magical Sword , Sandals of Hermes , Gauntlet of Atlas , Earrings , Power Rings , War suits (or uniform) , The Dark Knight Strikes Again ] I've been reading documentation the whole afternoon but haven't found examples that can help me. I really don't know how I should get these items. Help and explanation would be appreciated. snippet of data h2>Powers And Abilities Reality Manipulation - Wanda possesses the ability to manipulate reality based on how hard she "wonders". The full ext…
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84170065
answer count: 1
has comment: http://stackoverflow.com/comment/84169572
has comment: http://stackoverflow.com/comment/84168795
downvote count: 1

http://stackoverflow.com/a/48550468
has comment: http://stackoverflow.com/comment/84115469
has comment: http://stackoverflow.com/comment/84115266
has comment: http://stackoverflow.com/comment/84115182
type: Answer
answers question: http://stackoverflow.com/q/48549421
has comment: http://stackoverflow.com/comment/84106553
accepted answer of: http://stackoverflow.com/q/48549421
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84107447
has comment: http://stackoverflow.com/comment/84115510
upvote count: 1
has body: This is not like a Django error, this is a Basic Python OOP error!!. In Python class method(non-static), you have to invoke the first argument as self. So in forms.py. from django import forms class HomeForm(forms.Form): quantity1 = forms.IntegerField(required = False) quantity2 = forms.IntegerField(required = False) def multiply_two_integers(self, x, y): return x*y def return_product(self): return self.multiply_two_integers(self.quantity1, self.quantity2) or you can also make the multiply_two_integers as a staticmethod by simply decorating this method from django import forms class HomeForm(forms.Form): quantity1 = forms.IntegerField(required = False) quantity2 = forms.IntegerField(required = False) @staticmethod def multiply_two_integers(x, y): return x*y def return_product(self): return self.multiply_two_integers(self.quantity1, self.quantity2) And additionally, I want to suggest that, do not make these methods(multiply_two_integers and return_product) in forms, rather make these forms in views instead. Just fetch the form value by request.POST['field']
has comment: http://stackoverflow.com/comment/84115466
has comment: http://stackoverflow.com/comment/84115262

http://stackoverflow.com/comment/84067663
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48536061
has text: there is no way Python will be returning you "30.7...." for `41.72104029, 39.29410479, and 39.24708382`. Probably your lists are of different sizes and you are checking the last index of the list. Please check at the specific index

http://stackoverflow.com/comment/84033618
comment on: http://stackoverflow.com/q/48519001
has text: `alias python=/usr/local/bin/python3`fixed the issue...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84161090
type: Comment
comment on: http://stackoverflow.com/a/48574300
type: AnswerComment
has text: Ok, the setData I fixed... simple thing. I forgot to add the if role == Qt.BackgroundRole in the model setdata... my bad. now trying to fix the color display.
score: 0

http://stackoverflow.com/q/48633650
has comment: http://stackoverflow.com/comment/84266564
favorite count: 0
type: Question
has body: So, I have a python program with a class and logger. Here is the code: import logging path2log = "logs/1.pylog" LOG_FORMAT = "%(levelname)s - %(name)s (%(asctime)s) : %(message)s" #existing log levels are: #Debug #Info #Warning #Error #Critical logging.basicConfig(filename = path2log, level = logging.DEBUG, format = LOG_FORMAT) logger = logging.getLogger("1.py.logger 'CONSOLE'") class Emperor(): try: def __init__(self, name, famname, level): try: self.name = name self.famname = famname self.level = level try: logger.info("Emperor created with name:") logger.info(self.name) logger.info("family name:") logger.info(self.famname) logger.info("and level:") logger.info(self.level) except TypeError: logger.error("Missing perameter creating object in emperor class") except TypeError: logger.error("Missing perameter creating object in emperor class.") except TypeError: logger.error("Missing perameter creating object in emperor class.") But all of the excepts in the def init area don't do anything. I still get the error when running the program. How do I fix this? Edit: Here is the error:
has title: Except isnt working in my python 3.6 program. Why?
downvote count: 0
upvote count: 1
tagged with: python
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/84264463
accepted answer: http://stackoverflow.com/a/48636495
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48636495
has comment: http://stackoverflow.com/comment/84264377
tagged with: exception
score: 1
has comment: http://stackoverflow.com/comment/84264555
answer count: 1
has comment: http://stackoverflow.com/comment/84266320

http://stackoverflow.com/a/48510563
accepted answer of: http://stackoverflow.com/q/48510405
upvote count: 1
score: 1
type: AcceptedAnswer
has body: One approach is to use apply(): import pandas as pd BRANDS = ['Samsung', 'Apple', 'Nike'] def get_brand_name(row): if ~pd.isnull(row['brand_name']): # don't do anything if brand_name is not null return row['brand_name'] item_title = row['item_title'] title_words = map(str.title, item_title.split()) for tw in title_words: if tw in BRANDS: # return first 'match' return tw # default return None return None df['brand_name'] = df.apply(lambda x: get_brand_name(x), axis=1) print(df) # row item_title brand_name #0 1 Apple 6S Apple #1 2 Nike BB Shoes Nike #2 3 Samsung TV Samsung #3 4 Used bike None Notes I converted the tokenized title to title-case using str.title() because that's how you defined BRANDS. If you have a lot of brands, it's recommended to use a set instead of a list because lookups will be faster. However, this won't work if you care about order.
type: Answer
answers question: http://stackoverflow.com/q/48510405
downvote count: 0

http://stackoverflow.com/a/48491179
answers question: http://stackoverflow.com/q/48491073
type: Answer
accepted answer of: http://stackoverflow.com/q/48491073
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83975501
has comment: http://stackoverflow.com/comment/83976394
has comment: http://stackoverflow.com/comment/83976624
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83976538
has body: This list comprehension should do what you want: [li for li in my_list if not any(wi in li[0].split() for wi in remove_from_list)] This yields [[u'Int2 Paris A disconnected'], [u'Port3 Paris A Backup disabled']] It uses the idea you mentioned: splitting the entry and then checking whether any of the words is included in the resulting list using any. Some more explanation: [li[0].split() for li in my_list] yields [[u'Port', u'Name', u'Status'], [u'Int1', u'London', u'connected'], [u'Int2', u'Paris', u'A', u'disconnected'], [u'Port3', u'Paris', u'A', u'Backup', u'disabled']] That's a new list of lists which we created in a list comprehension; each string is split resulting in a list of single words. Now we have to check whether any of the desired strings are in these sublists which we can do by another list comprehension: [wi in [u'Port', u'Name', u'Status'] for wi in remove_from_list] [True, False] This list comprehension returns a list with Boolean variables stating whether the elements in remove_from_list were found. A quick way to check whether this list contains at least one element equal to True is to use any: any([True, False]) True and any([False, False]) False Now we can combine these to list comprehensions to expression in the beginning which leaves us with the desired outcome. One addition, if you want to split based on a regular expression, you can do the following: import re [re.split('\s{2,}', li[0]) for li in my_list] which gives [[u'Port', u'Name', u'Status'], [u'Int1', u'London', u'connected'], [u'Int2', u'Paris A', u'disconnected'], [u'Port3', u'Paris A Backup', u'disabled']] Difference to above is that you now always end up with only three strings per sublist as you now split only at at least two white spaces. I think that's what you had in mind originally; in your case it does not make a difference as remove_from_list contains only single words but if the strings in remove_from_list contained whitespaces the first approach would fail: then you shou…

http://stackoverflow.com/comment/84084245
type: Comment
comment on: http://stackoverflow.com/q/48538847
score: 0
type: QuestionComment
has text: Your log line complains about 1 second. So why are minutes OK now?

http://stackoverflow.com/comment/84089346
type: Comment
has text: Thanks! Sorry I meant global array named "global order" different from the "order" without the global indicator in the main function. But, I guess it is. Thanks so much!!!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48546673

http://stackoverflow.com/comment/84135673
type: Comment
type: QuestionComment
score: 0
has text: @internet_user maybe my explanations are bad. I do not need the algorithm here. I just need a way to properly invalidate some 'bad' values, like '8' in my example, but I cannot simply assign [7, 9] as it requires array of size 3 here.
comment on: http://stackoverflow.com/q/48569301

http://stackoverflow.com/comment/84177579
score: 0
type: Comment
type: QuestionComment
has text: i added the main function to the end of the script to call the init() but i get this error : `can't load package: package .: ` `main.go:1:2: expected 'package', found 'EOF'`
comment on: http://stackoverflow.com/q/48589653

http://stackoverflow.com/q/48511684
has comment: http://stackoverflow.com/comment/84018323
type: AnsweredQuestion
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/84018245
upvote count: 1
has answer: http://stackoverflow.com/a/48511879
has comment: http://stackoverflow.com/comment/84018301
has comment: http://stackoverflow.com/comment/84018356
has comment: http://stackoverflow.com/comment/84018413
has comment: http://stackoverflow.com/comment/84018246
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84018487
has body: Can we put a print in a method of class? (PEP8) I know it is better to make a return. But I have to turn a big python file into a class ... class Test: def __init__(self,name): self.name = name self.r = str def tester(self): print('hello') print(self.name) r = Test('pascal') r.tester()
has comment: http://stackoverflow.com/comment/84018414
has title: Put a print in a method?
accepted answer: http://stackoverflow.com/a/48511879
downvote count: 5
tagged with: python
score: -4

http://stackoverflow.com/a/48626407
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48625383
has body: Your PNG file is a palette-mapped image, so the numbers you get from pix[x, y] are palette numbers, not RGB tuples. That is, the image is in 'P' mode, not 'RGB mode'.You could convert the image to 24 bit RGB mode, eg by doing im = im.convert('RGB') but when you save the results to a file it will take up more space. Although PNG supports a variety of palette sizes up to 256 colors, PIL expects palettes to contain exactly 256 colors. Currently, PIL thinks that image's palette is White, Blue, Black, followed by 253 default grey values. To draw on the image in another color, you need to first add that color to the palette. Here's a short demo. from PIL import Image im = Image.open("grid.png") pal = im.getpalette() # Set palette number 3 color to red palnum = 3 pal[3*palnum:3*palnum+3] = 255, 0, 0 # Attach new palette to image im.putpalette(pal) pix = im.load() # Draw a red rectangle on image, pixel by pixel lox, hix = 50, 100 loy, hiy = 100, 150 for y in range(loy, hiy): for x in range(lox, hix): pix[x, y] = palnum im.show() im.save("new_grid.png") output PIL saved the above image in 'P' mode, but with a 256 color palette; I passed it through optipng to optimize the palette to 4 colors, and to improve the compression.
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48625383
upvote count: 1
score: 1

http://stackoverflow.com/a/48598819
has comment: http://stackoverflow.com/comment/84199846
has comment: http://stackoverflow.com/comment/84194126
has body: So, python has a very convenient dictionary subclass called Counter, that in essence, is very fast at calculating counts. I crafted the following: import random from collections import Counter prob = Counter([random.randint(1,6) for _ in range(10000)]) print(prob) &gt;&gt; Counter({1: 1650, 2: 1750, 3: 1679, 4: 1546, 5: 1686, 6: 1689}) Now, the problem with that is that it can only work up to a reasonable large range. So, in order to avoid creating an intermediate list, we can have the following: import random from collections import Counter prob = Counter() for _ in range(10000000): prob[random.randint(1,6)] += 1 print(prob) &gt;&gt; Counter({1: 13084052, 2: 13087518, 3: 13090177, 4: 13086193, 5: 13081778, 6: 13085341}) edit: Adding a third version, which is basically the first, giving up the intermediate list for the much more convenient generator, as @Mark Dickinson suggested: import random from collections import Counter prob = Counter(random.randint(1,6) for _ in range(1000000)) print(prob) &gt;&gt; Counter({1: 166503, 2: 166833, 3: 166531, 4: 166681, 5: 166846, 6: 166606})
answers question: http://stackoverflow.com/q/48598645
has comment: http://stackoverflow.com/comment/84199816
has comment: http://stackoverflow.com/comment/84194141
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/84005707
score: 1
type: Comment
type: QuestionComment
has text: Are you expecting to be able to write Python without even having learnt the first thing about it? Start withe the link in@Zack Tarr's comment.
comment on: http://stackoverflow.com/q/48505498

http://stackoverflow.com/q/48513591
tagged with: python
has answer: http://stackoverflow.com/a/48513612
accepted answer: http://stackoverflow.com/a/48513612
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: macos
tagged with: xgboost
has body: I have a MacBook Pro and successfully installed xgboost on it. If I start a Python shell in ~/xgboost/python-package I can easily import xgboost by running the command: import xgboost But if I go to some other folder, start the python shell and run the above command I get the following error: ImportError: No module named xgboost I am guessing this is related to $PATH. How can I fix it? Thanks.
tagged with: import
type: Question
tagged with: linux
has title: How to define path to import python library

http://stackoverflow.com/a/48529000
has comment: http://stackoverflow.com/comment/84054486
has comment: http://stackoverflow.com/comment/84055132
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48528848
type: Answer
has body: It calls that function with no arguments. – (Oliver Charlesworth)
score: 1

http://stackoverflow.com/comment/84085297
comment on: http://stackoverflow.com/q/48544692
type: QuestionComment
has text: Why don't you do it while reading?
type: Comment
score: 0

http://stackoverflow.com/comment/83986385
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48496318
type: Comment
has text: yes...! one while loop is present what else your teacher want

http://stackoverflow.com/comment/84324017
has text: I solved it by using a `.values` in the fit, predict, predict_proba, etc. In fact I created a wrapper that does that so I can keep the interface and pass Pandas DataFrames at will. However I'm wondering what I'm missing by not using Pandas. They muse use the column names for something, right?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48645846

http://stackoverflow.com/q/48527875
has answer: http://stackoverflow.com/a/48528003
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/84050734
score: -4
answer count: 1
has title: (Python) Importing data from text file into object
favorite count: 0
type: Question
has body: I have this code class List(object): def __init__(self, name=None, age=None, license=None): self.name = name self.age = age self.license=license peter = List('Peter Peter', '50', 'yes') martin = List('martin martin','40','no') but I would like to insert my data from a textfile (import more people with their name, age, license). How could I do that? Also, is there any way to make my code better? I am trying to achieve the same results as record function in Pascal. Thanks
has comment: http://stackoverflow.com/comment/84050813
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84050870
tagged with: python
has comment: http://stackoverflow.com/comment/84050958
has comment: http://stackoverflow.com/comment/84050911

http://stackoverflow.com/a/48511483
type: Answer
accepted answer of: http://stackoverflow.com/q/48504770
answers question: http://stackoverflow.com/q/48504770
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/105832728
has body: Based on the code in hpaulj's answer, I've tweaked the implementation to make it more versatile. It consists of 2 custom Action classes, ParentAction and ChildAction. Usage parser = argparse.ArgumentParser() # first, create a parent action: parent = parser.add_argument('-o', '--output', action=ParentAction) # child actions require a `parent` argument: parser.add_argument('-f', '--format', action=ChildAction, parent=parent) # child actions can be customized like all other Actions. For example, # we can set a default value or customize its behavior - the `sub_action` # parameter takes the place of the usual `action` parameter: parser.add_argument('-l', '--list', action=ChildAction, parent=parent, sub_action='append', default=[]) args = parser.parse_args(['-o', 'output1', '-l1', '-l2', '-o', 'output2', '--format', 'csv', '-o', 'output3', '-f1', '-f2']) print(args) # output (formatted): # Namespace( # output=OrderedDict([('output1', Namespace(list=['1', '2'])), # ('output2', Namespace(format='csv', list=[])), # ('output3', Namespace(format='2', list=[])) # ]) # ) Caveats Child actions must always follow after parent actions. For example, --format csv -o output1 would not work and show an error message. It's not possible to register multiple ChildActions with the same name, even with different parents. Example: parent1 = parser.add_argument('-o', '--output', action=ParentAction) parser.add_argument('-f', action=ChildAction, parent=parent1) parent2 = parser.add_argument('-i', '--input', action=ParentAction) parser.add_argument('-f', action=ChildAction, parent=parent2) # throws exception: # argparse.ArgumentError: argument -f: conflicting option string: -f Code import argparse from collections import OrderedDict class ParentAction(argparse.Action): def __init__(self, *args, **kwargs): super().__init__(*args, default=OrderedDict(), **kwargs) self.children = [] def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest) nspace = t…

http://stackoverflow.com/comment/84075680
has text: just keep this param `date_created__month=datetime.today().date().month` in the query
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48540267

http://stackoverflow.com/comment/84006139
has text: Another table widget which is pretty easy to use. Look at *Answer 1* in [this link](https://stackoverflow.com/questions/48358084/how-to-change-the-foreground-or-background-colour-of-a-selected-cell-in-tkinter/48361639#48361639) and be sure to download the tktable widget (as per the comments under Answer 1).
score: 0
comment on: http://stackoverflow.com/q/48505575
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84137842
has text: @CL, thank you. Any recommendation for how to do that in Python?
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48528300

http://stackoverflow.com/q/48597763
has answer: http://stackoverflow.com/a/48597784
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48597822
has comment: http://stackoverflow.com/comment/84192074
downvote count: 0
tagged with: python
has body: I'm new to python and have a simple question: Is it possible to statically overload a member fuction? Like for example so: class A: text="" def __init__(self, text): self.text = text def print(self): print (self.text) @staticmethod def print(): print ("static") a = A("test") a.print() In this case "static" is printed out. Is it impossible to call the member function if a static function with the same name exists? And if not, who do I call it?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84192090
upvote count: 3
score: 3
possible better answer: http://stackoverflow.com/a/48597822
tagged with: oop
has answer: http://stackoverflow.com/a/48597793
accepted answer: http://stackoverflow.com/a/48597793
answer count: 3
has title: python static overloading of member function
has comment: http://stackoverflow.com/comment/84192199

http://stackoverflow.com/a/48528767
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48527420
has body: Not very pretty but you can use equality broadcasting with the .eq method. m = df.iloc[:, :5].eq(df['TIME_MIN'], axis=0) m.columns = 'STATUS_' + m.columns.str.extract('TIME_(.*)') df['STATUS'] = df[m].bfill(axis=1).iloc[:, 0]
type: Answer

http://stackoverflow.com/a/48544205
has body: Just do a list comprehension! with open('reports/1.16-IAM.json') as jsonIAMUsers: IAMUsers = json.load(jsonIAMUsers) usernames = [u['UserName'] for u in IAMUsers['Users']] Note with part. It is context manager, which will do all file-related routine(close, etc) for you. Default mode for open function is r, so it might be skipped.
has comment: http://stackoverflow.com/comment/84083977
type: Answer
answers question: http://stackoverflow.com/q/48544161
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84083927
accepted answer of: http://stackoverflow.com/q/48544161

http://stackoverflow.com/a/48580448
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48568239
has body: This is how I solved it. df['A'] = df.groupby('Outlet_Type').A.transform(lambda x: x.fillna(x.mode()[0]))

http://stackoverflow.com/q/48539378
has comment: http://stackoverflow.com/comment/84074277
favorite count: 0
has answer: http://stackoverflow.com/a/48539541
type: AnsweredQuestion
has body: my_stng = " Einstein found out (apple) (fruit) which is (red)(green) in colour" Requirement: in the above string, count the number of times the parenthesis occurs and print the whole string that many times. if the count of parenthesis is 3, i need to print the above string 3 times.
score: -2
tagged with: textblob
linked to: http://stackoverflow.com/q/48521986
linked to: http://stackoverflow.com/q/48144487
has comment: http://stackoverflow.com/comment/84075776
tagged with: nlp
has comment: http://stackoverflow.com/comment/84073924
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84075832
has title: print a particular string based on the count of parenthesis occurs
upvote count: 0
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/48090657
tagged with: python
accepted answer: http://stackoverflow.com/a/48539541

http://stackoverflow.com/q/48572558
has comment: http://stackoverflow.com/comment/84142306
answer count: 4
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84144123
has answer: http://stackoverflow.com/a/48576183
tagged with: file
has answer: http://stackoverflow.com/a/48590377
tagged with: parsing
has comment: http://stackoverflow.com/comment/84142560
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I have a file with the following format: X ={ a= "someText"; b = 0; c = 1; d ={ t = "someText3"; }; f ="someText2"; }; X ={ a= "someText4"; b = 20; c = 40; f ="someText6"; d ={ t = "someText5"; }; }; I am looking for a smart and robust way to parse it to a list of dict like the following: X[0] = {'a':"someText",'b':0, 'c':0, 'd':{ 't':'SomeText3' }, 'f':"someText2"} X[1] = {'a':"someText4",'b':20, 'c':40, 'd':{ 't':'SomeText5' }, 'f':"someText6"} Note that there might be nested dictionaries and the variables can have different order of occurrence. My method is to keep track of the level by searching '={' and '};' and construct the list. I wonder if there is an elegant method to parse it.
has answer: http://stackoverflow.com/a/48597116
tagged with: python
has title: Parsing a file with special format using python to a list of dictionaries
tagged with: dictionary
has answer: http://stackoverflow.com/a/48591030

http://stackoverflow.com/q/48593014
answer count: 1
tagged with: tensorflow
type: Question
has body: With python 2.7 on a mac with tensorflow and running tensorboard --logdir= directory/wheremylog/fileis produces the following error ImportError: cannot import name weakref I've seen several folks remedy the issue with pip install backports.weakref but that requirement is already satisfied for me. Requirement already satisfied: backports.weakref in /usr/local/lib/python2.7/site-packages I am out of ideas and am really keen to get tensorboard working. Thanks
has answer: http://stackoverflow.com/a/48633697
has title: Launching tensorboard error - ImportError: cannot import name weakref
tagged with: tensorboard
tagged with: python
score: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48527094
accepted answer of: http://stackoverflow.com/q/48526157
has comment: http://stackoverflow.com/comment/84587557
has body: Aggregate in two steps and then join: import pyspark.sql.functions as F (df.groupBy(['product-name', 'Use-case']) .count() .withColumnRenamed('count', 'User counts') .join( df.groupBy('product-name').count(), ['product-name'] ).withColumn('User counts', F.col('User counts')/F.col('count')) .drop('count').show()) +------------+----------+-----------+ |product-name| Use-case|User counts| +------------+----------+-----------+ | B|Relaxation| 1.0| | C| health| 1.0| | A| therapy| 0.5| | A|relaxation| 0.5| +------------+----------+-----------+
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84587784
answers question: http://stackoverflow.com/q/48526157
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/48585737
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/84168642
has comment: http://stackoverflow.com/comment/84168522
has comment: http://stackoverflow.com/comment/84170243
has comment: http://stackoverflow.com/comment/84168369
answers question: http://stackoverflow.com/q/48584465
has body: I crafted the following: from datetime import datetime, date from datetime import timedelta def next_month_generator(d): while True: if d.month == 12: # on Dec, need to change year d = d.replace(year=d.year+1, month=1) else: try: # get next month, same date d = d.replace(month=d.month+1) except ValueError: # get next month, last months date d = date(year=d.year, month=d.month+2, day=1) - timedelta(days=1) yield d start_date=date(2017, 1, 31) nm = next_month_generator(start_date) for _ in range(13): print(nm.next()) &gt;&gt; 2017-02-28 &gt;&gt; 2017-03-28 &gt;&gt; 2017-04-28 &gt;&gt; 2017-05-28 &gt;&gt; 2017-06-28 &gt;&gt; 2017-07-28 &gt;&gt; 2017-08-28 &gt;&gt; 2017-09-28 &gt;&gt; 2017-10-28 &gt;&gt; 2017-11-28 &gt;&gt; 2017-12-28 &gt;&gt; 2018-01-28 &gt;&gt; 2018-02-28 If Python 3, use: for _ in range(13): print(next(nm))
downvote count: 0
score: 6

http://stackoverflow.com/q/48587950
has answer: http://stackoverflow.com/a/48588664
favorite count: 0
type: Question
has title: Python: How to import MS excel data into MS access database
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has body: I am trying to do it with the following code and I do not if it is right or not import pyodbc DBFile = r'C:\Users\sidhant\Documents\Database1.accdb' conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBFile) exfile = r'C:\Users\sidhant\Documents\Sheet1.xlsx' conn1 = pyodbc.connect('DRIVER={Microsoft Excel Driver \ (*.xlsx)};DBQ='+exfile,autocommit=True) curs1 = conn1.cursor() excel_results = curs1.execute('select [a_column] from [sheet1$]').fetchall() curs1.executemany('insert into mytable (mycolumn) values (?)', excel_results) conn.commit and it gives me this error C:\Users\sidhant\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/sidhant/PycharmProjects/untitled/practice.py Traceback (most recent call last): File "C:/Users/sidhant/PycharmProjects/untitled/practice.py", line 5, in conn = pyodbc.connect('DRIVER={access (*.mdb, *.accdb)};DBQ='+DBFile) pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') Process finished with exit code 1
has comment: http://stackoverflow.com/comment/84173404
answer count: 1
has comment: http://stackoverflow.com/comment/84173661
has comment: http://stackoverflow.com/comment/84173595
tagged with: python

bulkinsert
type: Tag
tag name: bulkinsert
tags question: http://stackoverflow.com/q/48622538

http://stackoverflow.com/comment/84134163
type: AnswerComment
comment on: http://stackoverflow.com/a/48568846
has text: I could not gain consistent results with this test. Each run had varying performances and each function performed better at times than the other two.
type: Comment
score: 0

http://stackoverflow.com/comment/84266309
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48634693
has text: Can you please provide the code you have already tried to generate the results with? Also, be more specific as to what output you would like.
score: 1

http://stackoverflow.com/q/48524402
has body: I'm noob with pandas, and recently, I got that 'ValueError' when I'm trying to modify the columns that follows some rules, as: csv_input = pd.read_csv(fn, error_bad_lines=False) if csv_input['ip.src'] == '192.168.1.100': csv_input['flow_dir'] = 1 csv_input['ip.src'] = 1 csv_input['ip.dst'] = 0 else: if csv_input['ip.dst'] == '192.168.1.100': csv_input['flow_dir'] = 0 csv_input['ip.src'] = 0 csv_input['ip.dst'] = 1 I was searching about this error and I guess that it's because the 'if' statement and the '==' operator, but I don't know how to fix this. Thanks!
has title: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()?
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48525313
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: valueerror
has comment: http://stackoverflow.com/comment/84043667

http://stackoverflow.com/a/48560810
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48560599
has comment: http://stackoverflow.com/comment/84120617
accepted answer of: http://stackoverflow.com/q/48560599
has body: I'm with @Chris_Rands. But as far as performance is concerned, there is a faster way using numpy: import numpy as np def with_np(my_list): return len(np.where(my_list&gt;=500)[0])
has comment: http://stackoverflow.com/comment/84121583
type: AcceptedAnswer

http://stackoverflow.com/a/48590653
has comment: http://stackoverflow.com/comment/84255708
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84281383
type: Answer
has comment: http://stackoverflow.com/comment/84208411
has comment: http://stackoverflow.com/comment/84260272
has comment: http://stackoverflow.com/comment/84208567
score: 0
has comment: http://stackoverflow.com/comment/84260339
accepted answer of: http://stackoverflow.com/q/48585490
has comment: http://stackoverflow.com/comment/84232760
answers question: http://stackoverflow.com/q/48585490
has body: Simply don't reuse the same python variable c for different operations: a = [-1.2, -5, 30.0, -7.5, 0.75] c = tf.get_variable("v", shape=[5], initializer=tf.constant_initializer(a)) assign55 = c[0].assign(55) assign66 = c[0].assign(66) assign77 = c[1].assign(77) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(assign55) print(sess.run(c)) # [55. -5. 30. -7.5 0.75] sess.run(assign66) print(sess.run(c)) # [66. -5. 30. -7.5 0.75] sess.run(assign77) print(sess.run(c)) # [66. 77. 30. -7.5 0.75]

http://stackoverflow.com/comment/83987232
comment on: http://stackoverflow.com/q/48497133
score: 1
has text: `password=None` is a keyword argument of the `create_user` method. `None` is the default value for `password` if `password` is not explicitly provided.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48515896
has comment: http://stackoverflow.com/comment/84026027
type: Question
has comment: http://stackoverflow.com/comment/84026536
has title: How to read a csv dataset when converting to a float that contain nan's
has answer: http://stackoverflow.com/a/48517529
has answer: http://stackoverflow.com/a/48516068
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84027669
tagged with: list
answer count: 2
has body: I have a dataset containing XY coordinates. df: ,Time_x,P1_X,P1_Y,P2_X,P2_Y,P3_X,P3_Y,P4_X,P4_Y,P5_X,P5_Y,P6_X,P6_Y,P7_X,P7_Y,P8_X,P8_Y,P9_X,P9_Y,P10_X,P10_Y,P11_X,P11_Y,P12_X,P12_Y,13_X,P13_Y,MP14_X,P14_Y,P15_X,P15_Y,P16_X,P16_Y,P17_X,P17_Y,P18_X,P18_Y,P19_X,P19_Y,P20_X,P20_Y,P21_X,P21_Y 0,10:39.2,65.74835477,45.10031842,,,73.73594438,-3.516560206,61.90991549,41.79799446,67.06663915,-24.6161481,77.13941436,-22.98303729,,,93.94853726,3.51273869,56.51826591,28.44337707,70.2095591,11.06472095,73.07962202,-35.54419066,,,69.78626105,45.73116662,73.34402753,29.26475119,64.72901307,-40.68655635,70.90387539,6.110571001,,,70.94140139,-45.11483157,42.78164288,3.001018117,61.77394225,-1.052283362,72.07455255,38.61536724 1,10:39.3,65.7684248,45.15534694,,,73.69043192,-3.346474054,61.69908417,41.78674915,67.18671591,-24.58808435,77.17029694,-23.02517617,,,93.89646426,3.528745627,56.5427544,28.38370261,70.19822793,10.99883442,73.1451771,-35.47750429,,,69.793868,45.85988623,73.19566664,29.30369084,64.95606388,-40.77004615,70.91007366,6.101747301,,,71.04051167,-45.29294224,42.83526579,3.015121968,61.82365038,-0.992786137,72.11546062,38.71278829 2,10:39.4,65.7834979,45.23761992,,,73.63024857,-3.170554247,61.69908417,41.78674915,67.31838918,-24.56060698,77.19810461,-23.05487575,,,93.83429634,3.549376049,56.58563081,28.31338862,70.20044679,10.91910555,73.19935612,-35.41010968,,,69.793868,45.85988623,73.03211884,29.35832821,65.18572736,-40.83631919,70.90862232,6.095069866,,,71.14518241,-45.50045784,42.91278516,3.042026157,61.89316922,-0.908282198,72.15835354,38.79647675 3,10:39.5,65.77840928,45.33358677,,,73.56738903,-3.004921009,61.49273767,41.78345615,67.45296434,-24.49742142,77.24683185,-23.0746477,,,93.75341377,3.57316934,56.58563081,28.31338862,70.21321398,10.82616678,73.24568774,-35.32805879,,,69.76596819,46.01111858,72.86184401,29.42608261,65.44690548,-40.85525672,70.89755931,6.089554125,,,71.14518241,-45.50045784,43.00642078,3.080217618,61.97555301,-0.809576222,72.19068707,38.…
has comment: http://stackoverflow.com/comment/84027373
type: UnansweredQuestion
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84026874

http://stackoverflow.com/a/48503683
has body: Apparently this is a known bug when using a combination of cx-freeze, distutils and virtualenv (see here). From the above link: This problem happens because distutils does not install all its modules into the virtualenv, it only creates a package with some magic code in the __init__ file to import its submodules dynamically. This is a problem to cx-freeze's static module analysis, which complains during the build command that it can't find distutils modules. Solution (workaround) from the above link: The workaround used was to tell cx-freeze to exclude distutils and add the package from the original interpreter (not from the virtualenv) manually. # contents of setup.py from cx_Freeze import setup, Executable import distutils import opcode import os # opcode is not a virtualenv module, so we can use it to find the stdlib; this is the same # trick used by distutils itself it installs itself into the virtualenv distutils_path = os.path.join(os.path.dirname(opcode.__file__), 'distutils') build_exe_options = {'include_files': [(distutils_path, 'lib/distutils')], 'excludes': ['distutils']} setup( name="foo", version="0.1", description="My app", options={"build_exe": build_exe_options}, executables=[Executable("foo_main.py", base=None)], )
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48502648
answers question: http://stackoverflow.com/q/48502648
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/comment/84064985
type: Comment
has text: Thanks for this answer... I'm starting to see how this works. With your second bullet, if you use the `x * x` column as the sorting order, going out from the middle or the zero, you get `0, 1, 1, . . . 25, 25` (like @Sanju commented above). If you apply this to the column from the `range(-5, 6)`, you get `0, -1 or 1, -2 or 2, . . . -5 or 5`. From here it's a matter of the rule Python follows, eg, `sorted()` outputting `-1` before `1` and you're done! Thanks! This helped a lot.
type: AnswerComment
comment on: http://stackoverflow.com/a/48534594
score: 0

http://stackoverflow.com/a/48506637
downvote count: 1
answers question: http://stackoverflow.com/q/48506592
type: Answer
has body: What's wrong with this: print(currency['euro']) It should print: 4.1423 Your currency OTOH needs to be like this (you were missing { and } and some dictionary inside dictionary related stuff): currency = { 'bat (Tajlandia)': 0.1062, 'dolar amerykański': 3.3375, 'dolar australijski': 2.6997, ... 'euro': 4.1423, 'forint (Węgry)': 0.013388, 'frank szwajcarski': 3.5625 }
has comment: http://stackoverflow.com/comment/84008725
score: 0
upvote count: 1

http://stackoverflow.com/q/48548296
has answer: http://stackoverflow.com/a/57438578
favorite count: 0
answer count: 3
tagged with: lxml
has answer: http://stackoverflow.com/a/48548401
tagged with: python
upvote count: 6
type: Question
has body: I found an object with specific class: THREAD = TREE.find_class('thread')[0] Now I want to get all elements that are its direct children. I tried: THREAD.findall("p") THREAD.xpath("//div[@class='thread']/p") But all of those returns all elements inside this , no matter if that is their closest parent or not. How can I make it work? Edit: Sample html: [...] [...] script should find two objects , which are children of THREAD. I should receive list of two objects, marked as "1" and "2" in comments in sample HTML. Edit 2: Yet another clarification, since people get confused: THREAD is some object stored in variable, can be any html element. I want to find objects that are direct children of THREAD. Those 's can not be outside THREAD or inside any element that's also inside THREAD.
tagged with: xpath
has answer: http://stackoverflow.com/a/48550674
has title: How to find direct children of element in lxml
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84094119
has comment: http://stackoverflow.com/comment/84094770
downvote count: 0
score: 6

http://stackoverflow.com/comment/84136930
score: 0
has text: @StefanPochmann I think the _It's puzzling why you chose this type of data structure_ part is addressed to OP. And yes it definitely is a valid syntax!
type: QuestionComment
comment on: http://stackoverflow.com/q/48569965
type: Comment

http://stackoverflow.com/comment/84106553
type: AnswerComment
comment on: http://stackoverflow.com/a/48550468
has text: still getting an error: AttributeError at /multiplication/multiplied 'HomeForm' object has no attribute 'quantity1'
type: Comment
score: 0

bytesio
tags question: http://stackoverflow.com/q/48592266
type: Tag
tag name: bytesio

http://stackoverflow.com/comment/84202247
type: AnswerComment
has text: Look more closely at the traceback. This is the wrong problem and the wrong solution.
type: Comment
comment on: http://stackoverflow.com/a/48593091
score: 0

http://stackoverflow.com/a/48600843
score: 1
type: Answer
has body: Your code is right except that when you need to use %s rather than %a because you want to input as a string (IE %s is a string). As indicated by in the comments by megaing
answers question: http://stackoverflow.com/q/48600784
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/57913826
answers question: http://stackoverflow.com/q/48567245
upvote count: 5
has body: Just do this: mkdir .venv pipenv install Explanation: pipenv checks your project directory for a sub directory named .venv. If it finds it, then pipenv creates a local virtual environment (because then it sets automatically PIPENV_VENV_IN_PROJECT=true) So now if you want you can either activate the virtual environment with: source .venv/bin/activate Or config you app.conf for gunicorn with something like this: exec /path/to/.venv/bin/gunicorn myapp:app
type: Answer
score: 5
downvote count: 0

http://stackoverflow.com/comment/84309085
comment on: http://stackoverflow.com/q/48626492
score: 0
type: Comment
type: QuestionComment
has text: Hello, and welcome to StackOverflow! At present, your question does not have enough information to give a good answer. Please see https://stackoverflow.com/help/mcve.

http://stackoverflow.com/a/48606217
score: 1
has body: Every content that exists in *.po files is not directly related to models, for example if you sets verbose_name of model field by django ugettext this content exist on the *.po file, but other thins such as template trans tag content also exist on these files. You can use models translation apps such as django-modeltranslation to translate models on the admin but you cant translations that not used directly definitioned on the models fields.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84210141
type: Answer
answers question: http://stackoverflow.com/q/48606119
has comment: http://stackoverflow.com/comment/84211466
has comment: http://stackoverflow.com/comment/84230419
accepted answer of: http://stackoverflow.com/q/48606119

http://stackoverflow.com/a/48868127
has body: The issue was not really related to Google Storage or misused Pandas functionality. The problem was that my json file was not correctly formatted. The reason was that the process which created the json data required that there was an empty or no file. In my test scenario I started the process a couple of times, so at the end my data file had a couple of lists appended to each other such as [....... json content 1 ] [....... json content 2 ] I found this out by searching for ][. The way how I access a json file residing in a Google bucket within Jupyter was correct: %env GOOGLE_APPLICATION_CREDENTIALS = /my_path/google-api-keys.json import pandas as pd from google.cloud import storage client = storage.Client() bucket = client.get_bucket('my_bucket') blob = bucket.get_blob('my_data.json') content = blob.download_as_string() my_df = pd.read_json(content) The Google API keys file can be created from the console via APIs &amp; Services &gt; Credentials &gt; Create credentials &gt; Service Account key &gt; select JSON
type: Answer
answers question: http://stackoverflow.com/q/48530448
score: 0

http://stackoverflow.com/a/48553188
downvote count: 0
upvote count: 1
has body: Inspired by the answer to the post mentioned in the comment I created a class that seems to do the job. I used the code from that answer, added timeout and blocking arguments and put it inside a class so I can use it as a context manager. The class uses static methods, so it can be instantiated once or it can be created many times (as the test below does in slow_worker_2). The first part of the code is the class, the second part tests both explicit acquire and release and the context manager with with. import threading import time namespace_lock = threading.Lock() namespace = {} counters = {} class NamespaceLock: def __init__(self, group): self.group = group def __enter__(self): self.__class__.acquire_lock(self.group) def __exit__(self, exc_type, exc_val, exc_tb): self.__class__.release_lock(self.group) @staticmethod def acquire_lock(value, blocking=True, timeout=-1.0): with namespace_lock: if value in namespace: counters[value] += 1 else: namespace[value] = threading.Lock() counters[value] = 1 return namespace[value].acquire(blocking=blocking, timeout=timeout) @staticmethod def release_lock(value): with namespace_lock: if counters[value] == 1: del counters[value] lock = namespace.pop(value) else: counters[value] -= 1 lock = namespace[value] lock.release() def slow_worker_1(group, seconds): if NamespaceLock.acquire_lock(group, timeout=2.5): print('Start {} {}'.format(group, seconds)) time.sleep(seconds) print('End {} {}'.format(group, seconds)) NamespaceLock.release_lock(group) else: print('Timeout {} {}'.format(group, seconds)) def slow_worker_2(group, seconds): with NamespaceLock(group): print('Start {} {}'.format(group, seconds)) time.sleep(seconds) print('End {} {}'.format(group, seconds)) def join_all(name): for t in threading.enumerate(): if t.name == name: t.join() if __name__ == '__main__': print('explicit acquire and release') threading.Thread(target=slow_worker_1, args=('g1', 1), name='worker').start() threading.Thread(target=slow_worker_1, args=('g2', 2),…
answers question: http://stackoverflow.com/q/48551679
accepted answer of: http://stackoverflow.com/q/48551679
score: 1
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/comment/108291829
has text: @AdamGriffiths. All done! I was trying to modify Qt objects outside Qt space. All working now. And it was because of the linked question.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/61198797
type: AnswerComment

http://stackoverflow.com/comment/84045045
type: Comment
type: QuestionComment
score: 0
has text: Then please reopen as maybe some one can come up with a different idea. Probably manually dropping the "duplicate" rows as second step ?
comment on: http://stackoverflow.com/q/48524362

http://stackoverflow.com/q/48490260
has answer: http://stackoverflow.com/a/52773848
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-import
has answer: http://stackoverflow.com/a/71003879
answer count: 12
has answer: http://stackoverflow.com/a/69885220
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50889706
upvote count: 45
has answer: http://stackoverflow.com/a/53896726
has comment: http://stackoverflow.com/comment/88780570
tagged with: python
has body: I have anaconda installed on my Win 7 machine with a GTX1070. I have been trying to install tensorflow gpu version for the past hour with no luck. I followed the tutorials on the tensorflow website to no success. They ask for you to install CUDA 8.0 and Cudll 6.0 which I do. I then add the location of cudnn64_6.dll, cudart64_80.dll and the libnvvp folder to my path variables. I then set up a virtual environment in conda and run the following command: (tensorflow)C:&gt; pip install --ignore-installed --upgrade tensorflow-gpu I believe when I do this, it installs tensorflow 1.5 which seems to require CUDA tools 9.0 because I get an error saying that cudart64_80.dll cannot be found. So I update my CUDA tools to 9.0 and download the corresponding Cuda library. I then change my path variables. Now I dont get any missing dll errors however, I am now faced with the following error ModuleNotFoundError: No module named 'absl' Does anyone have any suggestions as to what I can do from here on?
has title: No module named 'absl' error when I import tensorflow
downvote count: 1
tagged with: absl-py
has answer: http://stackoverflow.com/a/62175243
has answer: http://stackoverflow.com/a/53121990
has comment: http://stackoverflow.com/comment/84837544
has answer: http://stackoverflow.com/a/60755575
has answer: http://stackoverflow.com/a/51193645
tagged with: anaconda
score: 44
has answer: http://stackoverflow.com/a/59342083
has answer: http://stackoverflow.com/a/52064127
has comment: http://stackoverflow.com/comment/86833862
has comment: http://stackoverflow.com/comment/83976318
has answer: http://stackoverflow.com/a/66270608
has comment: http://stackoverflow.com/comment/116540126

http://stackoverflow.com/comment/84115242
type: AnswerComment
comment on: http://stackoverflow.com/a/48554580
type: Comment
has text: welcome and as @f5r5e5d mentioned replace random_list.append(randint(1, 7)) with random_list.append( str( randint(1, 7) ) )
score: 0

gmail
tags question: http://stackoverflow.com/q/48513869
type: Tag
tag name: gmail
tags question: http://stackoverflow.com/q/48628755
tags question: http://stackoverflow.com/q/48505749

http://stackoverflow.com/comment/83990946
comment on: http://stackoverflow.com/q/48498139
has text: Sure it is, but I believe at least one of those issues can be solved somehow. That's why I ask experienced community here
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48629253
has comment: http://stackoverflow.com/comment/84255778
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84255683
has comment: http://stackoverflow.com/comment/84255420
accepted answer: http://stackoverflow.com/a/48629656
has comment: http://stackoverflow.com/comment/84255745
has title: Dynamic dataframe column name in apply function
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84256007
upvote count: 1
has comment: http://stackoverflow.com/comment/84255632
has comment: http://stackoverflow.com/comment/84255505
has body: I am using the current dataframe: df = pd.DataFrame({'columnA':[1111,1111,2222,3333,4444,4444,5555,6666], 'columnB':['AAAA','AAAA','BBBB','AAAA','BBBB','BBBB','AAAA','BBBB'], 'columnC':['one','two','one','one','one','sales','two','one'], 'NUM1':[1,3,5,7,1,0,4,5], 'NUM2':[5,3,6,9,2,4,1,1], 'W':list('aaabbbbb')}) and I am trying to use a dynamic column in the following code: #First aggregate the data d = {'columnB':'unique', 'columnC':'unique' } df2 = df.groupby('columnA').agg(d) #Convert list to string for each cell of the inventory field mylist = ["columnB","columnC"] for x in mylist: columnName = x #print("df2."+columnName+".apply(', '.join)") df2[columnName] = df2[columnName].apply(', '.join) and it works fine in Jupyter. My issue is that it does not work when I run it on visualstudio. I am getting this error: sequence item 0: expected str instance, float found after print the dataframe's type I am getting this: &lt;class 'pandas.core.frame.DataFrame'&gt; Here is the full error message: Traceback (most recent call last): File "stage1.py", line 112, in main() File "stage1.py", line 57, in main templateScenarios[columnName] = templateScenarios[columnName].apply(', '.join) File "/Users/apolo.siskos/anaconda3/lib/python3.6/site-packages/pandas/core/series.py", line 2355, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File "pandas/_libs/src/inference.pyx", line 1574, in pandas._libs.lib.map_infer TypeError: sequence item 0: expected str instance, float found
has comment: http://stackoverflow.com/comment/84255960
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48629656
tagged with: pandas
has comment: http://stackoverflow.com/comment/84255451
has comment: http://stackoverflow.com/comment/84255553
score: 1
has comment: http://stackoverflow.com/comment/84256070
tagged with: python
has comment: http://stackoverflow.com/comment/84255511
has comment: http://stackoverflow.com/comment/84255557

http://stackoverflow.com/q/48585139
tagged with: python
has comment: http://stackoverflow.com/comment/91893711
has answer: http://stackoverflow.com/a/73425730
has body: I'm on the Windows, using mmap module for sharing information between two Python scripts. My problem is to write data into a memory for being accessed from other script, without writing it on a disk. According to documentation, mmap.write() method is exactly what I'm looking for: Write the bytes in bytes into memory at the current position of the file pointer and return the number of bytes written. I'm running the following code to test writing into memory and face 2 problems: def test_write_mmf(json_path): # Know the file size to read from the memory file_size = os.path.getsize(json_path) # Open and read file amd MMF json_file = open(json_path, "r+", encoding="utf8") mapped_file = mmap.mmap(json_file.fileno(), 0) mapped_file.seek(0) buffer_for_json = mapped_file[:file_size] # Content is JSON, so load it json_data = json.loads(buffer_for_json.decode("utf-8")) # do some in-memory edits json_data[0]["response_index"] = 0 json_data[0]["description"] = "INSTALL" # write it back into memory json_string = json.dumps(json_data) json_bytes = bytearray(json_string, encoding="utf8") mapped_file.seek(0) # It supposed to write into memory only! mapped_file.write(bytes(json_bytes)) # Here I wait to check if the file was written m.getch() # Supposed to be real flush content to disk mapped_file.flush() At the line mapped_file.write(bytes(json_bytes)) I'm expecting my changes are still in the memory, but it is in a file on the disk already. This problem is not connected to previous, but I realized when the written content smaller than it was before, I see the "tail" of the previous data still remains in the rewritten file. Is there a way to erase opened file? I tried json_file.truncate() with Permission Denied (WinError=13) error.
has comment: http://stackoverflow.com/comment/91893778
upvote count: 2
has comment: http://stackoverflow.com/comment/84209813
score: 2
has comment: http://stackoverflow.com/comment/84209931
downvote count: 0
type: UnansweredQuestion
answer count: 1
favorite count: 0
has title: Python mmap.write() writes not only in the memory, but also on the disk
type: Question
tagged with: memory-mapped-files
tagged with: windows

http://stackoverflow.com/q/48537305
tagged with: character-encoding
accepted answer: http://stackoverflow.com/a/48537439
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/48537442
possible better answer: http://stackoverflow.com/a/48537442
answer count: 2
linked to: http://stackoverflow.com/q/6936390
linked to: http://stackoverflow.com/q/25291474
duplicate of: http://stackoverflow.com/q/20845445
downvote count: 0
score: 4
tagged with: unicode
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20845445
has title: Same character, different length and bytes
has body: Downloading files from Korean websites, often filenames are wrongly encoded/decoded and end up being all jumbled up. I found out that by encoding with 'iso-8859-1' and decoding with 'euc-kr', I can fix this problem. However, I have a new problem where the same-looking character is in fact, different. Check out the Python shell bellow: &gt;&gt;&gt; first_string = 'â' &gt;&gt;&gt; second_string = 'â' &gt;&gt;&gt; len(first_string) 1 &gt;&gt;&gt; len(second_string) 2 &gt;&gt;&gt; list(first_string) ['â'] &gt;&gt;&gt; list(second_string) ['a', '̂'] &gt;&gt;&gt; Encoding the first string with 'iso-8859-1' is possible. The latter is not. So the question: What is the difference between these two strings? Why would downloads from the same website have the same character in varying format? (If that's what the difference is.) And how can I fix this? (e.g. convert second_string to the likeness of first_string) Thank you.
has comment: http://stackoverflow.com/comment/84069641
has answer: http://stackoverflow.com/a/48537439
tagged with: python

http://stackoverflow.com/a/48629483
type: Answer
has comment: http://stackoverflow.com/comment/84294312
upvote count: 16
has comment: http://stackoverflow.com/comment/84255933
has comment: http://stackoverflow.com/comment/84294951
has comment: http://stackoverflow.com/comment/84295020
has comment: http://stackoverflow.com/comment/84294343
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84256350
score: 16
has comment: http://stackoverflow.com/comment/84256106
has body: Use parametrized sql by supplying the arguments via the params keyword argument. The proper quotation of arguments will be done for you by the database adapter and the code will be less vulnerable to SQL injection attacks. (See Little Bobby Tables for an example of the kind of trouble improperly quoted, non-parametrized sql can get you into.) order = 10100 status = 'Shipped' sql = """SELECT * from orders where orderNumber = ? and status = ? order by orderNumber""" df1 = pd.read_sql_query(sql, cnx, params=[order, status]) The ?s in sql are parameter markers. They get replaced with properly quoted values from params. Note that the proper parameter marker depends on the database adapter you are using. For example, MySQLdb and psycopg2 uses %s, while sqlite3, and oursql uses ?.
has comment: http://stackoverflow.com/comment/84294650
accepted answer of: http://stackoverflow.com/q/48629413
has comment: http://stackoverflow.com/comment/84256025
has comment: http://stackoverflow.com/comment/84256041
has comment: http://stackoverflow.com/comment/84294360
answers question: http://stackoverflow.com/q/48629413

http://stackoverflow.com/comment/84052946
type: QuestionComment
has text: If the `try` block fails, `response` is not defined for subsequent code. You either need to define some default value before try/except or in the exception block.
comment on: http://stackoverflow.com/q/48528890
score: 1
type: Comment

http://stackoverflow.com/q/48489443
tagged with: web
accepted answer: http://stackoverflow.com/a/48490059
tagged with: http
has answer: http://stackoverflow.com/a/48490059
type: AnsweredQuestion
has title: "urllib.error.HTTPError: HTTP Error 404: Not Found" Python
has body: I'm trying to open this webpage with the urllib.request.open function: "https://prenotaonline.esteri.it/login.aspx?cidsede=100001&amp;returnUrl=//" I can access this webpage with my regular browser, still with the urrlib.request.open function it returns HTTP error 404: import urllib.request page = urllib.request.urlopen("https://prenotaonline.esteri.it/login.aspx?cidsede=100001&amp;returnUrl=//").read() print(page) I get the following error: Traceback (most recent call last): File "/Users/markmouawad/Documents/consu_programa/scrapper.py", line 4, in &lt;module&gt; page = urllib.request.urlopen("https://prenotaonline.esteri.it/login.aspx?cidsede=100001&amp;returnUrl=//").read() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 163, in urlopen return opener.open(url, data, timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 472, in open response = meth(req, response) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 582, in http_response 'http', request, response, code, msg, hdrs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 510, in error return self._call_chain(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 444, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 590, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found I'm using Python 3.5.3
tagged with: python
tagged with: urllib
type: Question
score: 0
answer count: 1
tagged with: error-handling

http://stackoverflow.com/a/48594855
type: Answer
has comment: http://stackoverflow.com/comment/128594491
has body: You can try this xpath: driver.find_element_by_xpath(&quot;//button[contains(text(),'Approve')]&quot;).click()
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48588828
score: 3
has comment: http://stackoverflow.com/comment/113641415

http://stackoverflow.com/a/50327040
has comment: http://stackoverflow.com/comment/130186985
has body: maybe you can try something like this soup = bs(" Lorem is simply dummy text of the printing and typesetting industry. ",'lxml') # This is the word we want to put a tag around special_word = 'Lorem' content_orig = soup.p.text split_content_orig = content_orig.split(special_word) soup.p.string = '' soup.p.insert(len(soup.p), split_content_orig[0]) for i_word in split_content_orig[1:]: # We need to create a new tag in every loop, otherwise it moves the tag around. Probably has something to do with each tag having a unique id() new_tag = soup.new_tag('mark') new_tag.string = special_word soup.p.insert(len(soup.p), new_tag) soup.p.insert(len(soup.p), i_word) I had a similar problem, and stated my question here: Replace text with bold version in Beautiful Soup Maybe somebody else will reply to it and find a better solution. But in the mean time you can use this I guess
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/130195235
answers question: http://stackoverflow.com/q/48638325
score: 1
type: Answer

http://stackoverflow.com/comment/84162628
comment on: http://stackoverflow.com/q/48582654
type: Comment
type: QuestionComment
has text: PyQt5-5.10 @eyllanesc
score: 0

http://stackoverflow.com/q/48492574
tagged with: list
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48492648
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83978346
type: Question
has answer: http://stackoverflow.com/a/48492648
tagged with: python
tagged with: dictionary
tagged with: updates
tagged with: append
has title: Unwanted Dictionary Update When Adding Multiple Dictionaries to a List
has body: In Python, I'm trying to create a list consisting of 2 independent dictionaries (dict1 &amp; dict2). However, when I add them both to a new list using append and update methods, it seems to change my dict1 dictionary. n = [] dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4, "e": 5} n.append(dict1) n[0].update(dict2) This gives me result I want for n but it also overwrites my dict1, which is not desired. dict1 {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} Why is this happening? How can I achieve my goal of joining the 2 dicts into a list without modifying my first dict? This code serves the purpose of joining 2 JSON docs into one, in case anyone is wondering.
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85063519
score: 0
type: Comment
has text: If you have a working code with loops, where only nnumpy arrays are involved Numba is the way to go. It is very easy to use and speeds up the computation by a factor of 100-1000. So you can do most things quite C-like if apropriate. Example: https://stackoverflow.com/a/49011917/4045774
type: QuestionComment
comment on: http://stackoverflow.com/q/48525138

http://stackoverflow.com/a/48580330
has comment: http://stackoverflow.com/comment/84157562
score: 1
has body: If for whatever reason you really want to insert all statements at once, just concatenate all insert statements using ; and sent it as a single string to the database. Like this: "INSERT INTO products(products_amazon) VALUES ('one'); INSERT INTO products(products_amazon) VALUES ('two'); INSERT INTO products(products_amazon) VALUES ('three');"
downvote count: 0
answers question: http://stackoverflow.com/q/48578848
accepted answer of: http://stackoverflow.com/q/48578848
type: AcceptedAnswer
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84156942

http://stackoverflow.com/q/48544925
has body: I want to plot a scatter plot where each point has a color that corresponds to the value of a third array. The colors need to be specific to a key called colors. So if the z value was 4 then the color should be '#9C6BE1' colors= ["#049FBB", "#5DF10A", "#BF5B3F", "#A95058", "#9C6BE1","#6CC43C","#7B3001", "#B3D407","#97CE66"] #hex colours x = [1,2,3,4] y = [3,4,8,6] z= [4,6,8,2] plt.scatter(x,y,c=c) How do I plot each point to the color that corresponds to the value for z?
tagged with: colors
possible better answer: http://stackoverflow.com/a/48544976
tagged with: matplotlib
tagged with: python
score: -1
has title: Plotting a scatter plot in python where the z value corresponds to a color key
has answer: http://stackoverflow.com/a/48545022
type: AnsweredQuestion
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/48544976
downvote count: 1
tagged with: plot
favorite count: 0
accepted answer: http://stackoverflow.com/a/48545022
type: Question

apache2
tags question: http://stackoverflow.com/q/48642530
type: Tag
tags question: http://stackoverflow.com/q/48511370
tag name: apache2

http://stackoverflow.com/a/48620739
type: Answer
answers question: http://stackoverflow.com/q/48620643
score: 2
has body: Your regex only matches alphanumeric characters, but your ID contains /. You should update it to be [\w/]+.
upvote count: 3
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48620643

http://stackoverflow.com/q/48529664
tagged with: pandas
score: 1
tagged with: openpyxl
downvote count: 0
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48529717
has body: I do have an excel sheet that has 30000 rows in it. I want to categorize the first 5 rows with for example #1. the second 5th rows with #2 and so on until reaching 30000 rows. how can I do that with excel sheet. lst1 = [] classifier = 0 while classifierOne &lt;= 30000: if classifier &lt;= 5: lst1.append(1) if classifier &gt; 5 and classifier&lt;=10: lst1.append(2) :: :: :: :: :: :: :: :: classifierOne +=1 # do this until I reach 30000 which is not an efficient way to do. print(lst1, classifierOne) df = DataFrame({'':lst1}) df.to_excel('list.xlsx', sheet_name='sheet1', index=False) I have tried many ways But I couldn't find and efficient way to do this. Your help is appreciated.
tagged with: excel
has comment: http://stackoverflow.com/comment/84054917
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48529717
has comment: http://stackoverflow.com/comment/84054715
has comment: http://stackoverflow.com/comment/84054644
has comment: http://stackoverflow.com/comment/84054666
tagged with: python
has comment: http://stackoverflow.com/comment/84054672
has title: Python with Excel, counting the cells
has comment: http://stackoverflow.com/comment/84054980
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84054747

http://stackoverflow.com/a/48587460
answers question: http://stackoverflow.com/q/48587192
downvote count: 0
upvote count: 1
has body: You can also use scipy.stats.stats to calculate a Pearson correlation. At a minimum, you can use this as a quick check your algorithm is correct. from scipy.stats.stats import pearsonr import pandas as pd a = pd.Series([2, 4, 5, 7, 9]) b = pd.Series([12, 10, 9, 7, 3]) pearsonr(a, b)[0] # -0.98466166762781315
score: 1
type: Answer

http://stackoverflow.com/q/48620355
accepted answer: http://stackoverflow.com/a/48629375
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48629104
answer count: 2
has answer: http://stackoverflow.com/a/48629375
linked to: http://stackoverflow.com/q/13269890
downvote count: 0
favorite count: 0
has title: Python - inefficient spatial distance calculation (how can it be speed up)
tagged with: performance
type: Question
tagged with: algorithm
has body: I am currently trying some geocoding in Python. The process is the following: I have two data frames (df1 and df2, houses and schools) with latitude and longitude values and want to find the nearest neighbour in df2 for every observations in df1. I use the following code: from tqdm import tqdm import numpy as np import pandas as pd import math def distance(lat1, long1, lat2, long2): R = 6371 # Earth Radius in Km dLat = math.radians(lat2 - lat1) # Convert Degrees 2 Radians dLong = math.radians(long2 - long1) lat1 = math.radians(lat1) lat2 = math.radians(lat2) a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLong/2) * math.sin(dLong/2) * math.cos(lat1) * math.cos(lat2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = R * c return d dists = [] schools =[] for index, row1 in tqdm(df1.iterrows()): for index, row2 in df2.iterrows(): dists.append(distance(row1.lat, row1.lng, row2.Latitude, row2.Longitude)) schools.append(min(dists)) del dists [:] df1["school"] = pd.Series(schools) The code works, however it takes ages. With tqdm I get an average speed of 2 iterations of df1 per second. As a comparison, I did the whole task in STATA with geonear and it takes 1 second for all observations in df1 (950). I read in the helpfile of geonear that they use clustering, to not calculate all distances, but only the closest. However, before I add a clustering function (which might also take CPU power), I wonder if someone sees some way to speed up the process as it is (I am new to python and might have some inefficient code that slows the process down). Or is there maybe a package that does the process faster? I would be ok if it takes longer than in STATA, but not nearly 7 minutes... Thank you in advance
tagged with: geospatial
tagged with: python
has answer: http://stackoverflow.com/a/48629104
score: 4
upvote count: 4
tagged with: distance

http://stackoverflow.com/comment/83983363
score: 0
type: Comment
type: AnswerComment
has text: Additionally if your intent was how to run this specific command from the beginning you will get better results on this site if you post the full context in your question.
comment on: http://stackoverflow.com/a/48494938

http://stackoverflow.com/a/48535384
has comment: http://stackoverflow.com/comment/84066277
has comment: http://stackoverflow.com/comment/84084648
type: Answer
answers question: http://stackoverflow.com/q/48535294
has comment: http://stackoverflow.com/comment/84066393
has comment: http://stackoverflow.com/comment/84066592
score: 0
has comment: http://stackoverflow.com/comment/84066356
has comment: http://stackoverflow.com/comment/84066309
has body: There is no explicit function in ConfigParser. You need to code that yourself. To keep going in your case you should try: if cmd_arguments.function_2: function_2(configParser.getint('Output', 'function_1'), b) if cmd_arguments.function_2 or cmd_arguments.function_3: function_3(configParser.getint('Output', 'function_2'), if cmd_arguments.function_2 or cmd_arguments.function_3 or \ cmd_arguments.function_4: function_4(configParser.getint('Output', 'function_2'),

http://stackoverflow.com/a/48543741
score: 0
answers question: http://stackoverflow.com/q/48543651
type: Answer
has body: String is a sequence of characters. Join function concatenates the sequence (iterable) to a new string by joining them on the string you called the function on. In this case it's s with value of 'HI'. Its not different than: print(" ".join("hello", "world")) That results in "hello world".

http://stackoverflow.com/comment/84205337
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48598219
has text: @crafter: `c,_ = ...` just means to get the two arguments returned by `accept` but ignore the second one since it is not needed in the code. See also https://stackoverflow.com/questions/26251861/how-to-elegantly-ignore-some-return-values-of-a-python-function
type: AnswerComment

http://stackoverflow.com/q/48518575
has answer: http://stackoverflow.com/a/48519309
answer count: 1
tagged with: user-interface
tagged with: wxpython
has body: So I have a small app. The gist of it is just a window with a button in the center of the main frame. When you click the button, the button gets hidden and a gauge/loading bar appears in the center of the main frame and fills up as it does some computations( the filling up part is not implemented yet, at the moment it's just an empty gauge that sits there). The button and the gauge are each implemented in their own panels, and to "switch" between them I just disable an hide the button panel and then enable and show the gauge panel. To switch back I just reverse that process. Pretty straight forward. Now, as a test I wanted the button, when clicked, to just switch to the gauge for a couple seconds and the switch back(using Sleep()). This is the relevant code(please ask for more if you consider it would be relevant): import wx import time import gui_base class MainFrame(gui_base.main_frame): def __init__(self): super(MainFrame, self).__init__(None) self.set_state_pre_compare() def set_state_pre_compare(self): self.panel_in_compare_panel.Disable() self.panel_in_compare_panel.Hide() print('done hiding in') self.panel_pre_compare_panel.Enable() self.panel_pre_compare_panel.Show() print('done enabling pre') self.Layout() def set_state_in_compare(self): self.panel_pre_compare_panel.Disable() self.panel_pre_compare_panel.Hide() print('done hiding pre') self.panel_in_compare_panel.Enable() self.panel_in_compare_panel.Show() print('done enabling in') self.Layout() def on_compare_button_click(self, event): self.set_state_in_compare() time.sleep(2.5) self.set_state_pre_compare() if __name__ == '__main__': app = wx.App(True) frame = MainFrame() frame.Show() app.MainLoop() The pre and in panels refer to "pre computation"(panel with the button, computations not yet started) and "in computation"(panel with the gauge, computations started) My big problem is this: the app starts up fine, I click the button, the button disappears just fine, however the loading bar does not show at all…
has title: wxPython panel not showing at Show()
tagged with: python
type: Question
tagged with: python-3.x
tagged with: wxwidgets
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/84239907
score: 0
type: AnswerComment
has text: Did you got any result while executing `data[data.isnull()]` ?
comment on: http://stackoverflow.com/a/48621452
type: Comment

http://stackoverflow.com/q/48509493
has comment: http://stackoverflow.com/comment/84013879
duplicate of: http://stackoverflow.com/q/13638898
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48509516
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/48509516
has body: I tried to use the map function in Python, and got the lazy evaluation figures of 0x000002131F50ECC0 as an output. How can I ask Python to calculate the value instead of giving me an address? Thanks in advance! Code:- A = [1, 2] B = [3, 4] min_value = map(min, A, B) print(min_value) Result:- &lt;map object at 0x000002131F50ECC0&gt;
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/13638898
has title: How to ask Python to show the lazy evaluation figures of <0x...>?
upvote count: 0
score: -3

http://stackoverflow.com/comment/84281586
has text: I watched that recently already. His space-efficiency advertisement was for dictionaries of size **5**, which are so small that 76 bytes indeed are significant. But with the OP's "many hundred million" items that's nothing. Also, what do you mean with "sequential keys"?
comment on: http://stackoverflow.com/a/48640317
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84191852
score: 0
has text: @mhawke How should I use form.save() ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48597139

http://stackoverflow.com/q/48587088
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48592398
tagged with: matplotlib
tagged with: python
has title: "Tube" Arrows in Python
score: 0
tagged with: visualization
tagged with: 3d
answer count: 1
has comment: http://stackoverflow.com/comment/84171592
linked to: http://stackoverflow.com/q/36464982
type: Question
has body: I am looking for a way to draw a few (O(1)) 3D arrows with python, which are "proper 3D", by which I mean something along the lines of what Mathematica yields, i.e. rod of the arrow looks like a tube. I did not find anything in the matplotlib documentation, but surely there must be a way?

http://stackoverflow.com/comment/84184213
has text: Your situation is more like the last paragraph of "where to patch", where it says if module `b` does `import a` and uses `a.SomeClass`, then you should patch `a.SomeClass` (not `b.a.SomeClass`). That would be a global change, though. There's nothing in the "where to patch" examples where you only want to mock one module's use of another module and leave all other uses unchanged.
score: 1
comment on: http://stackoverflow.com/q/48593427
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48543438
has answer: http://stackoverflow.com/a/48543569
type: AnsweredQuestion
downvote count: 0
upvote count: 1
tagged with: string
score: 1
accepted answer: http://stackoverflow.com/a/48543497
favorite count: 0
possible better answer: http://stackoverflow.com/a/48543569
has answer: http://stackoverflow.com/a/48543497
has title: How can you terminate a string after k consecutive numbers have been found?
answer count: 4
type: Question
has body: Say I have some list with files of the form *.1243.*, and I wish to obtain everything before these 4 digits. How do I do this efficiently? An ugly, inefficient example of working code is: names = [] for file in file_list: words = file.split('.') for i, word in enumerate(words): if word.isdigit(): if int(word)&gt;999 and int(word)&lt;10000: names.append(' '.join(words[:i])) break print(names) Obviously though, this is far from ideal and I was wondering about better ways to do this.
has answer: http://stackoverflow.com/a/48543637
tagged with: python
tagged with: optimization
has answer: http://stackoverflow.com/a/48544481

http://stackoverflow.com/comment/84097253
has text: There's nothing quite that straightforward, but you might have more readable solutions, depending on the variability of your keys (headers). How much variability do you have in the supplied fields? For instance, are you guaranteed that *some* dict will have *all* of the keys? If so, you can glean your headers from the longest dict. Will each dict have the first key, or the last? These can help with constructing an ordered list. If none of those, you will likely need to apply something like a topological sort on the partial orderings.
score: 0
comment on: http://stackoverflow.com/q/48550553
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48515560
has comment: http://stackoverflow.com/comment/84029311
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48510411
has body: You have to wait until the video title has been changed. See my code below. I created a custom wait class to compare new title and old title. However, you might face an ads video which will block nextVideo.click(), you need to handle that to make this code works completely. class element_text_changed(object): def __init__(self, locator, oldTitle): self.locator = locator self.oldTitle = oldTitle def __call__(self, browser): wait = WebDriverWait(browser, 10) titleElement = wait.until(EC.visibility_of_element_located(self.locator)) newTitle = titleElement.text.strip() print("OLD: " + self.oldTitle + ", NEW: " + newTitle) if len(self.oldTitle)==0 or (self.oldTitle!=newTitle): return titleElement else: return False oldTitle = '' for x in range(1, 7): wait = WebDriverWait(browser, 20) title = wait.until(element_text_changed((By.CSS_SELECTOR, 'h1.title'), oldTitle)).text print(title) oldTitle = title wait = WebDriverWait(browser, 10) positiveVotes = wait.until(EC.visibility_of_element_located( (By.CSS_SELECTOR, 'ytd-toggle-button-renderer.style-text:nth-child(1) &gt; a:nth-child(1) &gt; yt-formatted-string:nth-child(2)'))).text ...

http://stackoverflow.com/a/48511986
downvote count: 0
type: Answer
score: 4
upvote count: 4
has body: Since the dot rule is 'last of A with 2nd to the last of B', you can do X.dot(betas) and get a (n,d,r) array (this sums on the shared p dimension). Then you just need a transpose to get (d,n,r) In [200]: X.dot(betas).transpose(1,0,2) Out[200]: array([[[ 6, 12], [ 12, 24], [ 18, 36], [ 24, 48]], [[ 30, 36], [ 60, 72], [ 90, 108], [120, 144]]]) We can also write the einsum version directly from the dimensions specification: np.einsum('np,dpr-&gt;dnr', X,betas) So does matmul (this does dot on the last 2 axes, while d comes along for the ride). X@betas If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.
has comment: http://stackoverflow.com/comment/84018984
answers question: http://stackoverflow.com/q/48511256
has comment: http://stackoverflow.com/comment/84019097

http://stackoverflow.com/q/48632016
has comment: http://stackoverflow.com/comment/84261457
tagged with: python
has comment: http://stackoverflow.com/comment/84261163
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48632052
downvote count: 0
has answer: http://stackoverflow.com/a/48632052
has title: Concatenate range-like sequence to list of tuples
has comment: http://stackoverflow.com/comment/84261187
possible better answer: http://stackoverflow.com/a/48632360
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48632360
answer count: 2
upvote count: 2
has body: I have a list of tuples like so. rows = [] r1 = ('one.csv', 230) r2 = ('two.xls', 932) rows.append(r1) rows.append(r2) I want to add a third element to each tuple in the list, an integer key for use in a sql database. I have to wait until rows has been filled up like this before I adding the additional elements. In this example, I want the tuples to look like ('one.csv', 230, 0) and ('two.xls', 930, 1). In general, these key-integers won't start at one. It's a simple operation but I'm wondering if there's a more pythonic way to do it (i.e., not use a for loop). My other idea was to convert to a pandas data frame, but I thought the approach below was better than converting to and from a data frame. rows2 = [] count = 0 for r in rows: rows2.append(r + (count,)) count += 1

http://stackoverflow.com/q/48641406
has answer: http://stackoverflow.com/a/48914042
favorite count: 0
type: Question
tagged with: mocking
linked to: http://stackoverflow.com/q/32402502
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84810839
tagged with: python
upvote count: 4
score: 4
has body: I want to test a class that does logging when initialised and save logs to local file. Therefore, I'm mocking the logging piece of logic in order to avoid file IO when testing. This is pseudo-code representing how I've structured the tests class TestClass: def test_1(self, monkeypatch): monkeypatch.setattr('dotted.path.to.logger', lambda *args: '') assert True def test_2(self, monkeypatch): monkeypatch.setattr('dotted.path.to.logger', lambda *args: '') assert True def test_3(self, monkeypatch): monkeypatch.setattr('dotted.path.to.logger', lambda *args: '') assert True Note how monkeypatch.setattr() is copy-pasted across all methods. Considering that: we know a priori that all call methods will need to be monkey-patched in the same way, and one might forget to monkeypatch new methods, I think that monkey-patching should be abstracted at class level. How do we abstract monkeypatching at class level? I would expect the solution to be something similar to what follows: import pytest class TestClass: pytest.monkeypatch.setattr('dotted.path.to.logger', lambda *args: '') def test_1(self): assert True def test_2(self): assert True def test_3(self): assert True This is where loggers are configured. def initialise_logger(session_dir: str): """If missing, initialise folder "log" to store .log files. Verbosity: CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET.""" os.makedirs(session_dir, exist_ok=True) logging.basicConfig(filename=os.path.join(session_dir, 'session.log'), filemode='a', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S', format='|'.join(['(%(threadName)s)', '%(asctime)s.%(msecs)03d', '%(levelname)s', '%(filename)s:%(lineno)d', '%(message)s'])) # Adopt NYSE time zone (aka EST aka UTC -0500 aka US/Eastern). Source: # https://stackoverflow.com/questions/32402502/how-to-change-the-time-zone-in-python-logging logging.Formatter.converter = lambda *args: get_now().timetuple() # Set verbosity in console. Verbosity above logging level is ignored. console = logging.StreamHandle…
tagged with: logging
tagged with: monkeypatching
has answer: http://stackoverflow.com/a/48902806
answer count: 2
has comment: http://stackoverflow.com/comment/84793958
tagged with: pytest
has title: Preventing logging file IO during test execution
downvote count: 0
has comment: http://stackoverflow.com/comment/84834293

http://stackoverflow.com/a/48580850
accepted answer of: http://stackoverflow.com/q/48580506
has comment: http://stackoverflow.com/comment/84169093
type: Answer
score: 3
has body: Use isin with dict comprehension: df=pd.DataFrame(['a','b','c']) df.columns=['myvar'] df = df.set_index(['myvar']) list_of_interest_1=['b','c','d','z'] list_of_interest_2=['a'] list_of_interest_3=['duck'] d = {'list_of_interest_1':list_of_interest_1, 'list_of_interest_2':list_of_interest_2, 'list_of_interest_3': list_of_interest_3} for k, v in d.items(): df[k] = df.index.isin(v) df = df.sort_index(axis=1) print(df) list_of_interest_1 list_of_interest_2 list_of_interest_3 myvar a False True False b True False False c True False False
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48580506
downvote count: 0

sockets
tags question: http://stackoverflow.com/q/48597915
tags question: http://stackoverflow.com/q/48546308
tags question: http://stackoverflow.com/q/48584598
tags question: http://stackoverflow.com/q/48582400
tags question: http://stackoverflow.com/q/48594522
tags question: http://stackoverflow.com/q/48514724
tags question: http://stackoverflow.com/q/48521184
tags question: http://stackoverflow.com/q/48613006
tags question: http://stackoverflow.com/q/48507367
tags question: http://stackoverflow.com/q/48499713
tags question: http://stackoverflow.com/q/48560896
tags question: http://stackoverflow.com/q/48625102
tags question: http://stackoverflow.com/q/48610797
tags question: http://stackoverflow.com/q/48601182
tags question: http://stackoverflow.com/q/48544571
tags question: http://stackoverflow.com/q/48502444
tags question: http://stackoverflow.com/q/48492812
tag name: sockets
tags question: http://stackoverflow.com/q/48548639
tags question: http://stackoverflow.com/q/48531883
tags question: http://stackoverflow.com/q/48600677
tags question: http://stackoverflow.com/q/48588445
tags question: http://stackoverflow.com/q/48561871
tags question: http://stackoverflow.com/q/48549589
tags question: http://stackoverflow.com/q/48506460
tags question: http://stackoverflow.com/q/48640001
tags question: http://stackoverflow.com/q/48508018
tags question: http://stackoverflow.com/q/48598089
tags question: http://stackoverflow.com/q/48616936
tags question: http://stackoverflow.com/q/48565948
tags question: http://stackoverflow.com/q/48513869
type: Tag
tags question: http://stackoverflow.com/q/48634711
tags question: http://stackoverflow.com/q/48522920
tags question: http://stackoverflow.com/q/48600409
tags question: http://stackoverflow.com/q/48496982
tags question: http://stackoverflow.com/q/48554441

http://stackoverflow.com/comment/84111254
type: QuestionComment
has text: create an environment variable with `project-path` and use that in sys.path.append. configure the `project path`, whenever moved the project code.
score: 0
comment on: http://stackoverflow.com/q/48557738
type: Comment

http://stackoverflow.com/a/67750227
has body: 2021 update now there is pymeshlab, which allows automatization of meshlab processing through python!
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48523195

http://stackoverflow.com/q/48558990
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: keras
upvote count: 3
score: 3
has body: I am beginning to build CNN models using Keras. I have built a CNN with a fairly accurate results using the following architecture. classifier = Sequential() classifier.add(Convolution2D(32, (3,3), input_shape = (64, 64, 3), activation='relu')) classifier.add(MaxPool2D(pool_size = (2,2))) classifier.add(Convolution2D(32, (3,3), activation='relu')) classifier.add(MaxPool2D(pool_size = (2,2))) classifier.add(Convolution2D(32, (3,3), activation='relu')) classifier.add(MaxPool2D(pool_size = (2,2))) classifier.add(Convolution2D(32, (3,3), activation='relu')) classifier.add(MaxPool2D(pool_size = (2,2))) classifier.add(Flatten()) classifier.add(Dense(units=128, activation='relu')) classifier.add(Dropout(rate = 0.25)) classifier.add(Dense(units=128, activation='relu')) classifier.add(Dropout(rate = 0.25)) classifier.add(Dense(units=1, activation='sigmoid')) classifier.compile(optimizer = 'sgd', loss = 'binary_crossentropy', metrics=['accuracy']) What I want to do is to run my images through the model, but only the convolutional steps. I am interested in the output of the Flattening process (i.e. get the features from the convolutional steps). Can someone help me how I can get it in Keras? Thanks in advance
has answer: http://stackoverflow.com/a/48560420
favorite count: 0
type: Question
has title: Keras CNN get output from the Convolutional steps
downvote count: 0
tagged with: convolution

http://stackoverflow.com/comment/84023505
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48512043
score: 0
has text: @Divakar I see. So, hpaulj contends that `np.tensordot` uses `np.dot`. I think I'll have to go over the code to get a good grasp of what's happening... I really hope that NumPy devs start implementing support for GPUs well early.. :)

http://stackoverflow.com/a/48582974
answers question: http://stackoverflow.com/q/48582675
score: 0
type: Answer
has body: As far as I know, there is no way to obtain the coefficients with interp1d, but you could use splrep instead. It can be used to fit a b-spline and you can set the degree to cubic. It returns a tuple (t,c,k) containing the vector of knots t, the coefficients c and the degree k.

http://stackoverflow.com/comment/84091266
comment on: http://stackoverflow.com/q/48547420
score: 1
has text: You should mention your context in the question, providing a [mcve]. In this case I was mislead to believe you are using maybe `numpy.roots()`.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84193554
type: Comment
type: QuestionComment
has text: I would suggest to use another data-structure. Can't you just store them as `"point`" and `"feature"` together with a number telling how many you have of them?
comment on: http://stackoverflow.com/q/48598222
score: 0

http://stackoverflow.com/q/48509382
tagged with: delay
tagged with: python
has comment: http://stackoverflow.com/comment/84014343
has body: I have a function that takes x amount of time to run. This time follows approximately a standard distribution. Now I want this function to be executed y times per minute or per hour. How would I adjust the delays after each call to achieve that? I am guessing that I would have to time and average the last 10(maybe?) calls, see how long they took and then make the adjustments in the delays based on that? Similar to how fps are controlled. I can't however wrap my head around exactly how to do that. Than you. pseudocode: def repeat_x_per_hour(reps_per_hour): start_time = time.time() while(true): function(a,b,c) ellapsed_time = time.time()-start_time sleep(some_func_of_ellapsed_time(ellapsed_time, reps_per_hour))
has comment: http://stackoverflow.com/comment/84013864
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48530616
tagged with: sleep
type: Question
has title: Adjust sleep() to ensure a constant rate as accurately as possible
type: UnansweredQuestion
tagged with: rate

http://stackoverflow.com/comment/83982912
type: QuestionComment
comment on: http://stackoverflow.com/q/48494817
score: 0
has text: Why does BB go with LB and not L?
type: Comment

http://stackoverflow.com/q/48530730
has comment: http://stackoverflow.com/comment/84060142
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48530826
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84058037
favorite count: 0
has comment: http://stackoverflow.com/comment/84057068
has comment: http://stackoverflow.com/comment/84057608
has comment: http://stackoverflow.com/comment/84057450
has answer: http://stackoverflow.com/a/48531713
has comment: http://stackoverflow.com/comment/84059622
linked to: http://stackoverflow.com/q/27743900
type: Question
has comment: http://stackoverflow.com/comment/84060258
tagged with: math
tagged with: python
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/84056933
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84059538
has body: Heres my code run it: def mySeq(n): seq = 1 currentNumber = 1 tickIn = False for x in range(0,n): if (tickIn == True): currentNumber = (currentNumber / 4) tickIn = False else: currentNumber = currentNumber + 6 tickIn = True print(currentNumber) Output of mySeq(75): mySeq(75) 7 1.75 7.75 1.9375 7.9375 1.984375 7.984375 1.99609375 7.99609375 1.9990234375 7.9990234375 1.999755859375 7.999755859375 1.99993896484375 7.99993896484375 1.9999847412109375 7.9999847412109375 1.9999961853027344 7.999996185302734 1.9999990463256836 7.999999046325684 1.999999761581421 7.999999761581421 1.9999999403953552 7.999999940395355 1.9999999850988388 7.999999985098839 1.9999999962747097 7.99999999627471 1.9999999990686774 7.999999999068677 1.9999999997671694 7.999999999767169 1.9999999999417923 7.999999999941792 1.999999999985448 7.999999999985448 1.999999999996362 7.999999999996362 1.9999999999990905 7.9999999999990905 1.9999999999997726 7.999999999999773 1.9999999999999432 7.999999999999943 1.9999999999999858 7.999999999999986 1.9999999999999964 7.9999999999999964 1.9999999999999991 7.999999999999999 1.9999999999999998 8.0 2.0 8.0 2.0 8.0 2.0 8.0 2.0 8.0 2.0 8.0 2.0 8.0 2.0 8.0 2.0 8.0 2.0 8.0 2.0 8.0 2.0 8.0 Now why does it do this to a limit but then break into whole numbers? - Mathematically? I've tried this with another pair of commons and it produces the same type of output reaching a LIMIT.
has title: Python - Mathematical Sequence I've Created Which Is Cool But I Don't Understand The Meaning

macos
tags question: http://stackoverflow.com/q/48573184
tags question: http://stackoverflow.com/q/48614996
tags question: http://stackoverflow.com/q/48515595
tags question: http://stackoverflow.com/q/48575834
tags question: http://stackoverflow.com/q/48507359
tags question: http://stackoverflow.com/q/48577341
tags question: http://stackoverflow.com/q/48574538
tags question: http://stackoverflow.com/q/48518891
tags question: http://stackoverflow.com/q/48519001
tags question: http://stackoverflow.com/q/48599872
tags question: http://stackoverflow.com/q/48640143
tags question: http://stackoverflow.com/q/48552934
type: Tag
tags question: http://stackoverflow.com/q/48570796
tags question: http://stackoverflow.com/q/48520276
tags question: http://stackoverflow.com/q/48500152
tags question: http://stackoverflow.com/q/48641879
tags question: http://stackoverflow.com/q/48501966
tag name: macos
tags question: http://stackoverflow.com/q/48513591
tags question: http://stackoverflow.com/q/48532060
tags question: http://stackoverflow.com/q/48620855
tags question: http://stackoverflow.com/q/48568462

http://stackoverflow.com/q/48510355
upvote count: 1
linked to: http://stackoverflow.com/q/18499497
tagged with: multithreading
answer count: 1
has comment: http://stackoverflow.com/comment/84015697
favorite count: 0
type: AnsweredQuestion
has body: I have created a program that runs X number of threads which all need to be able to be closed down by the main thread. Currently I can stop the program so that each thread will be abruptly killed. I want to be able to detect the close and handle it more gracefully. To do this I want to use the join() function, which waits for the threads to finish. The issue is that the threads don't have a set end and so calling join() would mean that the main thread will wait forever for the threads to end. So the question is. Is there a way to detect a join() call in a thread and write a customized response to it?
score: 1
has comment: http://stackoverflow.com/comment/84015721
tagged with: python
has title: Python threading: Is there a way to detect a join() call in a thread?
has answer: http://stackoverflow.com/a/48510409
tagged with: pthread-join
accepted answer: http://stackoverflow.com/a/48510409
has comment: http://stackoverflow.com/comment/84015651
type: Question
tagged with: python-3.x
downvote count: 0
has comment: http://stackoverflow.com/comment/84015732

http://stackoverflow.com/comment/84257697
type: Comment
type: QuestionComment
has text: If it is not the points themselves that define the surface, what else would it be? What is the property of the surface and according to what data do you want to draw it? At the moment this does not seem like a programming question at all.
score: 1
comment on: http://stackoverflow.com/q/48630246

http://stackoverflow.com/comment/84266564
score: 0
has text: When you are creating the object/instance of the class you are passing only 2 variables but the `__init__()` requires 3 variables. This is the error you are getting. You never reach the definition/body of `__init__()` so none of the exception is caught.
comment on: http://stackoverflow.com/q/48633650
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48642694
has comment: http://stackoverflow.com/comment/84281853
upvote count: 2
tagged with: math
tagged with: python
tagged with: newtons-method
score: 2
has title: Newton Raphson: Can the user input the function?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48643105
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48643105
has body: [This image here is my python code for the Newton-Raphson method. The problem is with the mathematical function and the derivative. At the moment I am the one who specifies the function and its derivative. Is there any way to get the user to input the function that he/she desires? import math """ f: function, f_ : derivative of function, x0: initial guess, errortolerance: tolerance, maxIter: max number of iterations """ def newtonraphson(f, f_, x0, errortolerance=0.00001, maxIter=100): """ Take a function f, its derivative f_, initial value x0, TOL and NMAX, and returns the root(s) of the equation using the NR method """ n = 1 #initial numebr of iterations while n&lt;=maxIter: # check while n less than maxIter x1 = x0 - (f(x0)/f_(x0)) #newtonraphson formula if x1 - x0 &lt; errortolerance: return x1 else: x0 = x1 return False if __name__ == "__main__": def func(x): #initial function return 5*math.pow(x,2) - 8*math.pow(x,1) + 4 def func_(x): #its derivative return 10*math.pow(x,1) - 8 resNR = newtonraphson(func,func_,3) #result of newtonraphson print(resNR)
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84286474
has comment: http://stackoverflow.com/comment/84282646
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/48526973
has title: How do I find ten biggest contours?
has comment: http://stackoverflow.com/comment/84048874
tagged with: contour
tagged with: find
type: UnansweredQuestion
answer count: 1
type: Question
tagged with: area
tagged with: opencv
score: 0
has body: I'm new to OpenCV and I don't understand deeply what I'm doing. I'm looking for ten biggest light polluted areas in a photo of the dark side of the Earth. After I've found the contours of every light polluted area, how do I create a variable with ten biggest contours? I've tried biggest_contours=(0,0,0,0,0,0,0,0,0,0) for enum,contour in enumerate(contours): for item in biggest_contours: if cv2.contourArea(contours[enum])&gt;cv2.contourArea(contours[item]): biggest_contours[item]=enum but it returns "TypeError: 'tuple' object does not support item assignment"
tagged with: python
has answer: http://stackoverflow.com/a/48527134

http://stackoverflow.com/a/48613193
answers question: http://stackoverflow.com/q/48613158
type: Answer
score: 3
upvote count: 3
has body: You could transpose first, and then save to excel: df 0 0 1 1 2 2 3 3 4 4 5 df.T.to_excel(writer, sheet_name=sheetname, startrow=1, startcol=1, header=False, index=False) 1 2 3 4 5
downvote count: 0

python-3.x
tags question: http://stackoverflow.com/q/48630248
tags question: http://stackoverflow.com/q/48606334
tags question: http://stackoverflow.com/q/48645232
tags question: http://stackoverflow.com/q/48612009
tags question: http://stackoverflow.com/q/48630419
tags question: http://stackoverflow.com/q/48588717
tags question: http://stackoverflow.com/q/48586146
tags question: http://stackoverflow.com/q/48590397
tags question: http://stackoverflow.com/q/48605016
tags question: http://stackoverflow.com/q/48551038
tags question: http://stackoverflow.com/q/48566534
tags question: http://stackoverflow.com/q/48631131
tags question: http://stackoverflow.com/q/48501822
tags question: http://stackoverflow.com/q/48546690
tags question: http://stackoverflow.com/q/48613919
tags question: http://stackoverflow.com/q/48556919
tags question: http://stackoverflow.com/q/48521783
tags question: http://stackoverflow.com/q/48584949
tags question: http://stackoverflow.com/q/48495675
tags question: http://stackoverflow.com/q/48599880
tags question: http://stackoverflow.com/q/48500764
tags question: http://stackoverflow.com/q/48543737
tags question: http://stackoverflow.com/q/48532943
tags question: http://stackoverflow.com/q/48567880
tags question: http://stackoverflow.com/q/48503094
tags question: http://stackoverflow.com/q/48553276
tags question: http://stackoverflow.com/q/48630019
tags question: http://stackoverflow.com/q/48505902
tags question: http://stackoverflow.com/q/48508702
tags question: http://stackoverflow.com/q/48631408
tags question: http://stackoverflow.com/q/48612634
tags question: http://stackoverflow.com/q/48511319
tags question: http://stackoverflow.com/q/48604263
tags question: http://stackoverflow.com/q/48598276
tags question: http://stackoverflow.com/q/48571848
tags question: http://stackoverflow.com/q/48598508
tags question: http://stackoverflow.com/q/48613380
tags question: http://stackoverflow.com/q/48606710
tags question: http://stackoverflow.com/q/48568462
tags question: http://stackoverflow.com/q/48531928
tags question: http://stackoverflow.com/q/48569243
tags question: http://stackoverflow.com/q/48562439
tags question: http://stackoverflow.com/q/48531944
tags question: http://stackoverflow.com/q/48517133
tags question: http://stackoverflow.com/q/48601771
tags question: http://stackoverflow.com/q/48504813
tags question: http://stackoverflow.com/q/48528694
tags question: http://stackoverflow.com/q/48589216
tags question: http://stackoverflow.com/q/48516893
tags question: http://stackoverflow.com/q/48575598
tags question: http://stackoverflow.com/q/48623544
tags question: http://stackoverflow.com/q/48562051
tags question: http://stackoverflow.com/q/48499398
tags question: http://stackoverflow.com/q/48616694
tags question: http://stackoverflow.com/q/48493533
tags question: http://stackoverflow.com/q/48504771
tags question: http://stackoverflow.com/q/48618902
tags question: http://stackoverflow.com/q/48557880
tags question: http://stackoverflow.com/q/48565948
tags question: http://stackoverflow.com/q/48526360
tags question: http://stackoverflow.com/q/48630484
tags question: http://stackoverflow.com/q/48635296
tags question: http://stackoverflow.com/q/48489753
tags question: http://stackoverflow.com/q/48569690
tags question: http://stackoverflow.com/q/48637559
tags question: http://stackoverflow.com/q/48499301
tags question: http://stackoverflow.com/q/48502586
tags question: http://stackoverflow.com/q/48623489
tags question: http://stackoverflow.com/q/48497073
tags question: http://stackoverflow.com/q/48612067
tags question: http://stackoverflow.com/q/48524099
tags question: http://stackoverflow.com/q/48526850
tags question: http://stackoverflow.com/q/48554683
tags question: http://stackoverflow.com/q/48612170
tags question: http://stackoverflow.com/q/48642694
tags question: http://stackoverflow.com/q/48529256
tags question: http://stackoverflow.com/q/48571554
tags question: http://stackoverflow.com/q/48510355
tags question: http://stackoverflow.com/q/48548817
tags question: http://stackoverflow.com/q/48635316

http://stackoverflow.com/a/48627846
has comment: http://stackoverflow.com/comment/84309295
has body: Use a virtual environment and try the following: sudo apt-get install build-essential libperl-dev python-dev python-pip cd /tmp wget https://sourceforge.net/projects/net-snmp/files/net-snmp/5.7.3/net-snmp-5.7.3.tar.gz/ cd net-snmp* ./configure make sudo make install download netsnmp and unpack it sudo pip install easysnmp
answers question: http://stackoverflow.com/q/48626673
score: 0
type: Answer

http://stackoverflow.com/a/48564392
type: Answer
downvote count: 0
score: 21
upvote count: 21
has body: Two options: (1) Using a generator In order to steer the animation dynamically you may use a generator, which yields new values in a while loop as long some condition is fulfilled. This could look as follows: reward = 0 def gen(): global reward i = 0 while reward &lt;= 10: i += 1 yield i def animate(i): global reward reward = update(reward) some_object[i] = func(reward) return some_object anim = animation.FuncAnimation(fig, animate, frames=gen, repeat = False) (2) Using a class with event_source.stop(). Alternatively you may stop the animation with anim.event_source.stop(). In order to have access to the animation inside the animating function one may use a class and make the animation a class variable. class Anim(): def __init__(self, fig, **kw): self.reward=0 self.ani = animation.FuncAnimation(fig, self.animate, frames=100, repeat = False) def animate(self,i): reward = update(reward) some_object[i] = func(reward) if self.reward &gt; 10: self.ani.event_source.stop() return some_object Note that both codes are untested because the question does not provide a test case.
answers question: http://stackoverflow.com/q/48564181

http://stackoverflow.com/a/48496432
downvote count: 0
has comment: http://stackoverflow.com/comment/83985748
answers question: http://stackoverflow.com/q/48496295
type: Answer
has comment: http://stackoverflow.com/comment/83985727
accepted answer of: http://stackoverflow.com/q/48496295
has body: Python does short circuit evaluation which is why you're seeing the behavior you are. This comes into play in and and or clauses similarly. With and clauses, if the expression on the left side evaluates to False there is no way the entire statement can evaluate to True (False and anything is False) so it doesn't bother to evaluate the expression on the right-hand side. If the left-hand side of expression is True, then the right-hand one is evaluated to see what the full expression should be. Similarly, with or clauses, if the expression on the left evaluates to True, there is no way the entire statement can be False since True or anything is always True. So again, the right-hand expression will not be evaluated. But if the left-hand expression is False, the right-hand one must be evaluated to know the value of the entire expression. You can see this in action here: &gt;&gt;&gt; def foo(): ... print('foo') ... return 0 &gt;&gt;&gt; def bar(): ... print('bar') ... return 1 &gt;&gt;&gt; foo() and bar() foo 0 &gt;&gt;&gt; bar() and foo() bar foo 0
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83985944
type: AcceptedAnswer

http://stackoverflow.com/a/48576096
has body: If you want to create both the values of the same key in the dictionary, one solution would be to add the old value to a list and append the new value to the list. Mail_Dict = { MailList0 : CodeList0, MailList2 : CodeList2, MailList3 : CodeList3, MailList4 : CodeList4 } Now if you want to add MailList1 (which has the same value as MailList0) to the dictionary, check if MailList1 already is a list. if it is not a list make it into a list and then append the new value. if(MailList1 in Mail_Dict): if (isinstance(Mail_Dict[MailList1],list)==False): Mail_Dict[MailList1] = [Mail_Dict[MailList1] Mail_Dict[MailList1].append(codeList1)
type: Answer
answers question: http://stackoverflow.com/q/48558908
score: 0

http://stackoverflow.com/comment/84061594
type: QuestionComment
has text: The linked page never says "got"
score: 0
comment on: http://stackoverflow.com/q/48524577
type: Comment

http://stackoverflow.com/comment/84102264
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48552542
has text: @EvanWeissburg batch_size=32. sentences can be quite large bodies of text, up to 2k-3k words or so.

http://stackoverflow.com/q/48591484
linked to: http://stackoverflow.com/q/4630465
has answer: http://stackoverflow.com/a/48591509
score: 2
answer count: 2
upvote count: 2
downvote count: 0
has body: I am trying to run a python script from another as follows, some of the arguments take quotes ("),how do I run this command with quotes? cmd = r"python ./clone.py -u username -rl %s -ra adar.py -d 13346612 -at "Cloning for automation" -m "Pace" -r "Cloning for automation" "%radar proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE) UPDATE#1:I tried the following suggestions but none of them worked (i)escape the quotes (ii)Use multi line quotes (iii)Use single quotes as delimiter UPDATE#2: I tried to run with shell=TRUE but the python script hungs
has title: How to run a python script from another python script?
favorite count: 0
has comment: http://stackoverflow.com/comment/84180241
type: Question
has comment: http://stackoverflow.com/comment/84181584
has comment: http://stackoverflow.com/comment/84180223
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48591522
has comment: http://stackoverflow.com/comment/84181490
tagged with: python

http://stackoverflow.com/comment/120863614
type: AnswerComment
score: 1
type: Comment
has text: This helped a lot thanks! One suggestion, if you are using python most of the steps above can be done easily using PyCharm. I downloaded 3.9 (latest python) pip'ed all the required packages (including pyinstaller) and got a small 20MB file.
comment on: http://stackoverflow.com/a/48662686

http://stackoverflow.com/q/48587070
accepted answer: http://stackoverflow.com/a/48587135
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48587251
has comment: http://stackoverflow.com/comment/84172431
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48587251
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48587135
has body: I have a nested dictionary set up that I'm trying to access but having trouble accessing the 'nextmo' part when the key is set to something my user decides (I've set to Feb in the example below). Ideally it should print 'Mar' D = {'Jan': {'days': 31, 'nextmo': 'Feb', 'prevmo': 'Dec'}, 'Feb': {'days': 29, 'nextmo': 'Mar', 'prevmo': 'Jan'}, 'Mar': {'days': 31, 'nextmo': 'Apr', 'prevmo': 'Feb'}, 'Apr': {'days': 30, 'nextmo': 'May', 'prevmo': 'Mar'}, 'May': {'days': 31, 'nextmo': 'Jun', 'prevmo': 'Apr'}, 'Jun': {'days': 30, 'nextmo': 'Jul', 'prevmo': 'May'}, 'Jul': {'days': 31, 'nextmo': 'Aug', 'prevmo': 'Jun'}, 'Aug': {'days': 31, 'nextmo': 'Sep', 'prevmo': 'Jul'}, 'Sep': {'days': 30, 'nextmo': 'Oct', 'prevmo': 'Aug'}, 'Oct': {'days': 31, 'nextmo': 'Nov', 'prevmo': 'Sep'}, 'Nov': {'days': 30, 'nextmo': 'Dec', 'prevmo': 'Nov'}, 'Dec': {'days': 31, 'nextmo': 'Jan', 'prevmo': 'Jan'},} bday_month_in = "Feb" for k, v in D.items(): if bday_month_in is dict: print(bday_month_in['nextmo'])
has title: Looping through a nested dictionary
tagged with: python
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/comment/84106904
has text: and it returns 3 records
comment on: http://stackoverflow.com/a/48551170
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48567502
type: Answer
answers question: http://stackoverflow.com/q/48567205
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84131646
has comment: http://stackoverflow.com/comment/84132634
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48567205
score: 3
has body: The value you looking for is inside a tag import requests from bs4 import BeautifulSoup def get_cric_info_articles(): cricinfo_article_link = "http://www.espncricinfo.com/ci/content/story/news.html" r = requests.get(cricinfo_article_link) cricinfo_article_html = r.text soup = BeautifulSoup(cricinfo_article_html, "html.parser") # print(soup.prettify()) cric_info_items = soup.find_all("h2", {"class": "story-title"}) cricinfo_article_dict = {} for div in cric_info_items: cricinfo_article_dict[div.find('a').string] = div.find('a')['href'] return cricinfo_article_dict print(get_cric_info_articles()) Output: {'Bell-Drummond leads MCC in curtain-raiser': '/ci/content/story/1135157.html', 'Scotland pick Brad Wheal, Chris Sole for World Cup qualifiers': '/scotland/content/story/1135152.html', 'Newlands working to be water independent': '/southafrica/content/story/1135120.html', 'Scorchers bow out after Hurricanes pile up 210': '/australia/content/story/1135117.html', "'Strong evidence' of corruption in Ajman All Stars League - ICC ": '/ci/content/story/1135108.html', 'Du Plessis 120 powers South Africa to 269': '/south-africa-v-india-2018/content/story/1135099.html', "Plan is to expose India's middle, lower order - Harris": '/australia/content/story/1135091.html', 'Top order, King fire Scorchers into WBBL final': '/australia/content/story/1135084.html', 'Technical change brings prolific run for Mominul': '/bangladesh/content/story/1135077.html', 'Dhananjaya, Mendis lead strong Sri Lanka reply': '/bangladesh/content/story/1135075.html'}

http://stackoverflow.com/q/48583922
type: Question
accepted answer: http://stackoverflow.com/a/48583986
has answer: http://stackoverflow.com/a/48583986
downvote count: 0
tagged with: python
type: AnsweredQuestion
has body: I'm doing some analysis on a beer dataset and was wanting to update NaN values of the "abv" column to use the mean values of the style. Here's a couple of items in the dataset I want to update: I'm trying to do this via a Pandas query and I can query by a specific style as a local variable: df.query("styleName == @style") However, I can't seem to find a way to add to this query a way to also return rows that have an "abv" of NaN. Is there a way to do that?
has title: Pandas query by local variable and get null values
tagged with: pandas
answer count: 1
upvote count: 1
score: 1
favorite count: 0

http://stackoverflow.com/a/48601661
type: Answer
answers question: http://stackoverflow.com/q/48593893
score: 0
has body: Problem Solved, I was able to use np and take the whole dataframe in one line instead of iterating : df['Husband_Education'] = np.where(df['Husband_Black']=='years', df['Husband_Education'].map(str) + ' ' +'years', df['Husband_Education'])

http://stackoverflow.com/a/48521611
has comment: http://stackoverflow.com/comment/84037970
has body: I think you need create dictionary of DataFrames: d = dict(tuple(df.groupby('app_version'))) print (d) {'v2': user_id session_id timestamp time_seconds app_version 3 3 477 2014-01-03 221 v2 4 4 121 2014-01-03 120 v2, 'v3': user_id session_id timestamp time_seconds app_version 5 5 921 2014-01-04 60 v3, 'v1': user_id session_id timestamp time_seconds app_version 0 1 123 2014-01-01 251 v1 1 2 845 2014-01-01 514 v1 2 3 741 2014-01-02 141 v1} print (d['v1']) user_id session_id timestamp time_seconds app_version 0 1 123 2014-01-01 251 v1 1 2 845 2014-01-01 514 v1 2 3 741 2014-01-02 141 v1 print (type(d['v1'])) &lt;class 'pandas.core.frame.DataFrame'&gt;
upvote count: 6
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/48521560
has comment: http://stackoverflow.com/comment/84037919
answers question: http://stackoverflow.com/q/48521560

http://stackoverflow.com/comment/84313850
comment on: http://stackoverflow.com/a/48639813
type: Comment
score: 0
type: AnswerComment
has text: Are we talking about inexact representation of floating numbers or about rounding procedure? Is `numpy`'s result due to the inexact representation of 0.6? Can Python *exactly* represent 0.6?

http://stackoverflow.com/q/48501080
answer count: 1
has comment: http://stackoverflow.com/comment/84001061
type: Question
has comment: http://stackoverflow.com/comment/83996054
has comment: http://stackoverflow.com/comment/84000724
has comment: http://stackoverflow.com/comment/83997904
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83996987
has comment: http://stackoverflow.com/comment/84001485
tagged with: matplotlib
tagged with: python
has body: I need to update an already existing figure. However I want it to be completely redrawn. I currently have: import matplotlib.pyplot as plt def plot_func(xdata, ydata, subplot_kw=None, axis_setters=None): fig, ax = plt.subplots(**subplot_kw) fig.clf() ax.cla() fig, ax = plt.subplots(**subplot_kw) if axis_setters: for setter_name, setter_value in axis_setters.items(): setter_func = getattr(ax, setter_name) setter_func(setter_value) plot(xdata, ydata) return fig, ax and then at later times it will be called with: plot_func([1,2,3], [1,2,3], subplot_kw={'num': 'name'}, axis_setters={'set_title': 'Title'}) The problem is, the awkward: fig, ax = plt.subplots(**subplot_kw) fig.clf() ax.cla() fig, ax = plt.subplots(**subplot_kw) I need it because I need to call plot_func an arbitrary amount of times, and each time I want it to produce the correct plot. If I don't have the second: fig, ax = plt.subplots(**subplot_kw) axis_setters entries don't work. If I don't have the fig.clf() recalls of the function overwrite the old figure and lines and text gets blurry. So what is the "correct" way of doing it? Okay it seems to be misunderstandable: Here is the plot without the first 3 lines after 10 calls: and here after 10 calls with the strange 3 lines at the beginning: Notice how the fonts get blurry, because, they get redrawn each time. This gets worse with each call. Its not an compression artifact or anything. It is, because the figure get not redrawn correctly. Now you might say: "Hey then just don't update the complete figure but only its data content" like they do here. The problem here is, that I cant change axes/figure properties any more. Take the e.g. axis_setters={'set_title': 'Title'} I gave in the beginning. If I remove the second fig, ax = plt.subplots(**subplot_kw) this call of a setter doesn't do anything any more. Same happens when you add a fig.canvas.draw() the title will still not show up. Edit: So this brings me almost there: import matplotlib.pyplot as plt def …
has comment: http://stackoverflow.com/comment/84000010
has comment: http://stackoverflow.com/comment/83996876
has comment: http://stackoverflow.com/comment/84000693
has comment: http://stackoverflow.com/comment/83996184
linked to: http://stackoverflow.com/q/4098131
score: 0
has answer: http://stackoverflow.com/a/48506141
has comment: http://stackoverflow.com/comment/83997004
linked to: http://stackoverflow.com/q/14694501
has title: Updating of figure properties by recalling one function
has comment: http://stackoverflow.com/comment/83998774

http://stackoverflow.com/q/48627387
has answer: http://stackoverflow.com/a/48627523
tagged with: format
has comment: http://stackoverflow.com/comment/84251925
has comment: http://stackoverflow.com/comment/84251779
upvote count: 1
score: 1
tagged with: datetime
has body: I have two different dates that I am pulling from a database using a SQL query. Im looking to do transformations in Python, but the two main dates I want to work with are stored in different formats. The first date is of the date format (YYYY/MM/DD) the other is of (YYYY/MM/DD HH:MM:SS) format. I want a difference in days so the DATETIME is irrelevant on the second date. I was wondering what is the easiest way to do this in python? Ideally, I would like to automate this, where I create a DATE format of the DATETIME variable, and take the difference between the two DATES. I've tried the following but I am also getting errors since I am dealing with Series. I am trying to get the delta for every row. df.delta = (df.DATETIME - df.DATE) and df.delta = datetime.timedelta(df.DATETIME - df.DATE)
has comment: http://stackoverflow.com/comment/84251648
tagged with: date
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48627564
possible better answer: http://stackoverflow.com/a/48627564
accepted answer: http://stackoverflow.com/a/48627523
answer count: 2
has title: Want to find difference, in days, between two dates, of different date format, in Python
downvote count: 0
tagged with: timedelta
has comment: http://stackoverflow.com/comment/84251803
tagged with: python
has comment: http://stackoverflow.com/comment/84251735
linked to: http://stackoverflow.com/q/3743222
type: AnsweredQuestion

http://stackoverflow.com/comment/84279358
type: Comment
has text: I think you misunderstood the code. One of the input lines is: `LL123-456`. The following would solve it I guess, but then it puts every answer in a list, which is not what I want: `for i in df.values.astype(str): if not re.findall("(.[A-Z]\d+\-\d+)", str(i)): print(re.findall(r'(\d+)', str(i)))`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48641238

http://stackoverflow.com/comment/84289232
type: AnswerComment
comment on: http://stackoverflow.com/a/48645978
type: Comment
has text: Thanks, Edwin, this is what I needed.
score: 0

http://stackoverflow.com/comment/84088717
comment on: http://stackoverflow.com/a/48546050
type: Comment
type: AnswerComment
score: 0
has text: I just took this piece of code from google as an example, but I think it was this one: https://www.exploit-db.com/exploits/16153/

http://stackoverflow.com/comment/84049834
has text: in my project i have a image folder inside static (so is project/static/images) and my variables in settings are: MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/') MEDIA_URL = '/' STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')], the image correctly show with an src of the full path to the image
comment on: http://stackoverflow.com/a/48526277
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48546827
has comment: http://stackoverflow.com/comment/84090146
has answer: http://stackoverflow.com/a/48547125
answer count: 7
tagged with: python
has comment: http://stackoverflow.com/comment/84089516
has body: I want to check if two strings are anagrams. For example, if my word is "halo", I want to check if those letters appear in "loha". It should match because it's an anagram. My attempt fails and I'm not sure why. My code and output is below. I have a list of words and I want to check to see which elements are anagrams in the list. def anagram(myList): for elem in myList: chars = set(elem) if all((c in chars) for c in myList): print "Yes, anagram ", elem, chars else: print "NOT anagram ", elem, chars wordsList = ["halo", "loha", "ahlo", "sully"] anagram(wordsList) And here's my output NOT anagram halo set(['a', 'h', 'l', 'o']) NOT anagram loha set(['a', 'h', 'l', 'o']) NOT anagram ahlo set(['a', 'h', 'l', 'o']) NOT anagram sully set(['y', 's', 'u', 'l'])
has answer: http://stackoverflow.com/a/48547362
has answer: http://stackoverflow.com/a/48547894
has title: Python: Check if all characters from a word exists in a string in any order
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84116045
has comment: http://stackoverflow.com/comment/84089601
possible better answer: http://stackoverflow.com/a/48547125
has comment: http://stackoverflow.com/comment/84089434
has comment: http://stackoverflow.com/comment/84089446
has comment: http://stackoverflow.com/comment/84089654
has comment: http://stackoverflow.com/comment/84089366
has comment: http://stackoverflow.com/comment/84089432
has comment: http://stackoverflow.com/comment/84089483
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48548399
linked to: http://stackoverflow.com/q/8286554
has comment: http://stackoverflow.com/comment/84089574
has answer: http://stackoverflow.com/a/48547090
downvote count: 0
has answer: http://stackoverflow.com/a/48547386
accepted answer: http://stackoverflow.com/a/48547090
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/48547097

http://stackoverflow.com/a/62724751
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48553303
has body: I needed commas in my csv file, too. So, I tried to get it using df but in vain. I decided to do the following. I read tap-separated text file, first, and write to a csv file with commas added. Not sure this is what you exactly want, but this way you can have commas in your csv file. Hope it helps. with open('test.txt', newline = '') as cos: co_reader = csv.reader(cos, delimiter='\t') with open('output.csv', 'w', newline='') as csvfile: cowriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL) for co in cog_reader: cowriter.writerow(co)

http://stackoverflow.com/q/48552394
type: Question
answer count: 5
possible better answer: http://stackoverflow.com/a/48552441
has answer: http://stackoverflow.com/a/48552480
has answer: http://stackoverflow.com/a/48552473
accepted answer: http://stackoverflow.com/a/48552437
has answer: http://stackoverflow.com/a/48552441
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48552437
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48262754
has body: I would like to sort a dict based on keys that have a pattern like "[0-9]+_[A-Z]+". I would like it to be ordered by ascending number. Here is where I am for the moment : import operator myDict = { '120_str' : 'value', '150_str' : 'value', '110_str' : 'value', '80_str' : 'value', '10_str' : 'value', '20_str' : 'value' } sortedDict = sorted(myDict.items(), key=operator.itemgetter(0)) What I actually have : sortedDict = { '10_str' : 'value', '110_str' : 'value', '120_str' : 'value', '150_str' : 'value', '20_str' : 'value', '80_str' : 'value' } What I would like to have : sortedDict = { '10_str' : 'value', '20_str' : 'value', '80_str' : 'value', '110_str' : 'value', '120_str' : 'value', '150_str' : 'value' }
upvote count: 2
has title: Sort a dict based on numbered keys
score: 1
has comment: http://stackoverflow.com/comment/84101363
tagged with: sorting
downvote count: 1
has comment: http://stackoverflow.com/comment/84101288
has answer: http://stackoverflow.com/a/48552535
favorite count: 0

http://stackoverflow.com/a/48661105
type: Answer
score: 0
has body: This Error is raised from the Function which Sends Email to Employee's Manager when Employee apply for Leave. This function searches for Employee's Manager and extract Manager's Email ID to send Leave Email for approval/rejection. But wait a minute, I had rule in Access Control List on the Group hr.employee which state that [('user_id', '=', user.id)] i.e. Employees can not see other Employees. Due to this access rule, Access Error Warning was being raised. So I made a little change in Send Email function, and extracted Manager's Email ID as a Super User. Super user by-passess Access Rights.
answers question: http://stackoverflow.com/q/48635607

http://stackoverflow.com/comment/84119007
type: Comment
has text: try some research... https://docs.python.org/2/tutorial/datastructures.html#more-on-lists
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/48561673

http://stackoverflow.com/q/48594583
answer count: 1
has body: I installed Anaconda a while ago and I'm very new to Python.. but I can't seem to figure this out. After the installation, everything seems to work okay, conda is a valid command however, when I do pip list in zsh and pip list in bash I get returned two very different lists. Bash displays everything that Anaconda came pre-packaged with and zsh does not, is there a way to get zsh to see all of those packages? I use zsh instead not bash Thanks!
has comment: http://stackoverflow.com/comment/84186584
type: Question
tagged with: zsh
has answer: http://stackoverflow.com/a/48674535
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84186224
score: 0
tagged with: anaconda
has title: Anaconda zsh pip list different from bash pip list Mac OS High Sierra

http://stackoverflow.com/comment/84279841
has text: To be clear: you are entirely in charge of both the decorator and the class? I.e. you're not trying to use some existing decorator and detect it, but you can define what the decorator does yourself?
comment on: http://stackoverflow.com/q/48641456
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84199465
has text: Always read the documentation before using anything.
comment on: http://stackoverflow.com/q/48601420
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48553681
tagged with: dictionary
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84103768
has body: I have some doubts with a python example. I want to have a function that receives a text file name as input and returns a dictionary in which each word, separated by space, is associated with a list with the number of the lines in which that word appears. For example for this example: Example of python program. Basic python program. The result should be: d['Example] = [1] d['of'] = [1] d['python']= [1,2] d['program'] = [1,2] d['Basic'] = [2] Im doing like below to read the text file, I have a test.txt file and I enter that test.txt file I don't see any results. with open(input("Enter Filename: "),'r') as inF: newDict = {} inF = open(input("Enter Filename: "),'r') for line in inF: splitLine = line.split() newDict[(splitLine[0])] = ",".join(splitLine[1:])
answer count: 1
accepted answer: http://stackoverflow.com/a/48553866
type: Question
has title: Read a text file and return a dictionary
has answer: http://stackoverflow.com/a/48553866
tagged with: python

http://stackoverflow.com/comment/84259750
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48629901
has text: Every example will have features not representative of the concept the example exemplifies. It's a matter of common sense not to rely on those.
type: Comment

http://stackoverflow.com/comment/84286941
type: Comment
type: QuestionComment
has text: This shows me all the groups that I already stated in my previous comments.
comment on: http://stackoverflow.com/q/48635607
score: 0

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

http://stackoverflow.com/a/48541956
type: Answer
score: 0
has body: You can use double groupby, also for 10 Minutes frequency use 10T, 10M is 10 end month frequency: df = df.groupby(pd.Grouper(key='datetime', freq='10T')).size() s = df.groupby(df.index.time).sum() s.plot()
answers question: http://stackoverflow.com/q/48541743

http://stackoverflow.com/comment/133436984
score: 1
has text: I see that this module hasn't been updated since 2018. https://github.com/sns-sdks/python-facebook seems to be more modern but I haven't tried it yet.
type: Comment
comment on: http://stackoverflow.com/a/60505702
type: AnswerComment

http://stackoverflow.com/comment/84071697
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48537668
type: QuestionComment
has text: This was just an example, because in the real project I receive data in real time. I edited the question with the real KEY and a real encrypted message received, so the key and the data corresponds. Sorry, I thought that an example would be enough to explain the problem

http://stackoverflow.com/comment/84105314
has text: Could you add some code for clarity? I think I follow what you're trying to do, but I'm not picturing what you're starting with very well.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48554394
type: Comment

http://stackoverflow.com/q/48589734
accepted answer: http://stackoverflow.com/a/48590235
has comment: http://stackoverflow.com/comment/84176747
has comment: http://stackoverflow.com/comment/84176644
linked to: http://stackoverflow.com/q/1398674
possible better answer: http://stackoverflow.com/a/48589994
type: Question
has answer: http://stackoverflow.com/a/48589994
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48590043
answer count: 3
tagged with: timezone
has title: Python - how to run function at a certain PST/PDT time?
has answer: http://stackoverflow.com/a/48590235
tagged with: python
has body: I'm beginning to learn python and I've tried to create a script to run a certain command at a certain time. This is what I have so far: import datetime day_of_week = datetime.date.today().weekday() # 0 is Monday, 6 is Sunday time = datetime.datetime.now().time() if day_of_week == 4 and (time &gt;= datetime.time(2,45) and time &lt; datetime.time(9)): #do something elif (day_of_week == 3 and time &gt; datetime.time(22)) or (day_of_week == 4 and time &lt; datetime.time(2,45)): #wait until 2h45 else: #do nothing I want the script to continue only on a certain day and when it's around 19h00 PST/PDT (2h45 GMT/UTC). The one I wrote works fine with GMT/UTC, but I'm certain that it will fail when daylight savings starts or if I change the local timezone to a different one. What could I do to make the script check for the current time in PST/PDT and continue from there, ignoring or converting the local timezone?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/83996863
comment on: http://stackoverflow.com/q/48501703
score: 0
type: Comment
has text: your title has nothing to do with your problem, also you never specified where you want to call printThis
type: QuestionComment

http://stackoverflow.com/comment/84168696
has text: i don't know how many rows there are that's one thing that makes this so hard to figure out.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48585877

http://stackoverflow.com/comment/84029125
type: AnswerComment
comment on: http://stackoverflow.com/a/48516543
has text: You are saying current time is less that start date? and current time is greater than end date? Are you sure? Invert should help.
type: Comment
score: 0

http://stackoverflow.com/q/48564565
tagged with: list
tagged with: split
has answer: http://stackoverflow.com/a/48564757
has comment: http://stackoverflow.com/comment/84126282
downvote count: 2
has comment: http://stackoverflow.com/comment/84125016
has answer: http://stackoverflow.com/a/48564717
upvote count: 1
has answer: http://stackoverflow.com/a/48564777
accepted answer: http://stackoverflow.com/a/48564777
answer count: 7
has comment: http://stackoverflow.com/comment/84124916
has answer: http://stackoverflow.com/a/48564835
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48565498
has title: Working with list and split method in list in python
has answer: http://stackoverflow.com/a/48564670
has comment: http://stackoverflow.com/comment/84133329
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48564676
possible better answer: http://stackoverflow.com/a/48564676
has comment: http://stackoverflow.com/comment/84126326
has body: I have to open a file read it line by line. For each line, I have to split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already on the list and if not append it to the list. When the program completes, print the resulting words in alphabetical order. fname = input("Enter file name: ") fh = open(fname) lst=list() for line in fh: for each in line: word = line.split() if word not in lst: lst.append(word) print(lst) after this, I am getting 4 different lists but I am required to get a single list and I am not able to get that
has comment: http://stackoverflow.com/comment/84124963
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84125089
has comment: http://stackoverflow.com/comment/84125075

http://stackoverflow.com/comment/84207321
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48605413
score: 0
has text: Again, by best practices you should always use the single quote. That means that, given that "I had this thing" is using unnecessary double quotes , the interpreter will use single quotes, meaning 'I had this thing'. In the third case, you put "But it didn't sing." In this case double quotes are necessary, because you have a single quote in the middle. Usually your always use single quote and when you need something special you use double quotes, and that's what the interpreter is doing

http://stackoverflow.com/comment/84085167
comment on: http://stackoverflow.com/q/48544859
score: 0
type: QuestionComment
has text: can you share a sample code showing the structure
type: Comment

http://stackoverflow.com/comment/84058460
type: QuestionComment
score: 0
type: Comment
has text: At first step how to do this part with subprocess. because with Win 10 a have a problem with this, with linux has not these problems.
comment on: http://stackoverflow.com/q/48529259

http://stackoverflow.com/comment/85979249
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49473464
type: Comment
has text: I am using a virtualenv. I have django 1.10 and celery 4.1 . Should I upgrade django?

http://stackoverflow.com/a/48553786
has comment: http://stackoverflow.com/comment/84104050
has comment: http://stackoverflow.com/comment/84104471
has comment: http://stackoverflow.com/comment/84104513
has body: Isn't it the same as here ? Passing a Pipe/Connection as context arg to multiprocessing Pool.apply_async() I guess you are not getting the error message mentioned there because of Mac OS. The answer in the link says it is a bug of Python 2. I tried your code with Python 3 and it worked.
has comment: http://stackoverflow.com/comment/84104231
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84104473
has comment: http://stackoverflow.com/comment/84104900
answers question: http://stackoverflow.com/q/48553651
type: Answer

http://stackoverflow.com/comment/84235458
comment on: http://stackoverflow.com/q/48617746
score: 0
type: Comment
type: QuestionComment
has text: Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, [describe the problem](https://meta.stackoverflow.com/questions/254393/what-exactly-is-a-recommendation-question) and what has been done so far to solve it.

http://stackoverflow.com/comment/84348592
type: Comment
type: QuestionComment
score: 0
has text: All error, help and usage messages output from parser.parse_args('-x p g -h'.split()) .. Either caused by '-h' or because of parameter/syntax error.
comment on: http://stackoverflow.com/q/48640001

http://stackoverflow.com/comment/84173605
type: AnswerComment
has text: Also, `"numpy"` is a default argument. So you can omit it.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48588111

http://stackoverflow.com/a/48512528
downvote count: 0
type: Answer
has body: np.apply_along_axis doesn't make much sense with a 1d array. In a 2d or higher array, it applies the function to 1d slices from that array. Regarding that function: This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis. This nameerror is produced even before running apply. You didn't define a weekday function: np.apply_along_axis(weekday,0,dat) NameError: name 'weekday' is not defined weekday is a method of a date, not a function in the dt module: np.apply_along_axis(dt.weekday,0,dat) AttributeError: 'module' object has no attribute 'weekday' It's not defined in pandas either: np.apply_along_axis(pd.weekday,1,dat) AttributeError: 'module' object has no attribute 'weekday' This looks better, but apply_along_axis passes an array (1d) to the lambda. weekday isn't an array method. np.apply_along_axis(lambda x: x.weekday(),0,dat) AttributeError: 'numpy.ndarray' object has no attribute 'weekday' And an array doesn't have a dt attribute either. np.apply_along_axis(lambda x: x.dt.weekday,0,dat) AttributeError: 'numpy.ndarray' object has no attribute 'dt' So let's forget about apply_along_axis. Define a sample, first as list, and then as object array: In [231]: alist = [datetime.date(2010, 6, 11), datetime.date(2010, 6, 19), datetime.date(2010, 6, 30)] In [232]: data = np.array(alist) In [233]: data Out[233]: array([datetime.date(2010, 6, 11), datetime.date(2010, 6, 19), datetime.date(2010, 6, 30)], dtype=object) And for convenience a lambda version of weekday: In [234]: L = lambda x: x.weekday() This can be applied iteratively in several ways: In [235]: [L(x) for x in alist] Out[235]: [4, 5, 2] In [236]: [L(x) for x in data] Out[236]: [4, 5, 2] In [237]: np.vectorize(L)(data) Out[237]: array([4, 5, 2]) In [238]: np.frompyfunc(L,1,1)(data) Out[238]: array([4, 5, 2], dtype=object) I just did time tests on a 3000 item list. The list comprehension was fastest (as I expected from past tests), but the time differences were not large. …
upvote count: 2
answers question: http://stackoverflow.com/q/48512090
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48512090
score: 2
has comment: http://stackoverflow.com/comment/109342537

http://stackoverflow.com/a/48529326
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48525768
has body: The term you are looking for is lambda functions. These types of functions are ideal for quick, one-time calculations. The javascript equivalent is the map() function. For your specific case, the syntax would be let arr = some_array.map(x => { return SomeFunc(x); }); For example, the statement let arr = [1, 2, 8].map(num => { return num * 2; }); will assign the list [2, 4, 16] to the variable arr. Hope that helps!

http://stackoverflow.com/a/48530880
has body: With a decent network, you should be able to have at least 10fps in wifi and 25fps in ethernet depending of the resolution. Here are some ideas: If currently both in wifi, put your computer in ethernet Try reducing the size of the image (do you really need color ?) Try reducing the size of the image (do you really need 4VGA or HD ?) Stop some other processing potentially using camera (on board face detection/recognition, image analysis, autonomous life, choregraphe...) Good luck... You can also refer to the documentation from Softbank, which tells you the limitations: See here...
score: 3
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48507240
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48507240

http://stackoverflow.com/comment/84079362
comment on: http://stackoverflow.com/q/48542185
type: QuestionComment
has text: In case it is an object that can be JSON serialized, JSON objects are typically more compact than pickle (but as said before you lose some flexibility).
type: Comment
score: 0

http://stackoverflow.com/a/48499056
has body: I don't think you should return a GoString to C. Since the memory of GoString is managed by the go runtime and will be garbage collected. It's unreliable in C land to use this string. What you should do is return a CString by calling cs := C.CString(s). Memory allocations made by C code are not known to Go's memory manager. So I think its up to you to mange which side to free the CString, here and here.
downvote count: 0
has comment: http://stackoverflow.com/comment/83996608
accepted answer of: http://stackoverflow.com/q/48497879
type: Answer
answers question: http://stackoverflow.com/q/48497879
has comment: http://stackoverflow.com/comment/83999365
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/84047548
has comment: http://stackoverflow.com/comment/84047717
has comment: http://stackoverflow.com/comment/83999537
type: AcceptedAnswer

http://stackoverflow.com/q/48577372
type: UnansweredQuestion
has title: Tensorflow:using pandas_input_fn with TensorForestEstimator
tagged with: python
has body: I am working on a simple Tensorflow programme, and build input pipeline with pandas.My code is below: def train_rf(X,Y): print(X.shape) print(Y.shape) if os.path.isfile(config['rf']['model_dir']): shutil.rmtree(config['rf']['model_dir']) #features is the list of names of features params = tensor_forest.ForestHParams( num_classes=2, num_features=len(features), num_trees=config['rf']['num_trees']) est = random_forest.TensorForestEstimator(params, model_dir=config['rf']['model_dir']) train_input_fn = tf.estimator.inputs.pandas_input_fn( X, y=Y, batch_size=config['rf']['train_batch_size'], num_epochs=1, shuffle=True) est.fit(input_fn=train_input_fn, steps=100) However, when I run this function, I got error like this: Traceback (most recent call last): File "random_forest.py", line 118, in &lt;module&gt; train_rf(train_ohd[features].iloc[X_1],l(y_1),train_ohd[features].iloc[X_2]) File "random_forest.py", line 44, in train_rf est.fit(input_fn=train_input_fn, steps=100) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.py", line 316, in new_func return func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 480, in fit loss = self._train_model(input_fn=input_fn, hooks=hooks) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 986, in _train_model model_fn_ops = self._get_train_ops(features, labels) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1202, in _get_train_ops return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1166, in _call_model_fn model_fn_results = self._model_fn(features, labels, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/tensor_forest/client/random_forest.py",…
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51102288

http://stackoverflow.com/q/48533495
possible better answer: http://stackoverflow.com/a/48533627
favorite count: 0
accepted answer: http://stackoverflow.com/a/48533556
has answer: http://stackoverflow.com/a/48533627
has answer: http://stackoverflow.com/a/48533556
type: Question
answer count: 2
has title: Creating an array with list of strings
tagged with: arrays
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84062750
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84062992
upvote count: 1
score: 1
tagged with: string
has body: I want to create an array 10*10 (basically 100 elements letter on I can reshape it to 10*10) which has to contain random letter from alphabet. For example: array_box = [the first elemet (c), second (e),...100(f)]

http://stackoverflow.com/q/48587335
answer count: 1
favorite count: 0
tagged with: latex
type: Question
tagged with: matplotlib
tagged with: tex
tagged with: python
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/48587535
has title: Add limits to the integration symbol in matplotlib.pyplot.ylabel()
has answer: http://stackoverflow.com/a/48587535
type: AnsweredQuestion
downvote count: 0
has body: I want the ylabel to be of the form in the below figure. I have used the below line to get the integral symbol on the ylabel without the limits. plt.ylabel(r'$\int du/(1+u^{2})$') I need to know how to bring in the limits 0 and x in the integral symbol.
score: 1
upvote count: 1

http://stackoverflow.com/q/48591267
has comment: http://stackoverflow.com/comment/84180146
has comment: http://stackoverflow.com/comment/84187658
has comment: http://stackoverflow.com/comment/84266827
answer count: 0
has comment: http://stackoverflow.com/comment/84261129
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/84197985
tagged with: python
has comment: http://stackoverflow.com/comment/84182108
has body: I've been working on a Django application and have recently run into a few issues pushing updates and migrating DB settings from Local to Heroku. I followed these steps: I added a few columns to my app model. Then ran python manage.py makemigrations then python manage.py migrate. I then committed these updates via github. Then I ran git push heroku master w/ Heroku CLI Then I entered heroku run python manage.py migrate Unfortunately, this did not migrate the appropriate updates I made to the DB settings in my local dev environment. The error message I received is "Column x does not exist in X-app". I ended up reverting back to my previous settings in model.py temporarily, but I would like to eventually add new columns to my database. At this point, I'm trying to assess what the best solution is to the problem. I've reviewed several other Stack Overflow questions, but haven't found one that's worked for me yet. What's odd is that I was able to migrate successfully in previous Heroku deployments. Any tips anyone has would be extremely appreciated. For reference, I'm using Python 3.6.2 and Django 1.11 Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) The above exception (column courts_court.draft does not exist LINE 1: ...urts_court"."address", "courts_court"."location", "courts_co...) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/courts/views.py" in court_list 128. return render(request, "court_list.html", context) File "/app/.heroku/python/lib/python3.6/site-packages/django/shortcuts.py" in render 67. template_name, cont…
has comment: http://stackoverflow.com/comment/84198017
tagged with: git
has comment: http://stackoverflow.com/comment/84180090
has comment: http://stackoverflow.com/comment/84198071
tagged with: heroku
has comment: http://stackoverflow.com/comment/84262205
has comment: http://stackoverflow.com/comment/84180045
score: 0
has comment: http://stackoverflow.com/comment/84261893
has comment: http://stackoverflow.com/comment/84180305
has comment: http://stackoverflow.com/comment/84197514
has title: Issue migrating DB from Local to Heroku Django
type: Question
has comment: http://stackoverflow.com/comment/84180074

http://stackoverflow.com/comment/84202608
type: Comment
comment on: http://stackoverflow.com/a/48602601
type: AnswerComment
score: 0
has text: @MTG: are you sure that the operator you introduced is associative, commutative, etc. (like usually a numerical multiplication is)? In case it is not, the linear variant should still work.

http://stackoverflow.com/q/48513943
has answer: http://stackoverflow.com/a/48514376
accepted answer: http://stackoverflow.com/a/48514376
tagged with: python
has body: I have a bit of an optimization problem (I am sort of new to python and Stackoverflow). I am building a word collocation network for a research project. The code I wrote takes a stemmed text without stop words (text_c) and splits it into sentences. For each sentence, it the iterates over the terms in order to build a weighed semantic network that I will then process with NetworkX. This is partly based on a dictionary of the form {'word': digit} (the dic below). The code iterates over the list of existing edges in the network (represented as lists of 3 items). The problem might be how the loop over the network is growing exponentially (each time a new edge/list is added, the loop increases in size). There are about 110K sentences in the text, so this is taking way too much time (it last took 4 hours to run and didn't finish). There must be a better way of doing this. Would a 'for' statement be more efficient than the look? How would this work? Thanks! #determine semantic networks outfile = open("00_network_"+str(c)+".csv","a") network = [] er=0 data = text_c.split(".") for lines in data: linew = lines.split() ran = len(linew) if ran&gt;3: #sentences of more than three words i=0 while i &lt; ran: j = i+1 while j &lt; ran: try: previous_edge = [] for n in network: if n[0] == dic[linew[i]] and n[1] == dic[linew[j]]: previous_edge = [n[0],n[1],n[2]] if previous_edge == []: new_edge = [dic[linew[i]],dic[linew[j]],1/((j-i))] network.append(new_edge) else: new_edge = [dic[linew[i]],dic[linew[j]],previous_edge[2]+1/((j-i))] network.remove([previous_edge[0],previous_edge[1],previous_edge[2]]) network.append(new_edge) except KeyError: er=er+1 j=j+1 i=i+1
tagged with: optimization
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has title: Optimizing iteration of list in list on python
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/84455988
comment on: http://stackoverflow.com/a/48635553
score: 0
type: Comment
type: AnswerComment
has text: @Anaksunaman, you are exactly correct. It took me a while to figure it out. And I'm not sure what to do to fix it. I decided to clarify my question [here](https://stackoverflow.com/questions/48673359/how-to-properly-return-http-response-from-python-requests-library-want-a-python), but got no responses. In any case, you are completely correct, and I'm not sure how to solve it. Strange these comments did not show up in my notification.

http://stackoverflow.com/comment/84003432
type: QuestionComment
has text: Yes, I have installed pywin32. What do you mean by restarting the virtualEnv?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48491168

http://stackoverflow.com/comment/84087498
type: AnswerComment
has text: It works. Just change 'users.txt' to 'projections.txt'. I edited it to.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48545707

http://stackoverflow.com/q/48593671
answer count: 0
upvote count: 2
has body: I can't seem to install any packages with the conda package manager on Fedora 27, specifically, I'm trying to install pytorch. I've tried installing it using conda install pytorch torchvision -c pytorch but it says I don't have permission, and when I try source activate my_root like EVERY INTERNET SOURCE tells me to do, it just errors because source doesn't even do the right thing. I also tried building it from source but it gives the error that yaml is not installed, and I can't install it with conda for the same reason: source activate my_root is a total scam. I can't find anything else that is remotely close to functional. How do I perform the basic task of installing a package from the internet?
downvote count: 0
tagged with: fedora
has comment: http://stackoverflow.com/comment/86019170
favorite count: 0
type: Question
has title: Installing packages with Anaconda on Fedora 27
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84215490
tagged with: conda
score: 2

http://stackoverflow.com/comment/84278500
has text: @SeungYeupLEE If the answer worked for you, please accept it.
score: 0
comment on: http://stackoverflow.com/q/48607116
type: QuestionComment
type: Comment

negative-number
type: Tag
tags question: http://stackoverflow.com/q/48521384
tag name: negative-number

http://stackoverflow.com/a/48579338
score: 0
answers question: http://stackoverflow.com/q/48579152
has body: If you want to use ArgumentParser you need to change your code to: parser= argparse.ArgumentParser() parser.add_argument("-platform") args = parser.parse_args() if args.platform == 'iphone' ##do something with that information useage: python somefile.py -platform iphone read more about argParser here otherwise you could simply use sys.argv[1] : import sys if sys.argv[1] == 'iphone': # iphone useage for sys.argv: python somefile.py iphone
type: Answer

http://stackoverflow.com/comment/84025610
type: AnswerComment
comment on: http://stackoverflow.com/a/48512517
score: 0
type: Comment
has text: @ToddP I think the default focus policy for combo boxes is `Qt.NoFocus`, so focus returns to the line edit. You may want to investigate a slightly more complex example where you have a combo box and two line edits to see which one emits the `editingFinished` signal at which time, and how focus returns depending on the focus policy (which you can change) of each widget.

http://stackoverflow.com/q/48515479
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84025215
has body: I'am new in Python. Is there a way to search a list of values (words and fraises) in another list (csv table), and get only the matched rows? Example: LiastOfValues=['smoking','hard smoker','alcoholic'] ListfromCSV = ID,TYPE,STRING1,NUMBER 1, a,'this is hard smoker man',4 2, b,'this one likes to drink',5 3, c,'dont like sigarets',6 4, e,'this one is smoking',7 To search LiastOfValues in each row and reply only the matched rows. The Output: Output= ID,TYPE,STRING1,NUMBER 1, a,'this is hard smoker man',4 4, e,'this one is smoking',7 I have tryed this: import csv ListfromCSV ="ListfromCSV.txt" LiastOfValues=['smoking','hard smoker','alcoholic','smoker'] with open(ListfromCSV ,'r') as f: LineReader=csv.reader(f,delimiter=',') for i in LineReader: if value in (i[2])) : print (i)
has comment: http://stackoverflow.com/comment/84025216
answer count: 1
has comment: http://stackoverflow.com/comment/84025268
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48515557
downvote count: 4
type: UnansweredQuestion
has title: how to search a list of values in another list
score: -3

http://stackoverflow.com/comment/84224303
comment on: http://stackoverflow.com/q/48613702
has text: looks like you don't need `enumerate`. Remove your inner `for` loop and just do `print(z)`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48629513
has comment: http://stackoverflow.com/comment/84292650
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84259403
has body: Brand new to python. I've searched for this problem but the material out there is way far-ranging and over my head. I'm hoping I have a more specific issue with this 'traceback'? (traceback is the error code?). Having the following issue when I attempt "import matplotlib as plt". From the study on the matter it could be a font with e' or o: or something of that nature? Is there a file I have to delete within the folder structure? I'm set up Jupyter with Anaconda2. And as far as I can tell it's using python 3.5. Operating system is windows 7. UnicodeDecodeError Traceback (most recent call last) &lt;ipython-input-9-eff513f636fd&gt; in &lt;module&gt;() ----&gt; 1 import matplotlib.pyplot as plt C:\Users\Owner\Anaconda2\envs\gl-env\lib\site-packages\matplotlib\pyplot.py in &lt;module&gt;() 27 from cycler import cycler 28 import matplotlib ---&gt; 29 import matplotlib.colorbar 30 from matplotlib import style 31 from matplotlib import _pylab_helpers, interactive C:\Users\Owner\Anaconda2\envs\gl-env\lib\site-packages\matplotlib\colorbar.py in &lt;module&gt;() 32 import matplotlib.artist as martist 33 import matplotlib.cbook as cbook ---&gt; 34 import matplotlib.collections as collections 35 import matplotlib.colors as colors 36 import matplotlib.contour as contour C:\Users\Owner\Anaconda2\envs\gl-env\lib\site-packages\matplotlib\collections.py in &lt;module&gt;() 25 import matplotlib.artist as artist 26 from matplotlib.artist import allow_rasterization ---&gt; 27 import matplotlib.backend_bases as backend_bases 28 import matplotlib.path as mpath 29 from matplotlib import _path C:\Users\Owner\Anaconda2\envs\gl-env\lib\site-packages\matplotlib\backend_bases.py in &lt;module&gt;() 60 61 import matplotlib.tight_bbox as tight_bbox ---&gt; 62 import matplotlib.textpath as textpath 63 from matplotlib.path import Path 64 from matplotlib.cbook import mplDeprecation, warn_deprecated C:\Users\Owner\Anaconda2\envs\gl-env\lib\site-packages\matplotlib\textpath.py in &lt;module&gt;() 13 …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84387338
tagged with: matplotlib
answer count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84305789
has title: Import matplotlib as plt (UnicodeDecode Error)
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84284627

http://stackoverflow.com/q/48606909
has title: convert numbers in string to array in python
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: arrays
tagged with: python
score: 4
downvote count: 1
has body: I have a .csv file and it looks like 1, 1 2 3 4 5 3, 2 3 4 5 6 2, 5 6 5 4 8 5, 5 4 8 6 2 ... how can I do to get the first column a = [1 3 2 5 ...] and the matrix b = [ 1 2 3 4 5 2 3 4 5 6 5 6 5 4 8 5 4 8 6 2 ] with type integer numpy array and I have tried data = np.asarray(pd.read_csv('Data.csv')) but it make the thing worse...
has answer: http://stackoverflow.com/a/48607255
answer count: 3
has answer: http://stackoverflow.com/a/48607018
upvote count: 5
has answer: http://stackoverflow.com/a/48606964

http://stackoverflow.com/comment/95724946
has text: This error occurs also when your disk space is low.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48641884
type: Comment

http://stackoverflow.com/q/48613515
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: dictionary
has title: How to access elements in a dictionary in python with for loop?
has comment: http://stackoverflow.com/comment/84224039
has body: I need to extract information from a dictionary, but can't figure how to access data. I have: from datetime import timedelta, date from dateutil.relativedelta import relativedelta import numpy as np start_date = date(2017,1,1); final_date = date.today() + relativedelta(months=2); def datarange(start_date, final_date): for n in range((final_date-start_date).days+1): yield start_date + timedelta(n) PayDayTable = {i:np.zeros(5) for i in datarange(start_date, final_date)} and I can do: print(PayDayTable) print(PayDayTable[date.today()]) print(PayDayTable[date.today()][0]) print(PayDayTable[date.today()][1:3]) but when I do: for item in PayDayTable: print(item) How can I access the values of the PayDayTable dictionary by iterating over the items with for loop? Edit: I was looking for Python 2 documentation while I was using Python 3.6. So instead of doing something like: for item in PayDayTable.iteritems(): pass I've learned that I should do: for item in PayDayTable.items(): print(item[1][0])
has answer: http://stackoverflow.com/a/48613571
answer count: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84223861
score: -1
type: Question

http://stackoverflow.com/comment/84050195
comment on: http://stackoverflow.com/q/48527420
score: 0
type: Comment
has text: @Nico Albera - ValueError: too many values to unpack
type: QuestionComment

http://stackoverflow.com/q/48533002
has comment: http://stackoverflow.com/comment/84063093
linked to: http://stackoverflow.com/q/48487278
tagged with: numpy
type: AnsweredQuestion
has title: quaternion generation with non minimal rotation arc
score: 0
tagged with: rotation
has body: The quaternion module of numpy can generate quaternion from sperical coordinates. Example: theta = np.pi / 3.0 phi = np.pi / 3.0 qRot = q.from_spherical_coords(theta,phi) qRot quaternion(0.75, -0.25, 0.433012701892219, 0.433012701892219) This quaternion rotates Z axis to a unit vector V pointing to theta,phi coords. This quaternion does not produces a minimal rotation arc. The minimal rotation arc axis lies in the xy plane. Since the non minimal rotations moving Z to V are infinite, what is the underlying criteria that produces the quaternion qRot? Thanks for any reply.
answer count: 1
type: Question
tagged with: quaternions
has answer: http://stackoverflow.com/a/48536253
accepted answer: http://stackoverflow.com/a/48536253
tagged with: python

http://stackoverflow.com/comment/84197588
has text: This is probably better suited for stackoverflow (and there are already votes to migrate) but I think you should post your models file generated by the the inspectdb
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48600473

http://stackoverflow.com/comment/84288199
score: 0
type: AnswerComment
has text: I guess I need to learn bash. I've misunderstood the requirements of my task.It was supposed to work with "foo > bar " command and I've thought I need to write the data to the second file directly in my app. Now I just print it instead of writing to a file so it works nicely with this ">" shell command.Thanks for the clarification:) This "duplication" made me to think about that.
comment on: http://stackoverflow.com/a/48620563
type: Comment

http://stackoverflow.com/a/48511353
type: Answer
has comment: http://stackoverflow.com/comment/84017929
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84017861
answers question: http://stackoverflow.com/q/48511250
has body: When you do `words = line.split()` you're assigning to the variable words a list of strings - the non-whitespace strings in the line. But you're not doing anything with words after that. Instead, you do: if line[1:] == 'the raven': which checks if the whole line, minus its first character, is exactly 'the raven'. (Edited for handing unicode/bytes): If you want to add up the total number of times 'the raven' appears in your whole file, you can skip the split and the if and get the count of occurrences directly from each line. Because requests gives you bytes objects (in python 3) or unicode objects (in python 2) you'll need to decode the lines with the appropriate encoding first: for line in r.iter_lines(): count += line.decode('utf-8').count('the raven') If instead you want to return the total number of lines in which 'the raven' appears at all, you can do: for line in r.iter_lines(): if 'the raven' in line.decode('utf-8'): count += 1 You may need to choose a different encoding, depending on your data source.

http://stackoverflow.com/a/48645836
answers question: http://stackoverflow.com/q/48645531
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/84289029
has comment: http://stackoverflow.com/comment/84293694
has body: You can use Selenium Web Driver. Learning about it you can do what you need with a code similar to this: username = selenium.find_element_by_id("username") password = selenium.find_element_by_id("password") username.send_keys("YourUsername") password.send_keys("yourPa55worD") selenium.find_element_by_name("submit").click() Since it seems you want to use another OS user, I suggest you use Sikuli: Sikuli automates anything you see on the screen. It uses image recognition to identify and control GUI components. It is useful when there is no easy access to a GUI's internal or source code. I think there is no way to do what you are wanting with just Selenium. If you need to integrate Selenium and Sikuli, you can see this post on SOF: Calling to a Sikuli script from Python (Selenium) . It can give some ideas for you. I hope it helps.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48575854
has comment: http://stackoverflow.com/comment/84151292
tagged with: gis
has title: A smooth contour plot covering and masked by shapefile in Basemap
linked to: http://stackoverflow.com/q/42426095
has comment: http://stackoverflow.com/comment/84154340
has comment: http://stackoverflow.com/comment/84173991
has comment: http://stackoverflow.com/comment/84174440
score: 2
has comment: http://stackoverflow.com/comment/84174595
downvote count: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84173585
has comment: http://stackoverflow.com/comment/84173441
tagged with: python
linked to: http://stackoverflow.com/q/48015378
has comment: http://stackoverflow.com/comment/84174196
tagged with: matplotlib-basemap
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84174741
answer count: 0
has comment: http://stackoverflow.com/comment/95941875
tagged with: contour
has body: I have a polygon shapefile (the state of Illinois) and a CSV file with (lat, lon, zvalue). I want to plot a smooth contour plot representing those zvalues. Following is my code: import glob import fiona import numpy as np import pandas as pd from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib.mlab import griddata # Read in the tabulated data tabfname = glob.glob("Outputs\\*.csv")[0] df = pd.read_table(tabfname, sep=",") print(df.head()) lat, lon, z = list(df.y), list(df.x), list(df["Theil Sen Slope"]) z0, z1, z2 = np.min(z)+0.03, np.mean(z), np.max(z)-0.01 # Read some metadata of the shapefile shp = glob.glob("GIS\\*.shp")[0] with fiona.drivers(): with fiona.open(shp) as src: bnds = src.bounds extent = [values for values in bnds] lono = np.mean([extent[0], extent[2]]) lato = np.mean([extent[1], extent[3]]) llcrnrlon = extent[0]-0.5 llcrnrlat = extent[1]-0.5 urcrnrlon = extent[2]+0.5 urcrnrlat = extent[3]+0.5 # Create a Basemap fig = plt.figure() ax = fig.add_subplot(111) m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, resolution='i', projection='tmerc' , lat_0 = lato, lon_0 = lono) # Read in and display the shapefile m.readshapefile(shp.split(".")[0], 'shf', zorder=2, drawbounds=True) # Compute the number of bins to aggregate data nx = 100 ny = 100 # Create a mesh and interpolate data xi = np.linspace(llcrnrlon, urcrnrlon, nx) yi = np.linspace(llcrnrlat, urcrnrlat, ny) xgrid, ygrid = np.meshgrid(xi, yi) xs, ys = m(xgrid, ygrid) zs = griddata(lon, lat, z, xgrid, ygrid, interp='nn') # Plot the contour map conf = m.contourf(xs, ys, zs, 30, zorder=1, cmap='jet') cbar = m.colorbar(conf, location='bottom', pad="5%", ticks=(z0, z1, z2)) # Scatter plot of the points that make up the contour for x, y in zip(lon, lat): X, Y = m(x,y) m.scatter(X, Y, zorder=4, color='black', s=1) plt.show() fig.savefig("Myplot.png", format="png") And this is the output I got(The scattered black dots are th…
type: UnansweredQuestion

http://stackoverflow.com/a/48617079
answers question: http://stackoverflow.com/q/48588778
has body: I think this is a great question. Many people and companies don't bother managing their existing tests properly which leads to redundant and repeated code without having a clear idea what is covered by automated tests. There is no single answer to this question but in general you can consider the following options: Testing framework built in reporting. In Java, for example, you have the unit testing libraries like jUnit and TestNG. When they run, they generate certain output that can later be formatted and reviewed as the need arises. I am sure there an implementation of unit testing framework like this in Python too. You can also consider using a BDD tool like Cucumber. This is a bit different and might not be suitable in certain cases when the tests are low level system checks. It can however help you organize your test scenarios and keep them an a readable form. It is also very good for reporting to a non-technical person.
type: Answer
score: 0

http://stackoverflow.com/comment/84057307
type: Comment
has text: @CristiFati What does that even mean??
score: 0
comment on: http://stackoverflow.com/q/48530848
type: QuestionComment

http://stackoverflow.com/comment/84144552
type: Comment
type: QuestionComment
score: 0
has text: Why do you want to use a button?
comment on: http://stackoverflow.com/q/48573717

http://stackoverflow.com/q/48511467
answer count: 1
has title: Formula translation for Mars perturbers in Python
type: Question
has body: In the process to calculate Mars hours I need to translate certain formula to obtain the Mars perturbers (PBS). That formula is: PBS = Σ(i=1,7) Ai cos [ (0.985626° ΔtJ2000 / τi) + φi] where A is the amplitud, τ the period and φ the phase according to the value of i, in this table (7 values for each parameter): Table with values ΔtJ2000 is the offset from J2000 epoch, and I´m pretty sure I already have the right value, which is 6603.452757146675 when that formula needs to be calculated. So, this is the piece of code I´m using: A = [0.0071, 0.0057, 0.0039, 0.0037, 0.0021, 0.0020, 0.0018] tau = [2.2353, 2.7543, 1.1177, 15.7866, 2.1354, 2.4694, 32.8493] phi = [49.409, 168.173, 191.837, 21.736, 15.704, 95.528, 49.095] OffsettJ2000 = 6603.452757146675 PBS = 0 for i in range(0, len(A)): PBS += A[i] * math.cos(0.985626 * OffsettJ2000 / tau[i] + phi[i]) The result for PBS should be around 0,00219º (taken for MarsTime 1.2 app), but I´m getting 0.00048º What´s my mistake? Thanks from a martian! Editing to add a useful link with all the processes and formulas from NASA (mine is B-3): https://www.giss.nasa.gov/tools/mars24/help/algorithm.html digitalmeteo
accepted answer: http://stackoverflow.com/a/48511526
tagged with: python
has answer: http://stackoverflow.com/a/48511526
tagged with: formula
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/84078736
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48541552
score: 3
has text: Also, don't name your variable `dict`, since you're shadowing a builtin name.

http://stackoverflow.com/comment/84193492
comment on: http://stackoverflow.com/a/48598297
type: Comment
has text: @Kasramvd I'm using CPython 3.6.4
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84253324
type: Comment
score: 0
type: AnswerComment
has text: It does replace most of it but there are still rows with "SOME_NAME" value
comment on: http://stackoverflow.com/a/48628097

http://stackoverflow.com/comment/84246601
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48624874
has text: [HTML](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454).
score: 1

http://stackoverflow.com/comment/83990146
score: 1
comment on: http://stackoverflow.com/q/48497566
type: QuestionComment
has text: It means you are sending wrong credentials please verify your credentials.
type: Comment

http://stackoverflow.com/a/48527019
score: 0
has body: When creating a new GoodsCategory you need to explicitly set a category_type, set a default value or set the field as nullable (null=True) in the model. Model field reference #default
answers question: http://stackoverflow.com/q/48526914
type: Answer

http://stackoverflow.com/q/48629461
has comment: http://stackoverflow.com/comment/84260046
has comment: http://stackoverflow.com/comment/84260074
accepted answer: http://stackoverflow.com/a/48631541
has comment: http://stackoverflow.com/comment/84259987
type: Question
has answer: http://stackoverflow.com/a/48631541
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/52049918
tagged with: jsonpath
tagged with: python
has comment: http://stackoverflow.com/comment/84257317
has comment: http://stackoverflow.com/comment/84258833
linked to: http://stackoverflow.com/q/48602313
has comment: http://stackoverflow.com/comment/84259528
has body: I have an implementation question... #!/usr/bin/python #This is the API for BTC price request. # Average all the amounts, and push that to the program import json import urllib.request from jsonpath_rw import parse as parse_jsonpath class BtcAPI: def __init__(self, url, api_id, json_key): self.url = url self.api_id = api_id self.json_key = json_key def btc_api_call(self): hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' } req = urllib.request.Request(self.url, headers=hdr) readdata = urllib.request.urlopen(req) json_data = readdata.read() json_dict = json.loads(json_data) results = parse_jsonpath(self.json_key).find(json_dict) print(results) class Price: def __init__(self, api_id, url, json_key): self.api_id = api_id self.url = url self.json_key = json_key def pass_for_request(self): get_price = BtcAPI(self.url, self.api_id, self.json_key) get_price.btc_api_call() def Coindesk(): coindesk = Price("coindesk","https://api.coindesk.com/v1/bpi/currentprice.json","time.updated") coindesk.pass_for_request() The value that gets passed for the "json_key" is "bpi.USD.rate_float"... inside this url. It gets passed to a class called "Price", which creates variables that pass to the class that the code above is contained in. coindesk = Price("coindesk","api.coindesk.com/v1/bpi/currentprice.json", "bpi.USD.rate_float") And here is the json I am targeting... trying to get to the rate_float key: { "time": { "updated": "Feb 5, 2018 18:34:00 UTC", "updatedISO": "2018-02-05T18:34:00+00:00", "updateduk": "Feb 5, 2018 at 18:34 GMT" }, "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org", "chartName": "Bitcoin", "bpi": { "USD": { "code": "USD", "symbol": "&amp;#36;", "rate": "7,004.9588", "description": "United States Dollar", "rate_float": 7004.9588 } } When I run the program, it sends me the output of the entire json file, rather than the specific key…
has comment: http://stackoverflow.com/comment/84258907
has title: Python, jsonpath: How do I parse with jsonpath correctly?
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84259442
has comment: http://stackoverflow.com/comment/84259176
has answer: http://stackoverflow.com/a/52049918
favorite count: 0

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

http://stackoverflow.com/a/48641391
score: 2
has comment: http://stackoverflow.com/comment/84286419
type: Answer
accepted answer of: http://stackoverflow.com/q/48640650
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48640650
has body: When using the decimal module, you need to initialize with strings; initializing with floats will preserve in high resolution the imprecision of the underlying float type. For example, using Decimal(0.1) actually produces a value: Decimal('0.1000000000000000055511151231257827021181583404541015625') because that's the 30 digit extrapolation of the value represented by the float 0.1. So instead of testing Decimal(0.1) + Decimal(0.1) + Decimal(0.1) == Decimal(0.3) (where you compute in fixed decimal precision, but initialize with non-decimal values), use Decimal("0.1") + Decimal("0.1") + Decimal("0.1") == Decimal("0.3") and you'll get the expected results. Aside from that, you'll want to adjust the decimal context's .prec attribute to ensure you're preserving the intended amount of precision, but usually it's okay to preserve the full precision and just round to the correct precision later with the quantize method.
has comment: http://stackoverflow.com/comment/84305980

http://stackoverflow.com/a/48530924
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48530710
type: Answer
answers question: http://stackoverflow.com/q/48530710
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84057868
has body: : is same as slice(None, None, None) A[0, -1, :] is same as obj = (0, -1, slice(None, None, None)) A[obj]

http://stackoverflow.com/comment/84097270
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48550643
has text: `import matplotlib.pyplot as plt`

http://stackoverflow.com/q/48524798
answer count: 2
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84045569
has answer: http://stackoverflow.com/a/48525344
has title: Order of a list resulting from a group by of pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/84097848
type: Question
has comment: http://stackoverflow.com/comment/84045115
has body: I have a question regarding pandas.core.groupby.GroupBy.apply Consider df.groupby('col1')['col2'].apply(list) Is there some guarantee on the order? For example the following suggests it does: In [1]: import pandas as pd In [2]: df = pd.DataFrame({"col1": ['a', 'a', 'b', 'b', 'b'], "col2": [1,2,3,4,5]}) In [3]: df.groupby('col1')['col2'].apply(list) Out[3]: col1 a [1, 2] b [3, 4, 5] Name: col2, dtype: object In [4]: df = pd.DataFrame({"col1": ['a', 'a', 'b', 'b', 'b'], "col2": [2,1,3,4,5]}) In [5]: df.groupby('col1')['col2'].apply(list) Out[5]: col1 a [2, 1] b [3, 4, 5] Name: col2, dtype: object But is it always the case? Edit In both pandas.DataFrame.groupby and pandas.Series.groupby it is mentioned that the order inside each group is preserved. However, in the example above the type of df.groupby('col1')['col2'] is pandas.core.groupby.SeriesGroupBy and I am not sure anymoe that the same applies also in this case. I need to know (i.e. reference to code/documentation) that the order inside each group is preserved when applying list.
score: 3
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48525515
upvote count: 3

http://stackoverflow.com/q/48558677
score: 1
tagged with: spyder
has comment: http://stackoverflow.com/comment/84123372
tagged with: python
has body: I'm building a CNN using Python I have a folder of pictures for classification stored in D//Files directory however an exception keeps poping code: from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.preprocessing.image import img_to_array import numpy as np # Image manipulations and arranging data import os from PIL import Image import theano theano.config.optimizer="None" from sklearn.cross_validation import train_test_split os.chdir("D:/File"); # input image dimensions m,n = 50,50 path1="input"; path2="data"; classes=os.listdir(path2) x=[] y=[] for fol in classes: print (fol) imgfiles=os.listdir(path2+'\\'+fol); for img in imgfiles: im=Image.open(path2+'\\'+fol+'\\'+img); im=im.convert(mode='RGB') imrs=im.resize((m,n)) imrs=img_to_array(imrs)/255; imrs=imrs.transpose(2,0,1); imrs=imrs.reshape(3,m,n); x.append(imrs) y.append(fol) x=np.array(x); y=np.array(y); batch_size=32 nb_classes=len(classes) nb_epoch=20 nb_filters=32 nb_pool=2 nb_conv=3 x_train, x_test, y_train, y_test= train_test_split(x,y,test_size=0.2,random_state=4) uniques, id_train=np.unique(y_train,return_inverse=True) Y_train=np_utils.to_categorical(id_train,nb_classes) uniques, id_test=np.unique(y_test,return_inverse=True) Y_test=np_utils.to_categorical(id_test,nb_classes) model= Sequential() model.add(Convolution2D(nb_filters,nb_conv,nb_conv,border_mode='same',input_shape=x_train.shape[1:])) model.add(Activation('relu')); model.add(Convolution2D(nb_filters,nb_conv,nb_conv)); model.add(Activation('relu')); model.add(MaxPooling2D(pool_size=(nb_pool,nb_pool))); model.add(Dropout(0.5)); model.add(Flatten()); model.add(Dense(128)); model.add(Dropout(0.5)); model.add(Dense(nb_classes)); model.add(Activation('softmax')); model.compile(loss='categorical_crossentropy',optimizer='adadelta',metrics=['accuracy']) nb_epoch=5; batch_size=5; model.fit(x_train,Y_train,batch_size=batch_size,nb…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48559145
answer count: 2
tagged with: deep-learning
possible better answer: http://stackoverflow.com/a/48574760
has comment: http://stackoverflow.com/comment/84113097
downvote count: 0
has answer: http://stackoverflow.com/a/48574760
upvote count: 1
accepted answer: http://stackoverflow.com/a/48559145
favorite count: 0
has comment: http://stackoverflow.com/comment/84113481
type: Question
has comment: http://stackoverflow.com/comment/84114142
has title: Python: The system cannot find the path specified: 'data'
tagged with: operating-system

http://stackoverflow.com/comment/83977094
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48491915
has text: That's exactly what I wanted! Thanks
type: AnswerComment

http://stackoverflow.com/comment/84018593
has text: Nonlinear least squares, nls, refers to `nonlinear in parameters` which is not supported by OLS or WLS, Also, scipy has curve_fit for simple usecases.
comment on: http://stackoverflow.com/q/48505727
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84131837
comment on: http://stackoverflow.com/q/48567676
type: Comment
type: QuestionComment
has text: can't you pass the script in gnuplot command line instead?
score: 0

http://stackoverflow.com/comment/84140706
has text: What are the types of `price`, `ordersize` columns? They are `str` and `float`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48571918

http://stackoverflow.com/comment/84174595
score: 0
comment on: http://stackoverflow.com/q/48575854
has text: The paper tells you that they used ESRI ARCGIS for visualization of the previously smoothened data via a head-banging algorithm.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48596114
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/84198792
favorite count: 0
upvote count: 4
score: 4
type: Question
has title: PyQt5 GUI - exe made with PyInstaller doesn't open
has comment: http://stackoverflow.com/comment/84211237
tagged with: pyqt
tagged with: user-interface
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48627944
has body: I've got a GUI which runs perfectly fine when I execute it from the Anaconda Prompt. I get the following window as output: I have installed pyinstaller using pip, and have then run the line pyinstaller.exe --onefile [my file path]\mytest.py with my actual file path instead of [my file path]. This creates a file called 'mytest.exe'. However, when I double-click on it, all that happens is that a black window is shown for about 5 seconds, then I get this message for a split second: The window that the Python script makes is never shown (unlike when I directly execute the Python script). Here's the code: from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import sys from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure import matplotlib.pyplot as plt import numpy as np class LineBuilder: def __init__(self, ax): self.ax = ax self.on = 1 self.lastline, = self.ax.plot([0],[0]) self.cid = ax.figure.canvas.mpl_connect('pick_event', self) def __call__(self, event): self.on *=-1 thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind print(xdata[ind]) print('modified',xdata[ind][0]) self.lastline.remove() self.lastline=self.ax.axvline(x=xdata[ind][0]) self.ax.figure.canvas.draw() class View(QGraphicsView): def __init__(self): super(View, self).__init__() self.initScene(5) def initScene(self,h): self.scene = QGraphicsScene() self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.figure.subplots_adjust(left=0.03,right=1,bottom=.1,top=1,wspace=0, hspace=0) ax = self.figure.add_subplot(111) ax.set_xlim([0,1000]) data = np.random.rand(1000) ax.plot(data, '-') self.canvas.draw() self.setScene(self.scene) self.scene.addWidget(self.canvas) class MainWindow(QMainWindow): def __init__(self): super(MainWindow,self).__init__() self.setGeometry(150, 1…
has answer: http://stackoverflow.com/a/48627944
tagged with: pyinstaller
type: AnsweredQuestion

http://stackoverflow.com/a/48631980
type: AcceptedAnswer
has body: I managed to fix the problem by changing the DATABASE_URL in the .env file from DATABASE_URL=postgres://my_app:my_password@localhost/my_database to DATABASE_URL=postgres://my_app:my_password@docker.for.mac.host.internal/my_database and running the container, which I tagged lucy_web, like so: docker run -p 8000:8000 --env-file .env lucy_web It was not necessary to change listen_addresses to '*' in my postgresql.conf; this was still at its default, localhost. (I believe this is because the -p 8000:8000 argument maps port 8000 on localhost to the container).
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/48630545
accepted answer of: http://stackoverflow.com/q/48630545
upvote count: 4

http://stackoverflow.com/q/48626785
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
score: 0
has body: for some reason I get an error at the line containing this piece of code: t1 = threading.Thread(target=socket) this is the error: Traceback (most recent call last): File "D:/04 - Media/Python Projects/4 - Networking/Send_Variable_Test/Server.py", line 33, in &lt;module&gt; t1 = threading.Thread(target=socket) AttributeError: 'module' object has no attribute 'Thread' Exception AttributeError: "'module' object has no attribute '_shutdown'" in &lt;module 'threading' from 'D:\04 - Media\Python Projects\4 - Networking\Send_Variable_Test\threading.pyc'&gt; ignored its obvious from this error that apparently there is no "Thread" module in the threading library, why is this? is the fact that I'm using python 2 the reason?
has title: No "Thread" Module ( python 2.7 )
tagged with: multithreading
has answer: http://stackoverflow.com/a/48626834

http://stackoverflow.com/comment/84126412
comment on: http://stackoverflow.com/q/48563848
type: QuestionComment
type: Comment
score: 0
has text: Thank you for helping, I can't print anything until the page is running and a file is uploaded. If I remove `filename1=filename1` in the return it prints out exactly what the filename of the upload is, otherwise the error returns if I don't remove `filename1=filename1` .

http://stackoverflow.com/q/48532454
has answer: http://stackoverflow.com/a/48543151
accepted answer: http://stackoverflow.com/a/48543151
tagged with: unit-testing
linked to: http://stackoverflow.com/q/419163
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84061403
downvote count: 0
linked to: http://stackoverflow.com/q/4083796
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87723307
score: 2
type: AnsweredQuestion
has body: I have a very basic python application that I wanted to use for upskilling in unit testing. The problem is when I run my test file, it starts the application. I need to shut down the application in order for the test to run and get results. I think this is something to do with the mainloop() used in the application code. How can I just run the tests without the application starting? Application code: class User: def __init__(self, un, pw, ut, upc): self.username = un self.password = pw self.userT = ut self.userPreferredCar = upc self.userInfo = "" def get_un(self): return self.username def get_ut(self): return self.userT def get_pw(self): return self.password def get_userPreferredCar(self): return self.userPreferredCar def set_userInfo(self): self.userInfo = str("Hello " + self.username + ", you picked: " + self.userPreferredCar) return self.userInfo def Login(): #Create login window login_screen = Tk() #Create window title login_screen.title('Login') #Set the window size login_screen.geometry('250x150') #tkinter form code login_screen.mainloop() def signup_function(): #Get the current user curr_user = User(username_signupE.get(), password_signupE.get(), userT.get(), carT.get()) #If the inputs are empty then throw error screen if curr_user.get_un() == "" or curr_user.get_pw() == "" or curr_user.get_ut() == "" or curr_user.get_userPreferredCar() == "": accCreateErr = Tk() accCreateErr.title('Error') accCreateErr.geometry('150x50') errL = Label(accCreateErr, text='\nPlease fill out all details!') errL.grid() accCreateErr.mainloop() else: # Write the new user details to the user file with open(user_file, 'w') as f: f.write(curr_user.get_un()) f.write('\n') f.write(curr_user.get_pw()) f.write('\n') f.write(curr_user.get_ut()) f.write('\n') f.write(curr_user.get_userPreferredCar()) f.close() #Destory the signup window signup_screen.destroy() #Run the Login function Login() Test code: import unittest from main import User from main import Car class TestUser(unittest.TestC…
has title: Python - How to run unittest without starting the application?

http://stackoverflow.com/q/48490770
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83974780
has answer: http://stackoverflow.com/a/48491011
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83974703
has answer: http://stackoverflow.com/a/58353603
downvote count: 5
has body: So if I wanted to get a user input number to print out Color 1 Color 2 etc depending on what number the input is; how would I do that?? I have this so far but it just prints out the word color however many times x is. user = input("How many colors?:") x=int(user) for i in range(x): print("Color" * x)
score: -3
possible better answer: http://stackoverflow.com/a/48491011
has title: asking user input with for loop
tagged with: python
has comment: http://stackoverflow.com/comment/83974669
has answer: http://stackoverflow.com/a/48490830
accepted answer: http://stackoverflow.com/a/48490830
answer count: 4
has answer: http://stackoverflow.com/a/48490856

http://stackoverflow.com/q/48567901
has body: Based on this template I want to create my own CLI Interface to manage our services. Basically this CLI skeleton uses inspection to match CLI arguments/commands to a member class in the module 'commands' and instanciate it via .run() method One of my commands should be 'fetch' which basically downloads some data from an FTP server. so I have an fetch.py class in my commands module. When I do from ftplib import FTP now in this dynamically instanciated module member, it fails immediately with an weird TypeError in socket.py in ftplib So it seems, that ftplib has issues with being imported this way (other libraries like json work perfectly well). Does this approach (getmember() and call run() on it) come with any limitations in the usage of otherwise standard python code? Am I doing anything wrong here?
answer count: 1
has answer: http://stackoverflow.com/a/48618222
type: Question
tagged with: python-3.x
tagged with: python
has title: Import ftplib in dynamically instanciated member class
accepted answer: http://stackoverflow.com/a/48618222
tagged with: inspection
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/48571873
has comment: http://stackoverflow.com/comment/84142228
has comment: http://stackoverflow.com/comment/84141501
answers question: http://stackoverflow.com/q/48570625
type: Answer
has comment: http://stackoverflow.com/comment/84141437
has body: This one should do the job. I created two lists, one of the xmls, one of the jpgs. Then I check, whether a filename exists in both lists. If yes: move! For readability, I added a new function to create the lists. import os import glob import shutil def remove_ext(list_of_pathnames): """ removes the extension from each filename """ return [os.path.splitext(filename)[0] for filename in list_of_pathnames] path = os.getcwd() os.chdir("path\\to\\folder\\") os.mkdir("image_with_xml") # create a new folder newpath = os.path.join("path\\to\\folder\\","image_with_xml") # made it os independent... list_of_jpgs = glob.glob(path+"\\*.jpg") list_of_xmls = glob.glob(path+"\\*.xml") print(list_of_jpgs, "\n\n", list_of_xmls) #remove jpgs_without_extension = remove_ext(list_of_jpgs) xmls_without_extension = remove_ext(list_of_xmls) print(jpgs_without_extension, "\n\n", xmls_without_extension) #remove for filename in jpgs_without_extension: if filename in xmls_without_extension: print("moving", filename) #remove shutil.move(filename + '.jpg'), newpath) # move image to new path. shutil.move(filename + '.xml'), newpath) # move image to new path.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84142147
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48570625

http://stackoverflow.com/a/48595984
score: 3
has comment: http://stackoverflow.com/comment/84189129
type: Answer
answers question: http://stackoverflow.com/q/48594666
has body: Try this to get all the data from that table: from urllib.request import urlopen from bs4 import BeautifulSoup page = urlopen("http://bifr.nic.in/asp/list.asp") soup = BeautifulSoup(page, "html5lib") table = soup.select_one("table.forumline") for items in table.select("tr")[4:]: data = ' '.join([item.get_text(" ",strip=True) for item in items.select("td")]) print(data) Partial Output: 359 2000 A &amp; F OVERSEAS LTD. 99 1988 A B C PRODUCTS LTD. 103 1989 A INFRASTRUCTURE LTD. 3 2006 A V ALLOYS LTD. 13 1988 A V J WIRES LTD.
accepted answer of: http://stackoverflow.com/q/48594666
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84189854
upvote count: 3

http://stackoverflow.com/q/48587804
tagged with: subprocess
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48588343
answer count: 1
tagged with: serial-processing
tagged with: multiprocessing
type: Question
tagged with: parallel-processing
has title: How to execute processes in serial and in parallel using python
has body: How can i create a process execution in serial fashion vs parallel fashion? For example i want each process to execute the following python function: def execute(): time.sleep(random.randint(0,9)) If i run the processes like: for process in process_list: process.run() Given a scenario of only 2 processes in a serial fahsion i would expect the output of the program to be exatcly: process 1 - start process 1 - end process 2 - start process 2 - end In a parallel scenario i would expect a possible output such as: process 1 - start process 2 - start process 2 - end process 1 - end How can i replicate these two scenarios in python with a processing module? By using multiprocessing or subprocess modules?
score: 0
tagged with: python

http://stackoverflow.com/comment/83980031
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48493249
has text: thanks for all response. I was wondering if I need to duplicate the second row, can I use this solution again? why drop_duplicate remove the second column? is there any way to remove the selected rows by drop_duplicate! @Tai
score: 0

http://stackoverflow.com/q/48494568
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83982761
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: opencv
accepted answer: http://stackoverflow.com/a/48494888
has comment: http://stackoverflow.com/comment/83982659
has answer: http://stackoverflow.com/a/48494888
tagged with: python
type: AnsweredQuestion
has title: The effect of using cv2.HoughLines() is wrong
has body: I refer to this link for experiments. This is the original picture： My test code: import cv2 import numpy as np img = cv2.imread('E:/image/sudoku.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,50,150,apertureSize = 3) lines = cv2.HoughLines(edges,1,np.pi/180,200) for rho,theta in lines[0]: a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) cv2.imwrite('E:/image/myhoughlines.jpg',img) cv2.imshow('1',img) cv2.waitKey(0) The result of my code running： But I want this effect: Where is wrong?

http://stackoverflow.com/comment/84146832
has text: Every value in Python (and pretty much every other language) has a 'truthy' or 'falsey' value in a boolean context. Look up which is which: it's in the docs. Empty list is falsey, non-empty list is truthy. It's been a long time since you were restricted to 0 and 1, even in C (C99 added stdbool.h) let alone C++ which has a proper boolean type.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48575073

http://stackoverflow.com/comment/84175808
type: Comment
comment on: http://stackoverflow.com/a/48589232
score: 0
type: AnswerComment
has text: It says it can't find `fibo.py`. What to do?

http://stackoverflow.com/a/48635276
type: Answer
answers question: http://stackoverflow.com/q/48635192
score: 2
accepted answer of: http://stackoverflow.com/q/48635192
has body: Your error occurs because Foo unconditionally references A_CLASS, but you bound the class to a global name B_CLASS. This is going to be a problem in other circumstances (pickle relies on the class name matching the name it was bound to in the defining module), but for this limited case it's fixable. Instead of referring to A_CLASS.a directly, refer to it in terms of self: def Foo(self): print self.a print self.b self will look for class attributes if no instance attribute of that name exists. If you want to be 100% sure it came from the class, not the instance, you can instead define it as: def Foo(self): # New-style class only, but safe against weirdness like redefining __class__ print type(self).a # Old-style class, and vast majority of non-pathological new-style classes print self.__class__.a print self.b which looks up the class, then gets the attribute from the class, bypassing instance attributes. In an inheritance hierarchy, this might be wrong. If there is a A_CHILD class with a different a class attribute, calling Foo on it will get the child's attribute. But that's the price of violating the rules; if you give a class the name A_CLASS and bind it to the name B_CLASS, you can't refer to it by the name A_CLASS for lookup (because there is no part of your program that has that binding).
downvote count: 0
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/a/48593235
type: Answer
has comment: http://stackoverflow.com/comment/84204240
has comment: http://stackoverflow.com/comment/84183767
accepted answer of: http://stackoverflow.com/q/48593221
score: 8
answers question: http://stackoverflow.com/q/48593221
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84184030
has comment: http://stackoverflow.com/comment/84204912
has body: You want to group your data based on some predicate. The essential steps are: Identify what group the item belongs to Place the item into the corresponding "bucket" for that group. There are quite a few ways of achieving this. Some more direct than others. Option 1 This is a good use case for itertools.groupby. The predicate here is the type of an element. Note, however, that this won't work if your data isn't sorted by type to begin with. This could cause problems, so pre-sort your data first: sample_list.sort(key=lambda x: id(type(x))) Now, call groupby, and unpack each group as a list inside a dict comprehension: from itertools import groupby {i.__name__ : list(g) for i, g in groupby(sample_list, key=type)} { "float": [ 1.23, 34.34 ], "str": [ "abc", "xyz" ], "int": [ 22, 104 ] } Option 2 Here's an alternative approach using groupby from the pandas API. This does not require a pre-sorting step. import pandas as pd s = pd.Series(sample_list) s.groupby(s.map(lambda x: type(x).__name__)).apply(list).to_dict() { "float": [ 1.23, 34.34 ], "str": [ "abc", "xyz" ], "int": [ 22, 104 ] } Option 3 Here's a third option using a dictionary with setdefault (similar to the other answer with a defaultdict): gps = {} for s in sample_list: gps.setdefault(type(s).__name__, []).append(s) gps { "float": [ 1.23, 34.34 ], "str": [ "abc", "xyz" ], "int": [ 22, 104 ] } If we're talking efficiency, however, the defaultdict approach in the other answer is slightly more efficient compared to dict + setdefault.
upvote count: 8
has comment: http://stackoverflow.com/comment/84205361
has comment: http://stackoverflow.com/comment/84183878

http://stackoverflow.com/q/48579740
linked to: http://stackoverflow.com/q/8231877
answer count: 3
has title: How to write a post on facebook using python
downvote count: 1
has body: I have tried with a sample code that I found on google.. import facebook def main(): # Fill in the values noted in previous steps here cfg = { "page_id" : "XXXXXXXXXXXXXX", # Step 1 "access_token" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Step 3 } api = get_api(cfg) msg = "Hello, world!" status = api.put_wall_post(msg) def get_api(cfg): graph = facebook.GraphAPI(cfg['access_token']) # Get page token to post as the page. You can skip # the following if you want to post as yourself. resp = graph.get_object('me/accounts') page_access_token = None for page in resp['data']: if page['id'] == cfg['page_id']: page_access_token = page['access_token'] graph = facebook.GraphAPI(page_access_token) return graph if __name__ == "__main__": main() But I am getting this error: AssertionError: Write operations require an access token on line status = api.put_wall_post(msg). Can some one help me in solving the issue?
has answer: http://stackoverflow.com/a/60505702
has comment: http://stackoverflow.com/comment/84158420
tagged with: facebook-graph-api
favorite count: 0
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/48761250
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48579872
tagged with: facebook-sdk-4.0
tagged with: python
has comment: http://stackoverflow.com/comment/84158436
score: 8
has comment: http://stackoverflow.com/comment/84158404

ms-word
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/48575110
tags question: http://stackoverflow.com/q/48528949
tags question: http://stackoverflow.com/q/48626396

http://stackoverflow.com/comment/84006379
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48506061
score: 0
has text: Please elaborate more. I assume you need to use try/exception handling instead of the assert. please check [this link](https://stackoverflow.com/questions/4606919/in-python-try-until-no-error) and if it didn't help, please elaborate more on your issue.

http://stackoverflow.com/q/48628673
has body: So following the current Django-allauth documentation, I keep getting this minor syntax error when I thought I followed the documentation to every last detail. Terminal error after running: ./manage.py migrate /settings.py", line 43 'django.contrib.auth', ^ SyntaxError: invalid syntax My settings.py file: Was I not supposed to keep the default apps above the allauth section? ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... # The following apps are required: 'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', # ... include the providers you want to enable: 'allauth.socialaccount.providers.amazon', 'allauth.socialaccount.providers.angellist', 'allauth.socialaccount.providers.asana',
answer count: 1
downvote count: 0
has title: How to fix the Django-allauth settings.py contrib syntax error?
tagged with: django
has answer: http://stackoverflow.com/a/48628725
accepted answer: http://stackoverflow.com/a/48628725
favorite count: 0
type: Question
tagged with: django-allauth
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/48567952
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I have some Python code with can visualize triangular mesh. The aim is to change the color of clicked triangle. My realization is too straight-forward and very long in execution time. I wonder if it is possible to optimize my algorithm with some data structures for example binary heap or if there was a more elegant and faster method. My code: import matplotlib.pyplot as plt import numpy as np from mesh import Mesh from matplotlib.pylab import figure, gca, triplot, show, cla from shapely.geometry import Polygon, Point def refreshPlot(): cla() ax.tripcolor(mesh.nodes[:,0], mesh.nodes[:,1], mesh.elements, facecolors=zfaces, edgecolors='r') ax.axis('equal') ax.set_title('Click to select') show() def onClick(event): (x,y) = (event.xdata, event.ydata) clicked_point = Point((x,y)) for i in range(mesh.n_elements): if(triangles[i].contains(clicked_point)==True): zfaces[i] = 0 refreshPlot() mesh = Mesh('relais.msh', False, 1e-03) fig, ax = plt.subplots() zfaces = np.ones(mesh.n_elements) triangles = [Polygon(mesh.nodes[tri]) for tri in mesh.elements] fig.canvas.mpl_connect('button_press_event', onClick) refreshPlot()
type: UnansweredQuestion
tagged with: shapely
tagged with: python
tagged with: optimization
tagged with: search
answer count: 0
score: 1
has title: Search optimization in the array of Shapely polygons

http://stackoverflow.com/a/48583070
has comment: http://stackoverflow.com/comment/84163554
has comment: http://stackoverflow.com/comment/84183971
accepted answer of: http://stackoverflow.com/q/48581973
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84162550
has body: You can change working directory after opening Spyder by typing inside IPython console cd path/to/working/dir. EDIT: I have found how you can set directory from the command line (from spyder3 --help). It is -w flag: spyder3 -w path/to/dir or cd path/to/dir spyder3 -w `pwd`
type: Answer
answers question: http://stackoverflow.com/q/48581973

http://stackoverflow.com/q/48530915
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/48531757
tagged with: python
has answer: http://stackoverflow.com/a/48531757
has comment: http://stackoverflow.com/comment/84057961
has comment: http://stackoverflow.com/comment/84057755
has comment: http://stackoverflow.com/comment/84057460
score: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48531405
upvote count: 2
has body: I am trying to take multiple csv files (15 by 15 matrices), flatten them out into 1D matrices and then write them row by row into a new csv file using python. An example of an input csv file: 0,1,1,1,1,1,1,1,1,0,0,0,0,0,0 0,0,1,0,0,0,0,0,1,0,0,0,0,0,0 .... .... This is the approach I am currently using: import pandas as pd import glob import numpy as np path = r'.../Model_AMs' allFiles = glob.glob(path + "/*.csv") for file_ in allFiles: df = pd.read_csv(file_, header=None).values.flatten() np.savetxt('trainingdata.csv', df, newline=" ", delimiter=',') However when I open trainingdata.csv it looks like this: 0.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 It is not delimiting the elements with ',' and also adds a lot of 0s rather than simply keeping the values as 1s or 0s. Any help would be appreciated. Thanks
tagged with: arrays
downvote count: 0
has title: Write 1D numpy arrays to csv file row by row
has comment: http://stackoverflow.com/comment/84057792
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/48531405

http://stackoverflow.com/comment/84215862
type: Comment
has text: `for player, height in players`** I'd say is the best
type: AnswerComment
comment on: http://stackoverflow.com/a/48609721
score: 1

http://stackoverflow.com/a/48609155
type: Answer
has body: For python 3.6,check out this a="""1::Erin Burkovich (2000)::Drama 2::Assassins (1995)::Thriller""" a=a.split("\n") c=[] for b in range(len(a)): g=[] d=a[b].split("::") e=d[1].split(" (")[1].split(")")[0] f=d[1].split(" (")[0] g.append(d[0]) g.append(f) g.append(d[2]) g.append(e) h="::".join(g) c.append(h) print("\n".join(c)) OUTPUT:: 1::Erin Burkovich::Drama::2000 2::Assassins::Thriller::1995
score: 0
answers question: http://stackoverflow.com/q/48609055

http://stackoverflow.com/comment/84058039
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48530970
score: 0
has text: Does it work if you plot every nth line?

http://stackoverflow.com/comment/83992556
type: Comment
comment on: http://stackoverflow.com/q/48498184
type: QuestionComment
has text: What do you mean by **data will not be inserted to the API**??
score: 0

http://stackoverflow.com/comment/84105413
comment on: http://stackoverflow.com/q/48530585
score: 0
type: Comment
type: QuestionComment
has text: Thanks, this worked wonders (the math.floor())

opencv
tags question: http://stackoverflow.com/q/48614241
type: Tag
tags question: http://stackoverflow.com/q/48498615
tags question: http://stackoverflow.com/q/48596593
tags question: http://stackoverflow.com/q/48615935
tags question: http://stackoverflow.com/q/48512532
tags question: http://stackoverflow.com/q/48633734
tags question: http://stackoverflow.com/q/48496032
tags question: http://stackoverflow.com/q/48553336
tags question: http://stackoverflow.com/q/48590565
tags question: http://stackoverflow.com/q/48490792
tags question: http://stackoverflow.com/q/48530522
tags question: http://stackoverflow.com/q/48507389
tags question: http://stackoverflow.com/q/48520006
tags question: http://stackoverflow.com/q/48545534
tags question: http://stackoverflow.com/q/48515421
tags question: http://stackoverflow.com/q/48494568
tags question: http://stackoverflow.com/q/48606911
tags question: http://stackoverflow.com/q/48496223
tags question: http://stackoverflow.com/q/48516211
tags question: http://stackoverflow.com/q/48489780
tags question: http://stackoverflow.com/q/48611517
tags question: http://stackoverflow.com/q/48573178
tags question: http://stackoverflow.com/q/48514483
tags question: http://stackoverflow.com/q/48588352
tags question: http://stackoverflow.com/q/48628679
tags question: http://stackoverflow.com/q/48620562
tags question: http://stackoverflow.com/q/48551875
tags question: http://stackoverflow.com/q/48495282
tags question: http://stackoverflow.com/q/48636133
tags question: http://stackoverflow.com/q/48574664
tags question: http://stackoverflow.com/q/48545150
tags question: http://stackoverflow.com/q/48528754
tags question: http://stackoverflow.com/q/48500434
tags question: http://stackoverflow.com/q/48558150
tags question: http://stackoverflow.com/q/48539751
tags question: http://stackoverflow.com/q/48589151
tags question: http://stackoverflow.com/q/48630885
tags question: http://stackoverflow.com/q/48517476
tags question: http://stackoverflow.com/q/48634363
tags question: http://stackoverflow.com/q/48590321
tags question: http://stackoverflow.com/q/48528417
tags question: http://stackoverflow.com/q/48576087
tags question: http://stackoverflow.com/q/48527579
tags question: http://stackoverflow.com/q/48509138
tags question: http://stackoverflow.com/q/48517774
tags question: http://stackoverflow.com/q/48555402
tags question: http://stackoverflow.com/q/48578343
tags question: http://stackoverflow.com/q/48569647
tags question: http://stackoverflow.com/q/48519641
tags question: http://stackoverflow.com/q/48555287
tags question: http://stackoverflow.com/q/48525971
tags question: http://stackoverflow.com/q/48583135
tags question: http://stackoverflow.com/q/48613725
tags question: http://stackoverflow.com/q/48590635
tags question: http://stackoverflow.com/q/48526973
tags question: http://stackoverflow.com/q/48533305
tags question: http://stackoverflow.com/q/48488723
tags question: http://stackoverflow.com/q/48491217
tags question: http://stackoverflow.com/q/48641879
tags question: http://stackoverflow.com/q/48507321
tag name: opencv
tags question: http://stackoverflow.com/q/48493835
tags question: http://stackoverflow.com/q/48590712
tags question: http://stackoverflow.com/q/48569567
tags question: http://stackoverflow.com/q/48560201
tags question: http://stackoverflow.com/q/48599872
tags question: http://stackoverflow.com/q/48561126
tags question: http://stackoverflow.com/q/48528752
tags question: http://stackoverflow.com/q/48597099

http://stackoverflow.com/a/50381123
has body: I hope this code will help you. I used Telethon V0.19, but the previous versions are pretty much the same. also get_message_history is deprecated, use get_messages instead. from telethon import TelegramClient api_id = XXXXXXX api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' phone_number = '+98XXXXXXXXX' ################################################ channel_username = 'tehrandb' ################################################ client = TelegramClient('session_name', api_id, api_hash) assert client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) # --------------------------------------- msgs = client.get_messages(channel_username, limit=100) for msg in msgs.data: if msg.media is not None: client.download_media(message=msg)
upvote count: 4
downvote count: 0
type: Answer
score: 4
answers question: http://stackoverflow.com/q/48609616

http://stackoverflow.com/comment/84227504
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48615106
has text: @JohnBailey There is but it is a bit messy. Do you see help link under Add Comment button? It explains a bit.
type: Comment

http://stackoverflow.com/comment/84273355
score: 0
has text: Interestingly enough, for the 9th digit they round the same.. This seems to lie in the rounding policy of numpys round (np.round(a,8) also rounds up to 8) I guess?
comment on: http://stackoverflow.com/q/48638398
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48489753
tagged with: multiprocessing
tagged with: numpy
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48489897
has comment: http://stackoverflow.com/comment/83972658
has answer: http://stackoverflow.com/a/48489897
tagged with: python
has comment: http://stackoverflow.com/comment/83972863
type: AnsweredQuestion
score: 0
tagged with: pool
has title: Why doesn't multiprocessing pool map speed up compared to serial map?
answer count: 1
has comment: http://stackoverflow.com/comment/83972734
has comment: http://stackoverflow.com/comment/83972612
has comment: http://stackoverflow.com/comment/83972788
has body: I have this very simple python code that I want to speed up by parallelizing it. However no matter what I seem to do, multiprocessing.Pool.map doesn't gain anything over the standard map. I've read other threads where people use this with very small functions that don't parallelize well and lead to excessive overhead but I would think that shouldn't be the case here. Am I doing something wrong? Here's the example #!/usr/bin/python import numpy, time def AddNoise(sample): #time.sleep(0.001) return sample + numpy.random.randint(0,9,sample.shape) #return sample + numpy.ones(sample.shape) n=100 m=10000 start = time.time() A = list([ numpy.random.randint(0,9,(n,n)) for i in range(m) ]) print("creating %d numpy arrays of %d x %d took %.2f seconds"%(m,n,n,time.time()-start)) for i in range(3): start = time.time() A = list(map(AddNoise, A)) print("adding numpy arrays took %.2f seconds"%(time.time()-start)) for i in range(3): import multiprocessing start = time.time() with multiprocessing.Pool(processes=2) as pool: A = list(pool.map(AddNoise, A, chunksize=100)) print("adding numpy arrays with multiprocessing Pool took %.2f seconds"%(time.time()-start)) for i in range(3): import concurrent.futures start = time.time() with concurrent.futures.ProcessPoolExecutor(max_workers=2) as executor: A = list(executor.map(AddNoise, A)) print("adding numpy arrays with concurrent.futures.ProcessPoolExecutor took %.2f seconds"%(time.time()-start)) Which results in the following output on my 4-core/8-thread laptop, which is idle otherwise $ python test-pool.py creating 10000 numpy arrays of 100 x 100 took 1.54 seconds adding numpy arrays took 1.65 seconds adding numpy arrays took 1.51 seconds adding numpy arrays took 1.51 seconds adding numpy arrays with multiprocessing Pool took 1.99 seconds adding numpy arrays with multiprocessing Pool took 1.98 seconds adding numpy arrays with multiprocessing Pool took 1.94 seconds adding numpy arrays with concurrent.futures.ProcessPoolExecutor took 3.32 s…
has comment: http://stackoverflow.com/comment/83972459
type: Question

http://stackoverflow.com/comment/84027407
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48516264
has text: No. Just set the above snippet to the first line of your script.
type: Comment

http://stackoverflow.com/q/48567122
tagged with: data-pipeline
has title: Luigi not picking up next task to run, bunch of pending tasks left, no failed tasks
possible better answer: http://stackoverflow.com/a/71068257
tagged with: python
has answer: http://stackoverflow.com/a/71068257
score: 2
type: AnsweredQuestion
tagged with: worker
has body: I am running a big Luigi workflow that is supposed run over a hundred tasks in total. The workflow goes well for quite a while, but at one stage it comes to a point where there are 15 pending tasks and all other tasks are successfully done, and no failed tasks. However, it doesn't seem to pick up any more of those pending tasks to execute. I have thoroughly looked at the logs and there are no errors. From that point on, it just periodically prints the following logs: There are no more tasks to run at this time There are 15 pending tasks possibly being run by other workers There are 15 pending tasks unique to this worker There are 15 pending tasks last scheduled by this worker The luigi version that I am using is 2.6.1. And here is a screenshot: Any idea what might be going on here? Why would it think there is no task to run? Here is my luigi worker configuration: [worker] keep-alive = True max-reschedules = 3
answer count: 2
accepted answer: http://stackoverflow.com/a/48570552
tagged with: luigi
upvote count: 2
has answer: http://stackoverflow.com/a/48570552
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/84211827
has text: I know how to upload a local file but In the above code instead of 'image_uri' I want to keep my local file and when I am trying to do so it is not detecting any faces.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48607548
type: Comment

http://stackoverflow.com/comment/84266714
score: 0
comment on: http://stackoverflow.com/a/48634942
type: Comment
has text: @Chandan yw~ happy coding
type: AnswerComment

http://stackoverflow.com/comment/84104547
has text: Thanks for this - I can visualize this way more easily. How do I call a value here? I know it is probably simple, but I just cant picture it. If I want to scan through each one of these dicts, and if one particular team is represented (ex. all dicts containing Miami Heat), pull a specific value out (like points scored), how would I go about that?
comment on: http://stackoverflow.com/a/48553262
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48669918
has body: In case anyone else stumbles upon this same issue, there seems to be a solution in the works for FAB itself. Here's the PR that should resolve this problem: https://github.com/dpgaspar/Flask-AppBuilder/pull/694
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48592998
answers question: http://stackoverflow.com/q/48592998
type: Answer
score: 0

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

http://stackoverflow.com/comment/83980080
has text: @AlterNative There are only a few choices that you can choose from. See [Here](http://pandas.pydata.org/pandas-docs/version/0.17/generated/pandas.DataFrame.drop_duplicates.html) for the `keep` parameter.
comment on: http://stackoverflow.com/a/48493249
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/48626764
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48626567
type: AcceptedAnswer
has body: Your xticks-labels are overlapping. You could try to solve it by rotating them: plt.xticks(rotation=70)
answers question: http://stackoverflow.com/q/48626567
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84945121
has text: This worked as a workaround for now. Thank you. The issue is mentioned by several at https://github.com/supermihi/pytaglib/issues/42
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48592020
score: 0

http://stackoverflow.com/comment/84259176
comment on: http://stackoverflow.com/q/48629461
type: Comment
score: 1
type: QuestionComment
has text: Please also note the "minimal" I mentioned. You don't need to show us all your code. How much of that code can you get rid of while still demonstrating the problem? E.g. what happens if you replace all of that code by `from jsonpath_rw import parse as parse_jsonpath; results = parse_jsonpath("bpi.USD.rate_float").find({your_actual_dict_goes_here}); print(results)` (with newlines instead of `;`)? Do you still have the same problem?

http://stackoverflow.com/comment/108480035
comment on: http://stackoverflow.com/q/48603413
type: Comment
type: QuestionComment
has text: Have you considered accepting the upvoted answer, because it seems to work?
score: 0

http://stackoverflow.com/comment/83999496
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48502828
has text: In the [docstring for `minimize`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html), the first line of the description of the `constraints` argument is "Constraints definition (only for COBYLA and SLSQP)." You are using L-BFGS-B, which doesn't support equality constraints.

http://stackoverflow.com/q/48572064
type: AnsweredQuestion
upvote count: 8
tagged with: python
tagged with: gunicorn
downvote count: 2
answer count: 1
score: 6
linked to: http://stackoverflow.com/q/36820151
accepted answer: http://stackoverflow.com/a/48572328
has body: Im trying to develop a flask application with gunicorn, since gunicorn is implemented in python (i checked github). My question are gunicorn's threads or under GIL ?
has title: Are gunicorns threads real?
favorite count: 0
has answer: http://stackoverflow.com/a/48572328
type: Question

http://stackoverflow.com/comment/84726957
has text: Yes, not supported for now. There is nothing in the documentation (http://doc.aldebaran.com/2-5/naoqi/motion/exploration-api.html?highlight=explore) that mentions it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48823207
type: AnswerComment

http://stackoverflow.com/a/48596468
type: AcceptedAnswer
downvote count: 2
has body: Just loop through the items. First you loop through the internal lists: for lst in x: Then you sum the items in the list using the sum method: total = sum(lst) Together it looks like this: new_list = list() for lst in x: lst = sum(lst) new_list.append(total) print(new_list) Hope this helps. Edit: I haven't used the sum method before. Which is why the two downvotes despite the program working fine.
answers question: http://stackoverflow.com/q/48596243
type: Answer
score: -2
accepted answer of: http://stackoverflow.com/q/48596243
upvote count: 0

http://stackoverflow.com/comment/84055809
type: QuestionComment
has text: No, using an array in itself would not fix the issue. To continue with your approach, you'd need to initialise the list with the correct number of elements beforehand; `x = [0 for i in range(10)]` where 10 is your number of bins, for example. But numpy provides fast methods for binning data.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48530092

http://stackoverflow.com/a/48622192
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/48621983
type: Answer
has comment: http://stackoverflow.com/comment/84240840
has comment: http://stackoverflow.com/comment/84246216
answers question: http://stackoverflow.com/q/48621983
has body: I think the problem is that you're not calling super in your get_form_kwargs method, so the POSTed data is not actually being passed to the form. You probably need: def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['site_id'] = self.site_id return kwargs

http://stackoverflow.com/comment/84120216
score: 1
type: Comment
type: QuestionComment
has text: `df.apply` is not vectorised. It may appear so syntactically but it is just a thinly veiled loop which is faster than `df.iterrows`.
comment on: http://stackoverflow.com/q/48562236

http://stackoverflow.com/a/48553275
has comment: http://stackoverflow.com/comment/84103173
has comment: http://stackoverflow.com/comment/84103375
score: 0
type: AcceptedAnswer
has body: Assuming the paragraphs are neatly formatted into sentences with ending periods, something like: for index, paragraph in df['column_name'].iteritems(): for sentence in paragraph.split('.'): if 'superb prod' in sentence: print(sentence) df['extracted_sentence'][index] = sentence This is going to be quite slow, but idk if there's a better way.
answers question: http://stackoverflow.com/q/48553196
has comment: http://stackoverflow.com/comment/84103434
has comment: http://stackoverflow.com/comment/84103348
accepted answer of: http://stackoverflow.com/q/48553196
type: Answer

http://stackoverflow.com/q/48557376
has title: Why is my chart not printing and how do I change the bar chart colors?
tagged with: python
accepted answer: http://stackoverflow.com/a/48557842
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/24183101
score: 0
has answer: http://stackoverflow.com/a/48557842
tagged with: pandas
tagged with: matplotlib
answer count: 1
type: Question
has body: Below is the dataframe that I am trying to print using Python 3.6.3. Prior to changing the colors using the code below, my chart prints perfectly find. However, now the chart prints without any bars. Also, I can't figure out how to change all the bar chart colors using the list below. I'm working on a project in Jupyter and the chart prints out fine. The only problem there is that the colors are still not adjusted according to the list. Only orange and green print out. market_cap_usd market_cap_perc id bitcoin 1.862130e+11 33.481495 ethereum 1.141650e+11 20.527111 ripple 4.906157e+10 8.821376 bitcoin-cash 2.782094e+10 5.002265 cardano 1.522458e+10 2.737413 neo 1.041332e+10 1.872338 stellar 9.829044e+09 1.767283 litecoin 9.758786e+09 1.754651 eos 8.518116e+09 1.531575 nem 7.917498e+09 1.423583 # Colors for the bar plot COLORS = ['orange', 'green', 'orange', 'cyan', 'cyan', 'blue', 'silver', 'orange', 'red', 'green'] # Plotting market_cap_usd as before but adding the colors and scaling the y-axis ax = cap10.plot.bar(color=COLORS, title=TOP_CAP_TITLE, logy=True) # Annotating the y axis with 'USD' ax.set_ylabel('USD') # Final touch! Removing the xlabel as it is not very informative # ... YOUR CODE FOR TASK 5 ... ax.set_xlabel('') plt.show(ax)

http://stackoverflow.com/q/48601110
score: 1
has comment: http://stackoverflow.com/comment/84206647
downvote count: 0
has comment: http://stackoverflow.com/comment/84206249
upvote count: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/84206071
has comment: http://stackoverflow.com/comment/84206721
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48605209
has title: Django Rest Framework Filtering Not working
has comment: http://stackoverflow.com/comment/84206528
possible better answer: http://stackoverflow.com/a/48602806
has comment: http://stackoverflow.com/comment/84206794
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48602806
accepted answer: http://stackoverflow.com/a/48605209
has comment: http://stackoverflow.com/comment/84206569
has body: Using Django 1.11 &amp; djangorestframework==3.7.7, I want to return Videos where is_thumbnail=True on a GET call. However, all of my testing with filters have been returning all Videos objects. Model: class Videos(models.Model): """This class represents the Videos model.""" uid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) is_thumbnail = models.BooleanField(default=False) file_name = models.CharField(unique=True, max_length=64) file_path = models.CharField(unique=True, max_length=256) file_created_time = models.DateTimeField() owner = models.ForeignKey('auth.User', related_name='videos', on_delete=models.CASCADE) created_time = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.file_name) view: class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This class handles the http GET, PUT and DELETE requests.""" serializer_class = VideosSerializer permission_classes = (permissions.IsAuthenticated, IsOwner) lookup_field = 'uid' def get_queryset(self): return Videos.objects.filter(is_thumbnail=True) If I put a print statement inside of the get_queryset function, I don't see that statement in the log. So it seems like the function isn't being called. api/urls.py urlpatterns = { url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/videos/$', CreateView.as_view(), name="create"), url(r'^api/videos/(?P&lt;uid&gt;[0-9a-f-]+)/$', DetailsView.as_view(), name="details"), url(r'^get-token/', obtain_auth_token), } securedash_project/urls.py urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns = [ url(r'', include('secureDash.dash.urls')), url(r'^dash/', include('secureDash.dash.urls')), url(r'^admin/', admin.site.urls), url(r'^', include('secureDash.api.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
has comment: http://stackoverflow.com/comment/84206508
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/84206615

http://stackoverflow.com/comment/84202235
score: 0
comment on: http://stackoverflow.com/q/48602779
type: Comment
has text: Why downvote? If you think the question should be closed, write a comment, explaining that.
type: QuestionComment

http://stackoverflow.com/a/48549285
accepted answer of: http://stackoverflow.com/q/48542640
upvote count: 2
answers question: http://stackoverflow.com/q/48542640
type: AcceptedAnswer
type: Answer
has body: In [1]: from scipy import sparse In [2]: s, n1, n2 = 10,3,5 In [3]: v0 = sparse.random(1, n1) In [4]: v0 Out[4]: &lt;1x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 0 stored elements in COOrdinate format&gt; In [5]: l = [sparse.random(1, n2) for i in range(s)] In [6]: l Out[6]: [&lt;1x5 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 0 stored elements in COOrdinate format&gt;, ... &lt;1x5 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 0 stored elements in COOrdinate format&gt;] Instead of np.repeat use sparse.vstack to create a stack of V0 copies In [7]: V0 = sparse.vstack([v0]*s) In [8]: V0 Out[8]: &lt;10x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 0 stored elements in COOrdinate format&gt; Similarly convert the list of n2 matrices into one matrix: In [10]: V1 = sparse.vstack(l) In [11]: V1 Out[11]: &lt;10x5 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 0 stored elements in COOrdinate format&gt; Now join them: In [12]: m = sparse.hstack((V0,V1)) In [13]: m Out[13]: &lt;10x8 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 0 stored elements in COOrdinate format&gt; I won't make any claims about this being efficient. hstack and vstack use bmat (check their code). bmat collects the coo attributes of all the blocks, and joins them (with offsets) into the inputs to a new coo_matrix call (again, the code is readable). So you could avoid some intermediate conversions by using bmat directly, or even playing with the coo attributes directly. But hstack and vstack are relatively intuitive.
score: 2
downvote count: 0

http://stackoverflow.com/comment/84110313
has text: Look at `numpy.loadtxt()`: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html
score: 3
comment on: http://stackoverflow.com/q/48557207
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48515308
score: 0
type: Answer
has body: from datetime import datetime start_date = datetime(2017, 10, 10, 10, 10, 10) email_date = datetime.strptime("Thu, 18 Jan 2018 15:50:49", "%a, %d %b %Y %H:%M:%S") start_date, email_date &gt;&gt;&gt;datetime.datetime(2017, 10, 10, 10, 10, 10) datetime.datetime(2018, 1, 18, 15, 50, 49)
answers question: http://stackoverflow.com/q/48515176

http://stackoverflow.com/comment/84080560
comment on: http://stackoverflow.com/a/48542663
type: AnswerComment
score: 0
has text: Thank you for answering, but I have just tried, now, I can't even import googlemaps. I am using Visual studio, and it tells me that it can't analyze 'googlemaps', the IntelliSense may be lost. But sometimes, it can be imported correctly, but finally, when I want to start server, the result is the same.
type: Comment

http://stackoverflow.com/q/48549605
has body: I'm new to selenium. In a website When I click on the navigation menu from the browser it opens up. But I couldn't open it with selenium webdriver. Here is the source HTML Sample: Quick Filters Category Functional Category Special Skilled Category I tried this: foo = driver.find_element_by_xpath('//*[@id="bs-example-navbar-collapse-1"]/ul/li[1]/a') foo.click() It didn't work. It redirects to another page.
answer count: 1
has answer: http://stackoverflow.com/a/48551262
tagged with: selenium
accepted answer: http://stackoverflow.com/a/48551262
type: Question
tagged with: python
has title: Navigation bar doesn't collapse on click with selenium webdriver
type: AnsweredQuestion
score: 0

flask
tags question: http://stackoverflow.com/q/48570334
tags question: http://stackoverflow.com/q/48645166
tags question: http://stackoverflow.com/q/48595482
tags question: http://stackoverflow.com/q/48603220
tags question: http://stackoverflow.com/q/48590127
tags question: http://stackoverflow.com/q/48640959
tags question: http://stackoverflow.com/q/48488827
tags question: http://stackoverflow.com/q/48520265
tags question: http://stackoverflow.com/q/48498503
tags question: http://stackoverflow.com/q/48498292
tags question: http://stackoverflow.com/q/48637088
tags question: http://stackoverflow.com/q/48517547
tags question: http://stackoverflow.com/q/48622983
tags question: http://stackoverflow.com/q/48601291
tags question: http://stackoverflow.com/q/48520750
tags question: http://stackoverflow.com/q/48559509
tags question: http://stackoverflow.com/q/48560425
tags question: http://stackoverflow.com/q/48560345
tags question: http://stackoverflow.com/q/48536650
tags question: http://stackoverflow.com/q/48503499
tags question: http://stackoverflow.com/q/48518584
tags question: http://stackoverflow.com/q/48598273
tags question: http://stackoverflow.com/q/48511460
tags question: http://stackoverflow.com/q/48591394
tags question: http://stackoverflow.com/q/48510404
tags question: http://stackoverflow.com/q/48602128
tags question: http://stackoverflow.com/q/48514389
tags question: http://stackoverflow.com/q/48510665
tags question: http://stackoverflow.com/q/48549792
tags question: http://stackoverflow.com/q/48578906
tags question: http://stackoverflow.com/q/48498668
tags question: http://stackoverflow.com/q/48506113
tags question: http://stackoverflow.com/q/48552474
tags question: http://stackoverflow.com/q/48514185
tags question: http://stackoverflow.com/q/48572024
tags question: http://stackoverflow.com/q/48571304
tags question: http://stackoverflow.com/q/48513139
tags question: http://stackoverflow.com/q/48615707
tags question: http://stackoverflow.com/q/48631901
tags question: http://stackoverflow.com/q/48512055
tags question: http://stackoverflow.com/q/48592296
tags question: http://stackoverflow.com/q/48510466
tags question: http://stackoverflow.com/q/48628521
tags question: http://stackoverflow.com/q/48564242
tags question: http://stackoverflow.com/q/48606268
tags question: http://stackoverflow.com/q/48591655
tags question: http://stackoverflow.com/q/48527252
tags question: http://stackoverflow.com/q/48622486
tags question: http://stackoverflow.com/q/48549074
tags question: http://stackoverflow.com/q/48491178
tags question: http://stackoverflow.com/q/48613592
tags question: http://stackoverflow.com/q/48493722
tags question: http://stackoverflow.com/q/48639352
tags question: http://stackoverflow.com/q/48596059
tags question: http://stackoverflow.com/q/48635934
tags question: http://stackoverflow.com/q/48588120
tags question: http://stackoverflow.com/q/48527904
tags question: http://stackoverflow.com/q/48542822
tags question: http://stackoverflow.com/q/48624632
tags question: http://stackoverflow.com/q/48491147
tags question: http://stackoverflow.com/q/48537626
tags question: http://stackoverflow.com/q/48540355
tags question: http://stackoverflow.com/q/48588316
tag name: flask
tags question: http://stackoverflow.com/q/48641798
tags question: http://stackoverflow.com/q/48499299
tags question: http://stackoverflow.com/q/48563848
tags question: http://stackoverflow.com/q/48591664
tags question: http://stackoverflow.com/q/48506093
tags question: http://stackoverflow.com/q/48632977
tags question: http://stackoverflow.com/q/48550918
tags question: http://stackoverflow.com/q/48624306
tags question: http://stackoverflow.com/q/48640652
tags question: http://stackoverflow.com/q/48614941
tags question: http://stackoverflow.com/q/48592998
tags question: http://stackoverflow.com/q/48493028
tags question: http://stackoverflow.com/q/48643911
tags question: http://stackoverflow.com/q/48533983
tags question: http://stackoverflow.com/q/48546048
tags question: http://stackoverflow.com/q/48591476

http://stackoverflow.com/comment/84053777
type: AnswerComment
comment on: http://stackoverflow.com/a/48529274
score: 1
type: Comment
has text: You can always use `upper = str.upper` and call it like `upper("Hello World")`

http://stackoverflow.com/comment/84174869
type: QuestionComment
has text: What error your are getting ?
comment on: http://stackoverflow.com/q/48588828
score: 0
type: Comment

http://stackoverflow.com/comment/104672939
comment on: http://stackoverflow.com/a/59159239
has text: For linux admins: requiretty as a default is not a good idea: https://bugzilla.redhat.com/show_bug.cgi?id=1020147
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83991400
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48497115
has text: i have pasted urls.py of both mysite and polls
score: 0

http://stackoverflow.com/q/48546215
type: Question
has title: gdb python pretty printer uint64_t is interpreted signed
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has body: When I try to use: class MyPrinter: def __init__(self, val): self.val = val def to_string(self): return str(self.val['fData'][0]) + ":" + "%016x" % (self.val['fData'][0]).cast(gdb.lookup_type("uint64_t")) It prints 2929725441843584891:28a879c45a82df7b But also 9918728419520062851:-7659990ddaef5a7d When the most significant bit is set for val, it is interpreted as signed. fData[] is uint64_t. How can I avoid that? All my values should be unsigned.
has comment: http://stackoverflow.com/comment/138594066
score: 0
has answer: http://stackoverflow.com/a/48585026
type: UnansweredQuestion
tagged with: signedness
answer count: 1

http://stackoverflow.com/comment/84186118
type: Comment
comment on: http://stackoverflow.com/q/48594405
type: QuestionComment
has text: `div.find('p', {"class":"title"}).text`
score: 0

http://stackoverflow.com/q/48596542
has comment: http://stackoverflow.com/comment/84190182
tagged with: python
has answer: http://stackoverflow.com/a/58424230
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75276407
tagged with: for-loop
downvote count: 2
has answer: http://stackoverflow.com/a/48596750
possible better answer: http://stackoverflow.com/a/48596750
has body: I am trying to write a program which will print "YES" if all the numbers in the list are continuous and should return "NO" if the numbers are not continuous. By continuous I mean every number in the list should be greater than one from the previous element. For example: It should print "YES" for inputs: [3, 4, 5], [7, 8, 9], [1, 2, 3], [0, 1, 2, 3, 4, 5].. etc It should print "NO" for inputs: [9, 1, 0], [3, 2, 4], [5, 5], [9, 8, 2, 3, 7].. etc I used enumerate for this purpose. Here's my code: inp=[1,2,3,4,5] flag=0 for index,e in enumerate(inp): if index!=len(inp)-1: if inp[index+1]==inp[index]+1: flag=1 if flag==1: print ("YES") else: print ("NO") The code works fine but i find it redundant. Is there a better way to do it using enumerate or without using enumerate?
has comment: http://stackoverflow.com/comment/84190281
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: enumerate
has title: How to check all the integers in the list are continuous?
upvote count: 5
score: 3
has comment: http://stackoverflow.com/comment/84189988
has answer: http://stackoverflow.com/a/48596742
accepted answer: http://stackoverflow.com/a/48596742

http://stackoverflow.com/a/48568869
upvote count: 1
has comment: http://stackoverflow.com/comment/84140054
has comment: http://stackoverflow.com/comment/84143940
answers question: http://stackoverflow.com/q/48568635
type: Answer
has body: Please note that the Python Math.log() function is the base of e by default. By your questions it's unclear what base you expect so I'll assume log base of 10 like Google does. In order to make it equivalent to the mathematical function provided the code would need to be: import math #assuming x equals 2 x = 2 function1 = round(10 * math.log(x,10) + 5) function2 = round(10 * math.log(x,10)) + 5) function3 = 10 * round(math.log(x,10)) + 5) function4 = 10*math.log(x,10)+5 print(function1) print(function2) print(function3) print(function4) Now, assuming x = 2, the calculations for the mathematical equation is 8.01029995664 Looking at the printed output from the above code: 8 8 5 8.010299956639813 It clearly shows that functions 1,2 and 4 are roughly mathematically equivalent with function 3 being incorrect. This is because the round function uses Half and Above rule to round up. Math.log(2,10) results in 0.3, so when the round function happens it drops to zero. As for the equivalence of int() and round() the link referenced by IMCoins is pretty good. The summation is that int() removes decimal values from a number and the round uses the half and above rule so it will act like the int() for anything less than x.5. As for the speed question, if accuracy is non-negotiable it would be best to round upon completion of the answer due to the same reasons as why function 3 was wrong above. If you're fairly certain you can round safely at a step, then I agree with the answer above to use CProfile and find the bottlenecks Hope this helps.
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84203150

http://stackoverflow.com/comment/84142705
type: QuestionComment
comment on: http://stackoverflow.com/q/48572819
score: 0
has text: Then simply do some correction after the operation, something like [this](https://hastebin.com/ewohepeyer.py).
type: Comment

http://stackoverflow.com/a/48622705
upvote count: 7
score: 7
accepted answer of: http://stackoverflow.com/q/48621130
has body: try without content-type in header,it will help for sure.
answers question: http://stackoverflow.com/q/48621130
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84027519
score: 0
has text: Can you please provide the model where this field is declared?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48516612

http://stackoverflow.com/q/48585877
score: 0
has body: I am supposed to add up all the numbers in each row an output that number, and output the grand total of all rows, and i'm pretty lost, can someone point me in the right direction? This is the list and system code to work from: import sys numbers= sys.argv[1:] for i in range(0,len(numbers)): numbers[i]= numbers[i].split(',') This is my code: for i in range (0,row): total = total + i print (total)
has comment: http://stackoverflow.com/comment/84169367
answer count: 1
has answer: http://stackoverflow.com/a/48586227
has comment: http://stackoverflow.com/comment/84168800
has comment: http://stackoverflow.com/comment/84168736
type: Question
has title: addition of rows and grand total in 2d lists python
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84168657
has comment: http://stackoverflow.com/comment/84168696

http://stackoverflow.com/comment/84018245
comment on: http://stackoverflow.com/q/48511684
type: Comment
type: QuestionComment
has text: What issues are you currently experiencing?
score: 2

http://stackoverflow.com/comment/84116319
score: 0
type: QuestionComment
type: Comment
has text: Possible duplicate of [Python date string to date object](https://stackoverflow.com/questions/2803852/python-date-string-to-date-object)
comment on: http://stackoverflow.com/q/48560319

http://stackoverflow.com/q/48571049
tagged with: qscrollarea
tagged with: qt
tagged with: qdockwidget
score: 0
tagged with: pyqt
type: UnansweredQuestion
has title: How to size QScrollArea in QDockWidget at app launch?
has comment: http://stackoverflow.com/comment/84139890
answer count: 1
has comment: http://stackoverflow.com/comment/84140539
type: Question
has comment: http://stackoverflow.com/comment/84140790
has comment: http://stackoverflow.com/comment/84140494
has comment: http://stackoverflow.com/comment/84140819
has answer: http://stackoverflow.com/a/48572035
has body: How do I resize a QScrollArea widget to expland to a QDockWidget's dimensions at app launch? When my app launches, the QScrollArea is too small. See photo. I want it to expand to take up the entire QDockWidget area. After app launch, if I resize the QDockWidget manually with my mouse, the QScrollArea properly expands automatically to the QDockWidget area. See photo, taken just after resizing the dock. I've tried using QScollArea.resize(QDockWidget.width(), QDockWidget.height()) in the __init__ routine for the main window, but it reports a QDockWidget.height() that is too small: it's not the actual height of the displayed main window. I think the height request is reporting a height that Qt reports for the widget before it's actually displayed. I've tried QScrollArea.adjustSize() and QScrollArea.adjustGeometry() to no avail. I've also tried reading the height and width from the MDI area (mdiArea.height()) but this is also underreported by Qt, I think because the window hasn't yet displayed or maximized by the time the height request is made. I'll also attach the code to create the main window, generated by Qt Designer. Any suggestions greatly appreciated! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.mdiArea = QtWidgets.QMdiArea(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mdiArea.sizePolicy().hasHeightForWidth()) self.mdiArea.setSizePolicy(sizePolicy) self.mdiArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.mdiArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) brush = QtGui.QBrush(QtGui.QColor(110, 115, 205)) brush.setStyle(QtCore.Qt.SolidPattern) self.mdiArea.setB…
has comment: http://stackoverflow.com/comment/84140078
tagged with: python
has comment: http://stackoverflow.com/comment/84140177

http://stackoverflow.com/comment/84131089
comment on: http://stackoverflow.com/a/48567421
has text: Considering the audience here, I think recommending a debugger would be overkill.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/48572831
has answer: http://stackoverflow.com/a/50111244
has comment: http://stackoverflow.com/comment/115363216
downvote count: 5
tagged with: python
has body: The typing module provides a base class for generic type hints: The typing.Generic class. Subclasses of Generic accept type arguments in square brackets, for example: list_of_ints = typing.List[int] str_to_bool_dict = typing.Dict[str, bool] My question is, how can I access these type arguments? That is, given str_to_bool_dict as input, how can I get str and bool as output? Basically I'm looking for a function such that &gt;&gt;&gt; magic_function(str_to_bool_dict) (&lt;class 'str'&gt;, &lt;class 'bool'&gt;)
accepted answer: http://stackoverflow.com/a/50101934
tagged with: python-typing
has answer: http://stackoverflow.com/a/50101934
has title: How to access the type arguments of typing.Generic?
type: AnsweredQuestion
score: 79
has answer: http://stackoverflow.com/a/48573907
possible better answer: http://stackoverflow.com/a/50103907
linked to: http://stackoverflow.com/q/49171189
has answer: http://stackoverflow.com/a/50103907
upvote count: 84
tagged with: generics
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55677007
answer count: 5

http://stackoverflow.com/q/48603533
type: Question
has comment: http://stackoverflow.com/comment/84203772
has comment: http://stackoverflow.com/comment/84205750
has title: Python Selection sort with nested while loop
tagged with: arrays
has comment: http://stackoverflow.com/comment/84203957
has answer: http://stackoverflow.com/a/57749692
possible better answer: http://stackoverflow.com/a/48609517
tagged with: python
tagged with: sorting
score: 4
has body: I know that I can sort arrays using selection sort with a nested for loop as follows: def selection_sort(arr): for k in range(len(arr)): cur = k for i in range(cur, len(arr)): if arr[cur] &gt; arr[i]: cur = i temp = arr[cur] arr[cur] = arr[k] arr[k] = temp But can this be done with a while loop nested in a for loop? I'm curious because I saw it mentioned that the syntax for this selection sort function could be similar to an insertion sort function, such as the one that follows: def insertion_sort(arr): for k in range(1, len(arr)): cur = arr[k] j = k while j &gt; 0 and arr[j-1] &gt; cur: arr[j] = arr[j-1] j = j - 1 arr[j] = cur Am I overlooking something simple? It has been a while since I've used python, but it just seems simpler to use a for loop instead of a while loop, doesn't it? Nevertheless, I'm confused on how it can be done.
upvote count: 4
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/48604967
has comment: http://stackoverflow.com/comment/84203765
downvote count: 0
has answer: http://stackoverflow.com/a/48604967
has answer: http://stackoverflow.com/a/48609517
has comment: http://stackoverflow.com/comment/84203766
favorite count: 0

http://stackoverflow.com/q/48605245
has answer: http://stackoverflow.com/a/48605315
has comment: http://stackoverflow.com/comment/84206998
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84207004
has comment: http://stackoverflow.com/comment/84207036
type: Question
possible better answer: http://stackoverflow.com/a/62250051
has body: i saw this in https://leetcode.com/problems/merge-sorted-array/description/ and the answer in https://leetcode.com/problems/merge-sorted-array/discuss/29503/Beautiful-Python-Solution def merge(self, nums1, m, nums2, n): while m &gt; 0 and n &gt; 0: if nums1[m-1] &gt;= nums2[n-1]: nums1[m+n-1] = nums1[m-1] m -= 1 else: nums1[m+n-1] = nums2[n-1] n -= 1 if n &gt; 0: nums1[:n] = nums2[:n] I have two doubts: When i want to run the code print(Solution().merge([1, 2, 3], 3, [4, 5, 6], 3)) and it just gave me an error hint IndexError: list assignment index out of range. I don't quite understand the methodology in the answer above. Could someone tell me how to solve this kind of problem?
has title: Merge Sorted Array in leetcode
has answer: http://stackoverflow.com/a/62250051
tagged with: arrays
accepted answer: http://stackoverflow.com/a/48605315
has comment: http://stackoverflow.com/comment/84207085
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/78074917
has comment: http://stackoverflow.com/comment/84207041

http://stackoverflow.com/q/48601420
has title: What type of normalization happens with sklearn
has comment: http://stackoverflow.com/comment/84199473
has answer: http://stackoverflow.com/a/48601482
possible better answer: http://stackoverflow.com/a/48601482
answer count: 2
downvote count: 2
has body: I have a matrix which I'm trying to normalize by transforming each feature column to zero mean and unit standard deviation. I have the following code that I'm using, but I want to know if that method actually does what I'm trying to or if it uses a different method. from sklearn import preprocessing mat_normalized = preprocessing.normalize(mat_from_df)
has comment: http://stackoverflow.com/comment/84199448
has comment: http://stackoverflow.com/comment/84199469
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/48601493
type: Question
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/84199512
tagged with: pandas
score: 1
tagged with: normalize
has comment: http://stackoverflow.com/comment/84199465
tagged with: python
accepted answer: http://stackoverflow.com/a/48601493
favorite count: 0

http://stackoverflow.com/q/48572970
has answer: http://stackoverflow.com/a/48573686
possible better answer: http://stackoverflow.com/a/48573222
tagged with: dataframe
tagged with: python
has title: Dictionary into DataFrame
tagged with: dictionary
tagged with: jupyter
has answer: http://stackoverflow.com/a/48573222
linked to: http://stackoverflow.com/q/8957750
accepted answer: http://stackoverflow.com/a/48573031
has answer: http://stackoverflow.com/a/48573031
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84142770
has body: I am converting a dict into a dataframe: states = {'OH': 'Ohio', 'KY': 'Kentucky', 'AS': 'American Samoa', 'NV': 'Nevada', 'WY': 'Wyoming', 'NA': 'National', 'AL': 'Alabama', 'MD': 'Maryland', 'AK': 'Alaska', 'UT': 'Utah', 'OR': 'Oregon', 'MT': 'Montana', 'IL': 'Illinois', 'TN': 'Tennessee', 'DC': 'District of Columbia', 'VT': 'Vermont', 'ID': 'Idaho', 'AR': 'Arkansas', 'ME': 'Maine', 'WA': 'Washington', 'HI': 'Hawaii', 'WI': 'Wisconsin', 'MI': 'Michigan', 'IN': 'Indiana', 'NJ': 'New Jersey', 'AZ': 'Arizona', 'GU': 'Guam', 'MS': 'Mississippi', 'PR': 'Puerto Rico', 'NC': 'North Carolina', 'TX': 'Texas', 'SD': 'South Dakota', 'MP': 'Northern Mariana Islands', 'IA': 'Iowa', 'MO': 'Missouri', 'CT': 'Connecticut', 'WV': 'West Virginia', 'SC': 'South Carolina', 'LA': 'Louisiana', 'KS': 'Kansas', 'NY': 'New York', 'NE': 'Nebraska', 'OK': 'Oklahoma', 'FL': 'Florida', 'CA': 'California', 'CO': 'Colorado', 'PA': 'Pennsylvania', 'DE': 'Delaware', 'NM': 'New Mexico', 'RI': 'Rhode Island', 'MN': 'Minnesota', 'VI': 'Virgin Islands', 'NH': 'New Hampshire', 'MA': 'Massachusetts', 'GA': 'Georgia', 'ND': 'North Dakota', 'VA': 'Virginia'} myStates = pd.DataFrame(states.items(), columns=['a','b']) Jupyter Notebook throws following error: 13 ---&gt; 14 myStates = pd.DataFrame(states.items(), columns=['a','b']) PandasError: DataFrame constructor not properly called! But I am getting no error on PyCharm/Python2.7, output looks like: a b 0 WA Washington 1 WI Wisconsin 2 WV West Virginia 3 FL Florida 4 WY Wyoming 5 NH New Hampshire Any other workaround to that? Thanks, P
answer count: 3
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/84258513
type: AnswerComment
comment on: http://stackoverflow.com/a/48630733
has text: That's one problem. The other problem is that OP is printing `a` (the index variable) and not `x` (the string).
type: Comment
score: 0

http://stackoverflow.com/comment/84033753
type: Comment
comment on: http://stackoverflow.com/a/48519290
score: 0
type: AnswerComment
has text: It works the way you said but as I mentioned under GPhilo's answer, I wasn't supposed tot ouch that part of the code.

http://stackoverflow.com/q/48603066
downvote count: 0
tagged with: events
score: 1
has answer: http://stackoverflow.com/a/48603428
favorite count: 0
possible better answer: http://stackoverflow.com/a/48603139
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/48603139
has title: Doing tasks when a Tkinter application is closed
type: Question
answer count: 2
has body: When my Tkinter application ends it has to do some jobs (e. g. store some data to files). In some cases, the users should be asked if she/he really wants to close the application. There are multiple ways to close a Tkinter application: The X on the window A button An entry in the menubar How can I catch all this kind of "events"? #!/usr/bin/env python3 from tkinter import * def on_delete_window(): print('on_delete_window') print('save my data') if __name__ == '__main__': root = Tk() Button(root, text='Destroy', command=root.destroy).pack() Button(root, text='Quit', command=root.quit).pack() menu = Menu(root) menu.add_command(label='Destroy', command=root.destroy) menu.add_command(label='Quit', command=root.quit) root.config(menu=menu) # this catches ONLY the X in the window # but none of the two buttons! root.protocol('WM_DELETE_WINDOW', on_delete_window) root.mainloop()
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48603428

http://stackoverflow.com/q/48565703
type: Question
has comment: http://stackoverflow.com/comment/84143410
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84146741
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84147133
tagged with: python
has comment: http://stackoverflow.com/comment/84146436
has comment: http://stackoverflow.com/comment/84127613
has comment: http://stackoverflow.com/comment/84146421
has comment: http://stackoverflow.com/comment/84147118
has comment: http://stackoverflow.com/comment/84146251
score: 0
answer count: 0
tagged with: pyqt
has body: I am trying to make a simple GUI that has two main buttons. One of the buttons is running a scrapping function in a while loop and append some items into a list. The other button I want it to write a file from the list generated by the loop function without stopping the loop. It is more like posing the for-loop while the script is creating a text file. I am struggling figure out a way to make it work. The following error shows in self.save.clicked.connect(self.writer(self.links)) TypeError: argument 1 has unexpected type 'NoneType' Here is what I have done: from PyQt5 import QtCore, QtGui, QtWidgets from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import logging from selenium.webdriver.remote.remote_connection import LOGGER import time from sys import exit import random from bs4 import BeautifulSoup from PyQt5 import QtCore, QtGui, QtWidgets import os from sys import exit class Ui_window(object): def __init__(self): self.links = [] def writer(self, links): with open('{}_links.txt'.format(len(links)), "w+", newline = '') as file: file.write("\n".join(links)) def loop(self): LOGGER.setLevel(logging.WARNING) browser = webdriver.Chrome(executable_path=r"chromedriver.exe") while True #Dynamic page with infinite scroll browser.get('www.example.com/posts') WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH,'//*[@id="posts"]'))) for I in range(random.randint(3,12)): scroll = browser.execute_script("window.scrollTo(0, document.body.scrollHeight)") time.sleep(4) page = browser.page_source soup = BeautifulSoup(page, 'lxml') posts = soup.findAll('a', {'class':'user_post'}) for i in items: self.links.append(i) else: pass def setupUi(self, window): window.setObjectName("window") self.verticalLayout = QtWidgets.QVBoxLayout(window) self.verticalLayout.setObjectName("verticalLayout") self.start = QtWidgets.QPushButt…
has comment: http://stackoverflow.com/comment/84128176
tagged with: pyqt5
has title: PyQt5 pausing a while loop, operating a file writing function and resume it again
has comment: http://stackoverflow.com/comment/84143474
has comment: http://stackoverflow.com/comment/84145489

http://stackoverflow.com/a/48542539
has comment: http://stackoverflow.com/comment/84080691
answers question: http://stackoverflow.com/q/48542469
has comment: http://stackoverflow.com/comment/84081069
type: Answer
has body: The result of ax.scatter is a matplotlib.collections.PathCollection. Therefore there are many arguments you can use. One of them is set_sizes(): fig, ax = plt.subplots() a = list(range(20)) b = list(range(20, 40)) p = ax.scatter(a, b) p.set_sizes([10]) This also allows you to set different of sizes, so long as the list is the same length as the number of scatter points. p.set_sizes(range(20))
accepted answer of: http://stackoverflow.com/q/48542469
score: 0
has comment: http://stackoverflow.com/comment/84080252
has comment: http://stackoverflow.com/comment/84081236
has comment: http://stackoverflow.com/comment/84080141
type: AcceptedAnswer
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84080553
has comment: http://stackoverflow.com/comment/84080694
has comment: http://stackoverflow.com/comment/84080551

http://stackoverflow.com/q/48590311
tagged with: loops
has answer: http://stackoverflow.com/a/48590438
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48590346
possible better answer: http://stackoverflow.com/a/48590346
tagged with: for-loop
has title: How can you print a variable in quotation marks?
tagged with: python
has body: favoriteword = input('Enter your word: ') print('What is your favorite word?',favoriteword) print(favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword) print(favoriteword, 'does not even sound like a word anymore.') How can I make it so that in line 4 it comes out as "___" does not even sound like a word anymore." If I put it as this below it doesn't work. print('"favoriteword"', 'does not even sound like a word anymore.') Also if I put line 2 into a loop how would I print it so that it prints on a single line? for i in range(12): print(favoriteword)
downvote count: 1
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 3
has answer: http://stackoverflow.com/a/48590341
accepted answer: http://stackoverflow.com/a/48590341

http://stackoverflow.com/q/48567621
has title: Using Shopify API Python, add new product with price and 'requires_shipping': False
tagged with: api
has answer: http://stackoverflow.com/a/48568334
downvote count: 0
tagged with: shopify
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 1
tagged with: variants
has body: I am trying to add a new product through the Python Shopify API. I know how to add title and body and a picture but I am having issues with adding price and I need to have 'requires_shipping': False. I can't find anywhere how to achieve this. This is what I have so far. import shopify API_KEY = 'dsfsdsdsdsdsad' PASSWORD = 'sadsdasdasdas' shop_url = "https://%s:%s@teststore.myshopify.com/admin" % (API_KEY, PASSWORD) shopify.ShopifyResource.set_site(shop_url) path = "audi.jpg" new_product = shopify.Product() new_product.title = "Audi pictures test " new_product.body_html = "body of the page &lt;br/&gt;&lt;br/&gt; test &lt;br/&gt; test" ###########this part is so far good. but the bottom part is not working#### variant = shopify.Variant(price=9.99)) # this does not work new_product.variant() # this does not work variant_2 = shopify.Variant(requires_shipping=False) #this does not work new_product.variant_2() This does not work image = shopify.Image() with open(path, "rb") as f: filename = path.split("/")[-1:][0] encoded = f.read() image.attach_image(encoded, filename=filename) new_product.images = [image] # Here's the change new_product.save()
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/84018233
type: QuestionComment
has text: @dukebody Yes i have tried old string interpolation, it isn't working either
score: 0
comment on: http://stackoverflow.com/q/48508711
type: Comment

http://stackoverflow.com/q/48537626
downvote count: 3
has answer: http://stackoverflow.com/a/51124905
has comment: http://stackoverflow.com/comment/84075116
has body: I do have 2 classes like these => class User(db.Model): __tablename__ = "user" user_id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(32), unique=True, nullable=False) password = db.Column(db.String(77), unique=False, nullable=False) server_limit = db.Column(db.Integer, unique=False, nullable=False, server_default="4") servers = db.relationship('Server', backref='owner', lazy='dynamic') class Server(db.Model): __tablename__ = "server" server_id = db.Column(db.Integer, primary_key=True) server_admin = db.Column(db.Integer, db.ForeignKey("user.user_id")) server_port = db.Column(db.Integer, unique=False, nullable=False) server_slot = db.Column(db.Integer, unique=False, nullable=False, server_default="32") Now Im trying to get sum of server_slot column where for example user_id is 1. I know there is questions with accepted answer about this but the difference is Im trying to do it with servers ( db.relationship ) that I assigned in my User class. I did it with an alternative method that I created for User class => def used(self): return db.session.execute("SELECT SUM(server.server_slot) FROM server WHERE server_admin={}".format(self.user_id)).scalar() How can I do it using db.session.query() ? Im looking for something that I can get it from db.session.query(User).all() I dont want to use db.session.query(db.func.sum(Server.server_slot)).filter_by(server_admin=self.user_id).scalar() Cause Im passing a list to my Flask page, The list is made by db.session.query(User).all() so I can iterate over it using a for loop inside my Jinja2 Template and show each user information in a list like this => {% for user in users %} user.username user.server_limit ... user.used_slots() {% endfor %} I can use user.servers.value("server_slot") but it returns only first server's server_slot, I also tried to iterate over user.servers.all() so I could sum their server_slot inside a nested loop, but I can't assign variables any value inside of a loop and get it outside…
has comment: http://stackoverflow.com/comment/84144190
has comment: http://stackoverflow.com/comment/90160866
has answer: http://stackoverflow.com/a/48584114
linked to: http://stackoverflow.com/q/41152973
has comment: http://stackoverflow.com/comment/84158993
possible better answer: http://stackoverflow.com/a/48584114
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84141410
has comment: http://stackoverflow.com/comment/84146125
upvote count: 5
linked to: http://stackoverflow.com/q/21271382
accepted answer: http://stackoverflow.com/a/51124905
has comment: http://stackoverflow.com/comment/84074250
tagged with: python
tagged with: flask
type: AnsweredQuestion
score: 2
has title: Flask-SQLAlchemy Sum of a Column of a Relationship
has comment: http://stackoverflow.com/comment/90160865
answer count: 2
has comment: http://stackoverflow.com/comment/90160864

http://stackoverflow.com/a/48599902
has comment: http://stackoverflow.com/comment/84196414
accepted answer of: http://stackoverflow.com/q/48599880
type: Answer
score: 4
upvote count: 4
has body: Do you have __init__.py in the same directory as AsyncDownloader.py? That should do it. __init__.py is an empty file that signals that the directory contains packages and makes functions and classes importable from .py files in that directory. You can probably lose the leading . in from .AsyncDownloader as well. If you like, you can make the import absolute by changing it to: from enclosing_folder.AsyncDownloader import AsyncDownloader
has comment: http://stackoverflow.com/comment/84196631
downvote count: 0
has comment: http://stackoverflow.com/comment/84196646
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48599880

http://stackoverflow.com/comment/84231291
has text: You are sure your application is working correctly? And can you post the nginx logs?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48616403
type: QuestionComment

http://stackoverflow.com/comment/84083852
has text: In my understanding of __init__.py in modules, it generates variables that are then made available to the scripts in the same module as the __init__.py. Am I wrong ? If yes how should I proceed ?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48544310

http://stackoverflow.com/q/48562763
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48563087
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/84121098
has title: Finding mean of those values in column B who reside in rows having one of the K largest elements in Column A: Pandas Dataframe GroupBy Object
has answer: http://stackoverflow.com/a/48563087
type: AnsweredQuestion
has body: I have a panda dataframe, call it df1, with many columns (col1, col2, ...) I want to group the data on two particular columns - say col4 and col7 In each group, I want to find the top K values in col9. Then, I want to find the mean of values in col10, which satisfy the condition of having the top K values in col9. I attempted to solve it as shown below: consideredCols = ['col4', 'col7'] k_value = 3 grp_data = df1.groupby(consideredCols) print(grp_data.apply(lambda grp: (grp.col9.nlargest(k_value)).mean('col10'))) Example: (showing after the groupby ['col4', 'col7'] phase) col9 col10 col4 col7 john doe 5 12 4 15 11 9 4 14 jane doe 42 421 50 42 124 27 15 25 if K=2 here, then I want the result as (12+9)/2 for John and (42+27)/2 for Jane.
tagged with: pandas-groupby

http://stackoverflow.com/comment/84050287
comment on: http://stackoverflow.com/a/48527665
has text: What do you mean? Why do you need to know them?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84087034
type: AnswerComment
has text: No, why would it have anything to do with migrations? The error now tells you that it is expecting a `file_upload` field, but you are only providing a field with the name `file`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48544515

http://stackoverflow.com/comment/84050813
comment on: http://stackoverflow.com/q/48527875
score: 0
type: Comment
type: QuestionComment
has text: You can use a csv file. Look up the documentation [here](https://docs.python.org/2/library/csv.html). Using `import csv`, you can fetch the data from the csv file into arrays which can be passed into your class.

http://stackoverflow.com/q/48622326
downvote count: 1
linked to: http://stackoverflow.com/q/5478351
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: -1
has title: python programming time occurrence detection
has answer: http://stackoverflow.com/a/48622910
upvote count: 0
tagged with: sqlite
answer count: 1
has body: I am doing gender and emotion classification using python programming and I want to save results in sqlite databases...A piece of code is following: text2 = emotion_mode + " " + gender_mode tstmp = datetime.datetime.now().strftime("%S") date = str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S')) fps.update() fps.stop() t = fps.elapsed() if text2 == last_row1: continue else: last_row1 = text2 c.execute("INSERT INTO users (gender,emotion,time,start,end) VALUES (?,?,?,?,?)" ,(gender_mode,emotion_mode,date,t,t1)) conn.commit() bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR) cv2.imshow('window_frame', bgr_image) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break emotion_mode and gender_mode is for example (angry man and etc...) I want to get t and t1 :t=time that start angry man and t1:time that end angry man and so on...

http://stackoverflow.com/comment/83991899
comment on: http://stackoverflow.com/q/48499207
type: QuestionComment
has text: 1. You loop twice over the items in your name list (more accurately: squared). 2. You forget to add up tally's.
type: Comment
score: 1

http://stackoverflow.com/comment/84241325
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48622434
score: 1
has text: Thanks for your help. I just tested your code, its not working either. Edit: It's working perfectly fine.

http://stackoverflow.com/comment/84185529
score: 0
has text: I have a data frame with 6 columns , I want to copy from the 3rd column to the second
type: Comment
comment on: http://stackoverflow.com/a/48594100
type: AnswerComment

http://stackoverflow.com/q/48516215
tagged with: python
tagged with: pygame
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/48517213
answer count: 2
has title: Pygame how to change image layer using LayeredUpdates()
downvote count: 0
tagged with: sprite
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48516552
linked to: http://stackoverflow.com/q/44580764
type: UnansweredQuestion
has body: I'm having trouble figuring out how to change the layers of images. What I try to achieve is moving a player around the screen and when it comes across an object, box, stone, etc., the player appears on top of the object when its bottom coord is bigger than the object and behind when the coord is smaller than the object. Instead it's always in front or behind the object. I've searched online and couldn't quite get what I want and I had found a post on Stack Overflow which demonstrated the usage of pygame.sprite.LayeredUpdates(). It explained the idea but I still can't figure out how to change the image layer while running the program. A simple code demonstration would be nice.

http://stackoverflow.com/a/49032887
upvote count: 53
downvote count: 0
answers question: http://stackoverflow.com/q/48541040
type: AcceptedAnswer
score: 53
has body: maybe it can save the picture independently from google.colab import files plt.savefig("abc.png") files.download("abc.png") https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/io.ipynb&amp;scrollTo=p2E4EKhCWEC5
type: Answer
accepted answer of: http://stackoverflow.com/q/48541040

http://stackoverflow.com/a/48498364
answers question: http://stackoverflow.com/q/48496552
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48496552
has comment: http://stackoverflow.com/comment/83998431
has comment: http://stackoverflow.com/comment/83998245
score: 3
type: Answer
has body: TL;DR: Read the third point in the list below. Long-ish generic explanation of how to restore a model Whenever you need to load weights from a checkpoint, you need the matching model definition to be able to define the graph before attempting to restore the weights. This is necessary because the checkpoint file only contains the values of the variables, it does NOT have information about the structure of the graph itself. The model structure can be retrieved in different ways: The checkpoint comes with a matching .meta file. In this case, import the metagraph and then restore the weights via: new_saver = tf.train.import_meta_graph('my-save-dir/my-model-10000.meta') new_saver.restore(sess, 'my-save-dir/my-model-10000') The checkpoint comes with a matching .pb/.pbtxt file containing the serialized GraphDef. In this case, load the graph from its definition and then restore the weights: For .pbtxt: with open('graph.pbtxt', 'r') as f: graph_def = tf.GraphDef() file_content = f.read() text_format.Merge(file_content, graph_def) tf.import_graph_def(graph_def, name='') saver = tf.train.Saver() # note: it is important that this is defined AFTER you import the graph definition or it won't find any variables in the graph to restore saver.restore(sess, "/tmp/model.ckpt") For .pb: with gfile.FastGFile('graph.pb','rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') saver = tf.train.Saver() # note: it is important that this is defined AFTER you import the graph definition or it won't find any variables in the graph to restore saver.restore(sess, "/tmp/model.ckpt") The checkpoint comes with a matching python file containing the model definition. In this case, read through the documentation of the file and find the function that you need to call to define the model. Then, in your script, import the function, call it before defining a saver and then restore the variables' values from the checkpoint: from inception_v3 import …
upvote count: 3

http://stackoverflow.com/comment/84168131
has text: example: for dx=0.1 and R=1 and we start with 0.1 this is what I am trying to do: start with x=[0.1, 0.1, 0.1] (after the first loop) x=[0.9, 0.1, 0.1] And then [0.1, 0.2, 0.1] And so on until [0.9, 0.9, 0.1] After we will get [0.1,0.1,0.2] And we will start again with [0.2, 0.1, 0.2] and so on
type: QuestionComment
comment on: http://stackoverflow.com/q/48585532
score: 0
type: Comment

http://stackoverflow.com/comment/84158351
comment on: http://stackoverflow.com/q/48580669
type: Comment
has text: @Rawing I am using pydev and running by 'run as python unit test'
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84262705
type: Comment
comment on: http://stackoverflow.com/q/48632765
type: QuestionComment
has text: `2007` and `2008` etc aren't valid names for variables.
score: 6

http://stackoverflow.com/q/48629259
linked to: http://stackoverflow.com/q/492519
tagged with: python
score: 0
duplicate of: http://stackoverflow.com/q/492519
has comment: http://stackoverflow.com/comment/84257147
has title: python input() wait for some time and if no input is given follow default
has comment: http://stackoverflow.com/comment/84255402
has body: I want to make a script in python 3(preferably) in which I get an "input()" from the user, but the user may or may not give the input. So it should wait for some fixed time and if no input is given in that time follow default condition already set. I have no idea, if there are any keywords I should search for.
type: Question
linked to: http://stackoverflow.com/q/45130837
answer count: 0
has comment: http://stackoverflow.com/comment/84255549
type: UnansweredQuestion

http://stackoverflow.com/comment/96522832
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48542686
has text: @ParthSharma What does `googlecode` have to do with the `googlemaps` module?

http://stackoverflow.com/a/48510493
has comment: http://stackoverflow.com/comment/84016002
score: 1
has comment: http://stackoverflow.com/comment/84016439
type: Answer
has comment: http://stackoverflow.com/comment/84016033
has comment: http://stackoverflow.com/comment/84017137
has comment: http://stackoverflow.com/comment/84016169
has comment: http://stackoverflow.com/comment/84018763
has body: In the same directory of flask_home.py, enter python shell and try to import from python.libs import login to see if you have syntax error in your login.py file. Make sure you didn't forget to put __init__.py files in python/ and python/libs/ folders.
answers question: http://stackoverflow.com/q/48510404
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84282506
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48642919
score: 0
has text: I converted row.split to str(row).split and rest of remains the same and it appears to be working.

http://stackoverflow.com/comment/84014992
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48508782
has text: Please share Model code also social auth code how you process after successful social login.

http://stackoverflow.com/a/48516936
type: Answer
score: 0
has body: In your function create_custom_permission you try to create a ContentType with name in the args and no model. Content type has no field name, name is a function returning the verbose name of the linked model. I don't know what you're tying to do but you're using the wrong tool.
answers question: http://stackoverflow.com/q/48516612

http://stackoverflow.com/a/69626386
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48509732
has body: A little late over here, but is anaconda installed in the instance. If so please try conda activate tensorflow_p36

http://stackoverflow.com/comment/84262092
has text: A tilted plane would be the best.
comment on: http://stackoverflow.com/q/48630246
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84101492
comment on: http://stackoverflow.com/q/48551633
score: 0
has text: I updated my question, hopefully it helps. thanks for the suggestion.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84017956
comment on: http://stackoverflow.com/a/48508982
type: Comment
score: 0
type: AnswerComment
has text: @user3910919 yw :-) happy coding

http://stackoverflow.com/a/55051166
has body: Clone the repository and install explicitly using below command. Worked for me. python setup.py install sometimes pip install nlgserv throws the above error.
answers question: http://stackoverflow.com/q/48595728
type: Answer
score: 0

http://stackoverflow.com/comment/84374744
type: Comment
type: QuestionComment
has text: What happens if you run this, eg. from a REPL prompt? `list(sorted(glob.glob('path_to_gmls'), key=os.path.getsize))`
score: 0
comment on: http://stackoverflow.com/q/48526468

http://stackoverflow.com/a/48637149
type: Answer
has comment: http://stackoverflow.com/comment/84271040
has body: You are assigning value to variable 'answer' inside the if statement so its scope is limited to those if statements, simply initialize your variable answer before if statement.
has comment: http://stackoverflow.com/comment/84312127
score: 0
answers question: http://stackoverflow.com/q/48637047

http://stackoverflow.com/comment/84224690
score: 6
has text: Possible duplicate of [Python MySQLdb placeholders syntax](https://stackoverflow.com/questions/2527941/python-mysqldb-placeholders-syntax)
comment on: http://stackoverflow.com/q/48613887
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84140054
has text: I don't see any indication that the OP wanted log base 10 rather than natural log, so your use of `math.log(x, 10)` seem unjustified.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48568869
score: 0

http://stackoverflow.com/q/48598829
has comment: http://stackoverflow.com/comment/84194913
has comment: http://stackoverflow.com/comment/84194602
has comment: http://stackoverflow.com/comment/84195765
linked to: http://stackoverflow.com/q/30706919
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84195378
tagged with: colormap
has title: How to convert a spectrogram to 3d plot. Python
score: 8
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/84194828
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84195482
has answer: http://stackoverflow.com/a/66649311
tagged with: python
has comment: http://stackoverflow.com/comment/84196868
type: UnansweredQuestion
tagged with: wav
has comment: http://stackoverflow.com/comment/84195550
has body: I am trying to achieve waterfall graph of wav file. In my attempts I noticed that this is basically a spectogram in 3d (or as close to what I need). I am trying to do this in Python with numpy and matplotlib. My main problem is I don't know how to change the plot of specgram from matplotlib into a 3d plot. Sample of my "code": sample ,data = wavfile.read('file.wav') F = Figure() a = F.add_subplot(111,projection='3d') Spec, t, freq, im = a.specgram(data,Fs=2) I've got this far and have no clue what to do next. I wanna change already existing plot into 3d. I have no code of changing it to 3d, due to lack of my knowledge. Is it possible to convert 2d plot to 3d ? If so how ? Am i better off constructing a new plot with data from specgram? The desired outcome would be something like the following: Thanks for any replies.

http://stackoverflow.com/comment/125282977
score: 0
comment on: http://stackoverflow.com/a/70856641
type: Comment
has text: I don't know how to use, can you explain me please?
type: AnswerComment

http://stackoverflow.com/q/48580248
downvote count: 0
has body: I have a celery app consuming from large amount of queues with gevent concurrency. For each queue I need to have some guaranteed number of workers, but the number is different for each queue. For example: qA must have 10 qB must have 25 qN must have M etc. I'd like to avoid to start dedicated celeryd for each queue due to the large total amount of queues. Workers do a lot of IO and I use -P gevent so don't care how many subworkers celeryd starts. Is there a way to configure a single celeryd instance to assign some specific number of workers to different queues?
answer count: 1
has answer: http://stackoverflow.com/a/48747906
tagged with: gevent
accepted answer: http://stackoverflow.com/a/48747906
tagged with: celeryd
tagged with: celery
favorite count: 0
type: Question
has title: Celery: how to assign some specific number of workers to different queues?
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: celery-task

http://stackoverflow.com/comment/84276325
comment on: http://stackoverflow.com/a/48637957
type: Comment
has text: `[:, 1]` returns the second lowest value.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48575815
has body: I am trying to simulate a systolic array structure -- all of which I learned from these slides: http://web.cecs.pdx.edu/~mperkows/temp/May22/0020.Matrix-multiplication-systolic.pdf -- for matrix multiplication in a Python environment. An integral part of a systolic array is that data flow between PE's is concurrent with any multiplication or addition that occurs on any one node. I am having difficulty surmising how exactly to implement such a concurrent procedure in Python. Specifically, I hope to better understand a computational approach to feed the elements of the matrices to be multiplied into the systolic array in a cascading fashion, while allowing these elements to propagate through the array in a concurrent fashion. I have begun writing some code in python to multiple two 3 by 3 array's, but ultimately, I want to simulate any sized systolic array to work with any sized a and b matrices. from threading import Thread from collections import deque vals_deque = deque(maxlen=9*2)#will hold the interconnections between nodes of the systolicarray dump=deque(maxlen=9) # will be the output of the SystolicArray prev_size = 0 def setupSystolicArray(): global SystolicArray SystolicArray = [NodeSystolic(i,j) for i in range(3), for i in range(3)] def spreadInputs(a,b): #needs some way to initially propagate the elements of a and b through the top and leftmost parts of the systolic array new = map(lambda x: x.start() , SystolicArray) #start all the nodes of the systolic array, they are waiting for an input #even if i found a way to put these inputs into the array at the start, I am not sure how to coordinate future inputs into the array in the cascading fashion described in the slides while(len(dump) != 9): if(len(vals_deque) != prev_size): vals = vals_deque[-1] row = vals['t'][0] col = vals['l'][0] a= vals['t'][1] b = vals['l'][1] # these if elif statements track whether the outputs are at the edge of the systolic array and can be removed if(row &gt;= 3): dump.append(a) e…
tagged with: signal-processing
type: Question
accepted answer: http://stackoverflow.com/a/48595438
upvote count: 1
tagged with: multithreading
answer count: 1
downvote count: 0
favorite count: 0
tagged with: vlsi
has answer: http://stackoverflow.com/a/48595438
type: AnsweredQuestion
has title: Systolic Array Simulation in Python
score: 1
tagged with: python
tagged with: simulation

http://stackoverflow.com/comment/84100247
comment on: http://stackoverflow.com/a/48551926
score: 0
type: Comment
has text: I'm getting the following error: AttributeError: module 'git' has no attribute 'clone_from'. I think it's because clone_from is a part of the repo class in the library.
type: AnswerComment

http://stackoverflow.com/q/48610824
favorite count: 0
tagged with: parsing
type: Question
has body: I want to parse a log4j configuration in order to know how to parse a given log. Requirements: python 2.6+, no custom c modules (unless absolutely required). For example: %d{yyyy-MM-dd HH:mm:ss.SSS} %-5p{length=5} [%t] %c:%L %message%n or %d{ISO8601} %-5p{length=5} ((%t) %c:%L) %message%n As a reference, the pattern layout is described here: Pattern Layouts for log4j Initially, I was going to customize it for each log pattern, as an example using re: log1 = re.compile(r'([\d-]{10}) ([\d:.]{12}) {1}([A-Z]{0,}) \[(catalina-exec-[0-9]{2})\]{0,} (.*)\n') Note: I realize that this is not a very comprehensive use of re, nor is it an optimized regular expression. It was testing only. I initially started using parsimonious like so (very early stage): from parsimonious.grammar import Grammar grammar = Grammar( r""" category = "%c" category_precise = category optional_open number optional_close timedate = '%d' timedate_absolute = timedate optional_open timedate_abstext optional_close timedate_iso = timedate optional_open timedate_isotext optional_close timedate_date = timedate optional_open timedate_date optional_close timedate_era = "G" timedate_year_two_digit = ~"y{2}" timedate_year_number = ~"(?:y{1}|y{3,}" timedate_month = "MM" timedate_minute = "mm" """ Effectively, I am wondering if I am going about it the wrong way? It almost seems like I am using a PEG parser in the wrong way, in fact the more I look at it, I think I am. I don't need full code, just a good concept, a start, an idea, or a good place to start reading. In the end, I want to be able to review a log format, and for lack of better words "convert the log4j2 pattern into a regular expression" Any help would be appreciated
has answer: http://stackoverflow.com/a/48611468
has comment: http://stackoverflow.com/comment/84254815
has comment: http://stackoverflow.com/comment/84241913
type: UnansweredQuestion
tagged with: python
tagged with: logging
downvote count: 0
score: 1
upvote count: 1
has title: Python parse configuration tokens from log4j in order to parse logs
answer count: 1
tagged with: log4j

http://stackoverflow.com/a/48535270
downvote count: 2
answers question: http://stackoverflow.com/q/48535236
type: Answer
score: -2
upvote count: 0
has body: Please try mentioning master as "local[*]" instead of just "local".

hadoop
tags question: http://stackoverflow.com/q/48574997
tags question: http://stackoverflow.com/q/48560572
tags question: http://stackoverflow.com/q/48535980
tags question: http://stackoverflow.com/q/48643406
tags question: http://stackoverflow.com/q/48634272
tag name: hadoop
tags question: http://stackoverflow.com/q/48610405
tags question: http://stackoverflow.com/q/48518125
tags question: http://stackoverflow.com/q/48640679
type: Tag
tags question: http://stackoverflow.com/q/48640978
tags question: http://stackoverflow.com/q/48513900

http://stackoverflow.com/q/48605270
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48605534
tagged with: django
score: 1
upvote count: 1
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/48605534
favorite count: 0
tagged with: serialization
accepted answer: http://stackoverflow.com/a/48636898
type: Question
has body: Hello guys i'm back again i have a little trouble about my problem. I want to create Account in my Django Project. I extend user model using OneToOneField. here is my mode.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=15, unique=True, null=False, blank=False) birth_date = models.DateField() address = models.TextField() district = models.ForeignKey(District, on_delete=models.CASCADE, related_name='district') created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_at', ] def __str__(self): return self.user.username and here is my serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='account.id', read_only=True) phone_number = serializers.CharField(source='account.phone_number') birth_date = serializers.DateField(source='account.birth_date') address = serializers.CharField(source='account.address') class Meta: model = User fields = ( 'id', 'first_name', 'last_name', 'username', 'email', 'password', 'phone_number', 'birth_date', 'address' ) def update_or_create_account(self, user, account_data): Account.objects.update_or_create(user=user, defaults=account_data) def create(self, validated_data): account_data = validated_data.pop('account', None) user = super(UserSerializer, self).create(validated_data) self.update_or_create_account(user, account_data) return user def update(self, instance, validated_data): account_data = validated_data.pop('account', None) self.update_or_create_account(instance, account_data) user = super(UserSerializer, self).update(instance, validated_data) return user class AccountSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) created_at = serializers.DateTimeField(read_only=True) class Meta: model = Account fields = ( 'user', 'district', 'created_at' ) and here for views.py class AccountList(APIView): def get(self, format=None): account = Account.objects…
has answer: http://stackoverflow.com/a/48636898
tagged with: python
has title: Create Account, nested serialization Django Rest Framework
tagged with: post
type: AnsweredQuestion

http://stackoverflow.com/q/48530658
tagged with: pandas
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48530871
type: Question
has body: I have a dataframe like below: data = {'name': {0: 'mypath\\is\this', 1: 'mynewpath\\is\this'}, 'vals': {0: [{'name1': 'val1'}, {'name2': 'val2'}, {'name3': 'val3'}], 1: [{'name1': 'val1'}, {'name2': 'val2'}, {'name3': 'val3'}]}} df = pd.DataFrame(data) name vals mypath\is\this [{name1:val1},{name2:val2},{name3:val3}] mynewpath\is\this [{name1:val1},{name2:val2},{name3:val3}] How can i expand the values column and map the key to the create a new name keeping the value associated to it appropriately. Expected output like below: name vals mypath\is\this\name1 val1 mypath\is\this\name2 val2 mypath\is\this\name3 val3 mynewpath\is\this\name1 val1 mynewpath\is\this\name2 val2 mynewpath\is\this\name3 val3
has title: List of dictionaires in series mapped to pandas dataframe
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/48531179
score: 0
has answer: http://stackoverflow.com/a/48531137
answer count: 3

http://stackoverflow.com/comment/84222756
type: QuestionComment
comment on: http://stackoverflow.com/q/48613042
has text: Have you tried `app.exec_()` or `app.exec()`? I can't see a reason why the former wouldn't work.
score: 0
type: Comment

http://stackoverflow.com/comment/84204987
comment on: http://stackoverflow.com/q/48604015
type: Comment
score: 0
has text: In pycharm, your code is right. NO Error@Roxy
type: QuestionComment

http://stackoverflow.com/comment/84139935
comment on: http://stackoverflow.com/q/48571555
has text: @TemporalWolf When Davide submits that as an answer to their instructor, they won't get a good grade. What I put in the comment is clearly not what their instructor wanted. My answer aligns with your point.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84184571
has text: @ChristianDean I need to get the two files my program runs for though but I'm not sure what I did wrong. I even ran it with no arguments and still get an error.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48593656

http://stackoverflow.com/a/48500619
upvote count: 5
type: Answer
has body: This should work: import pandas as pd df = pd.DataFrame({'Col1' : pd.Series(['Abc','Cde','Efg','Abc'], index=['a', 'b', 'c','d']), 'Col2' : pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']), 'Col3' : pd.Series([1, 2., 3., 4.], index=['a', 'b', 'c', 'd'])}) df.loc[df['Col1'] == 'Abc', 'Col3'] = df['Col2']
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48500534
downvote count: 0
score: 5
answers question: http://stackoverflow.com/q/48500534

http://stackoverflow.com/q/48527336
has answer: http://stackoverflow.com/a/48587204
has comment: http://stackoverflow.com/comment/84049850
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84059621
type: Question
has title: Impossible to upload pdf on Gdrive subfolders with Python using service account
has comment: http://stackoverflow.com/comment/84087514
score: 0
has comment: http://stackoverflow.com/comment/84059723
has comment: http://stackoverflow.com/comment/84087789
has body: I created a flask project which stores a pdf on google drive. The user simpliy drags a pdf over a DIV, and flask uploads the file to Drive using a service account. The upload works fine, but the file uploads in the root folder and not in subfolders. The service account creates a delegate object to enter in gdrive, with the credentials of the owner of files and folders, but it is impossible to upload a file into any subfolder, and it is impossible to read the contents of the folders too. Does service accounts require any particular permissions to read and write into subfolders? Regards, Fabio def gauth(id_dipartimento): d={} json_url = os.environ['SERVICE-ACCOUNT.json'] scopes = ['https://www.googleapis.com/auth/drive.file'] credentials = erviceAccountCredentials.from_json_keyfile_name(json_url, scopes=scopes) ## The service account creates ua delegated object with current user credentals delegated_credentials = credentials.create_delegated(&lt;CURRENT_USER&gt;) http_auth = delegated_credentials.authorize(httplib2.Http()) return http_auth def upload_file(): http_auth = gauth() drive_service = discovery.build('drive', 'v3', http=http_auth) folder_id = &lt;folder_id_here&gt; body = { 'name': filename, 'mimeType': mime_type, 'useDomainAdminAccess':True, 'parents':folder_id } media = MediaFileUpload(filepath, mimetype=mime_type, resumable=True) file = drive_service.files().create(body=body, media_body=media, fields='id,originalFilename').execute() new_permission = { 'type': "anyone", 'role': "reader", } try: drive_service.permissions().create(fileId=file["id"], body=new_permission).execute() except errors.HttpError, error: print 'An error occurred: %s' % error
tagged with: python
has comment: http://stackoverflow.com/comment/84074124
has comment: http://stackoverflow.com/comment/84077433
has answer: http://stackoverflow.com/a/48596738
tagged with: google-drive-api
answer count: 2

http://stackoverflow.com/q/48605547
has comment: http://stackoverflow.com/comment/84207428
tagged with: python
has comment: http://stackoverflow.com/comment/84208684
has answer: http://stackoverflow.com/a/48605838
has title: how can I deal with the garbled string like '\xe7\xbe\x8e'?
has comment: http://stackoverflow.com/comment/84207732
has body: I have a list of words like s = ['a','\xe7\xbe\x8e\xe7','b'], and I want to remove the members like '\xe7\xbe\x8e\xe7', but I cannot think of any useful method. I have never deal with such kind of encoded or decoded words. I wish any suggestion in python. Thanks!
upvote count: 2
has comment: http://stackoverflow.com/comment/84208525
type: AnsweredQuestion
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/48605691
downvote count: 1
tagged with: string
tagged with: unicode
possible better answer: http://stackoverflow.com/a/48605838
has comment: http://stackoverflow.com/comment/84209752
favorite count: 0
has answer: http://stackoverflow.com/a/48605584
accepted answer: http://stackoverflow.com/a/48605584
type: Question

http://stackoverflow.com/comment/84324968
type: QuestionComment
comment on: http://stackoverflow.com/q/48613466
type: Comment
has text: Thanks so much @PatrickHaugh. I''ll have a look at the documents.
score: 0

http://stackoverflow.com/a/48529646
score: 0
answers question: http://stackoverflow.com/q/48529567
type: Answer
has body: The easiest way to work around this is to make the outer while alterable by using a boolean variable, and toggling it: loop = True while loop: for x in y: if exit_condition: loop = False break That way you can stop the outer loop from within an inner one.

http://stackoverflow.com/q/48551028
tagged with: python
has body: When using the python TA-Lib library with large arrays (length 2000) I am finding a TA-Lib function (for example BBands) only produces results up til index 1100 then the rest of the result is NaN's. So for a array of 2000 passed to BBands the final 900 values are NaN's. I am finding this result consistent across all functions I have tried. Is anyone else experiencing this issue?
has comment: http://stackoverflow.com/comment/116871307
tagged with: ta-lib
answer count: 0
tagged with: pandas
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: TA-Lib producing NaN's for large inputs (length 1100+)
type: UnansweredQuestion
score: 1

http://stackoverflow.com/a/48573346
score: 0
has body: It sounds like the OP's problem is having something like: def f(i): if i == 1: return "a string" Then wants to do something like: a = '' for i in range(5): a += f(i) This will throw an exception when i &gt; 1, because in that case f(i) returns None which cannot be concatenated with the previous value of a, which was "a string". There are several ways to deal with this: 1. Check the type of the return of f() before concatenation: (LBYL) a = '' for i in range(5): temp = f(i) a = a if temp is None else a + temp # this will skip the concatenation if temp is None 2. Catch the TypeError exception: (EAFP) a = '' for i in range(5): try: a += f(i) except TypeError: continue 3. change the thing that is creating the None value: (wisdom) def f(i): if i == 1: return "a string" return ""
has comment: http://stackoverflow.com/comment/84179115
answers question: http://stackoverflow.com/q/48571774
type: Answer

http://stackoverflow.com/q/48600481
upvote count: 7
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48600555
has title: Remove double quotes enclosing numbers using regex
has answer: http://stackoverflow.com/a/48600555
tagged with: python
tagged with: regex
has body: I'm working with the following string: '"name": "Gnosis", \n "symbol": "GNO", \n "rank": "99", \n "price_usd": "175.029", \n "price_btc": "0.0186887", \n "24h_volume_usd": "753877.0"' and I have to use re.sub() in python to replace only the double quotes (") that are enclosing the numbers, in order to parse it later in JSON. I've tried with some regular expressions, but without success. Here is my best attempt: exp = re.compile(r': (")\D+\.*\D*(")', re.MULTILINE) response = re.sub(exp, "", string) I've searched a lot for a similar problem, but have not found another similar question. EDIT: Finally I've used (thanks to S. Kablar): fomatted = re.sub(r'"(-*\d+(?:\.\d+)?)"', r"\1", string) parsed = json.loads(formatted) The problem is that this endpoint returns a bad formatted string as JSON. Other users answered "Parse the string first with json, and later convert numbers to float" with a for loop and, I think, is a very inneficient way to do it, also, you will be forced to select between int or float type for your response. To get out of doubt, I've wrote this gist where I show you the comparations between the different approachs with benchmarking, and for now I'm going to trust in regex in this case. Thanks everyone for your help
has comment: http://stackoverflow.com/comment/84202667
linked to: http://stackoverflow.com/q/10756427
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/84197734
accepted answer: http://stackoverflow.com/a/48600613
score: 6
has answer: http://stackoverflow.com/a/48600616
has answer: http://stackoverflow.com/a/48600613

http://stackoverflow.com/q/48545467
tagged with: linux
has title: How to setup virtual environment for python(2.7, 3.5, 3.6) on Ubuntu16.04 LTS?
type: Question
has comment: http://stackoverflow.com/comment/84123482
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48550144
tagged with: ubuntu
upvote count: 6
score: 6
has answer: http://stackoverflow.com/a/48550235
has body: I've read a lot of blog post about this and I'm still confused as to what is "best" way to set it up. Most of the blog posts I've read are out-dated. I'm new to Linux and have messed up my system twice now and still can't setup the virtual environments properly. According to what I've read, Virtualenv and Virtualenvwrapper combination is the most widely used setup. So, After a fresh Ubuntu 16.04 LTS install, I do the following: Install Python 3.6 as shown in the following link. https://tecadmin.net/install-python-3-6-ubuntu-linuxmint/ The current state of the system now is, $ python3.6 -V Python 3.6.4 $ pip3.6 -V pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6) pip3 (python3.5) and pip(python2.7) do not come pre-installed. To install them , I do: $ sudo apt-get install python-pip $ sudo apt-get install python3-pip $ which pip /usr/bin/pip $ which pip3 /usr/bin/pip3 Now, the pip-version installed through apt-get method is old(version 8.1.1). We need to update it to (version 9.0.1). This is where it all goes wrong. Question 1: How do I update the two different pip versions without breaking anything? Assume, both pip versions are upgraded to version 9.0.1 Now, I have to install virtualenv and virtualenvwrapper. Which pip version do I use to install it? $ pip install --user virtualenv and $ pip install --user virtualenvwrapper or $ pip3 install --user virtualenv and $ pip3 install --user virtualenvwrapper ps: I'm following this link- http://chrisstrelioff.ws/sandbox/2016/09/21/python_setup_on_ubuntu_16_04.html
answer count: 2
downvote count: 0
tagged with: virtualenv
tagged with: virtualenvwrapper
favorite count: 0

http://stackoverflow.com/comment/84143958
comment on: http://stackoverflow.com/a/48573501
score: 0
type: Comment
type: AnswerComment
has text: Fixed the answer for the sake of correctness but that-other-guy's one is better ;)

http://stackoverflow.com/q/48604341
accepted answer: http://stackoverflow.com/a/48605024
tagged with: python-asyncio
tagged with: event-loop
score: 10
tagged with: python
upvote count: 10
has title: What is event_loop_policy and why is it needed in python asyncio?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48605024
answer count: 1
downvote count: 0
favorite count: 0
has body: The event loops documentation mentions event_loop_policy but doesn’t describe what it is and why this abstract layer is needed in detail. (the documentation even says one can customize this layer). In addition, help(asyncio.get_event_loop_policy()) is just saying... UNIX event loop policy with a watcher for child processes. Then, I come to be more confused. What is watcher? What are child processes in event loop?
type: Question
linked to: http://stackoverflow.com/q/963965

http://stackoverflow.com/q/48628870
has body: I am new to Natural Language Processing (NLP) and I came across a problem where from the given text, I have to extract sentences belongs to different category like 1) sentences related to commitments (like sentences including 'will', 'shall' etc) 2) sentences related to cost or budget 3) and so on.... I need to know which features of NLTK should I use to implement this. How easy to add more and more category to extract more subjective information? Any examples are even more helpful.
answer count: 1
tagged with: machine-learning
tagged with: text-mining
favorite count: 0
has title: Extracting sentenses belongs to different category from text using NLTK
tagged with: python
tagged with: nlp
type: Question
has answer: http://stackoverflow.com/a/48675796
tagged with: nltk
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2

http://stackoverflow.com/comment/84266481
comment on: http://stackoverflow.com/a/48634628
has text: Still the same issue with `df['Loc'] = ['something', 'nothing', 55, None]`. Try `lambda x : True if isinstance(x, (str, unicode)) and 'some' in x else False`
type: AnswerComment
score: 0
type: Comment

tensorflow
tags question: http://stackoverflow.com/q/48609484
tags question: http://stackoverflow.com/q/48518895
type: Tag
tags question: http://stackoverflow.com/q/48504543
tags question: http://stackoverflow.com/q/48608776
tags question: http://stackoverflow.com/q/48496479
tags question: http://stackoverflow.com/q/48516696
tags question: http://stackoverflow.com/q/48525138
tags question: http://stackoverflow.com/q/48496612
tags question: http://stackoverflow.com/q/48570146
tags question: http://stackoverflow.com/q/48593029
tags question: http://stackoverflow.com/q/48595802
tags question: http://stackoverflow.com/q/48493936
tags question: http://stackoverflow.com/q/48577372
tags question: http://stackoverflow.com/q/48615667
tags question: http://stackoverflow.com/q/48614321
tags question: http://stackoverflow.com/q/48634151
tags question: http://stackoverflow.com/q/48628502
tags question: http://stackoverflow.com/q/48598402
tags question: http://stackoverflow.com/q/48533216
tags question: http://stackoverflow.com/q/48573243
tags question: http://stackoverflow.com/q/48529048
tags question: http://stackoverflow.com/q/48498711
tags question: http://stackoverflow.com/q/48524836
tags question: http://stackoverflow.com/q/48643378
tags question: http://stackoverflow.com/q/48550201
tags question: http://stackoverflow.com/q/48636600
tags question: http://stackoverflow.com/q/48585318
tags question: http://stackoverflow.com/q/48552103
tags question: http://stackoverflow.com/q/48552542
tags question: http://stackoverflow.com/q/48571080
tags question: http://stackoverflow.com/q/48490260
tags question: http://stackoverflow.com/q/48513337
tags question: http://stackoverflow.com/q/48558652
tags question: http://stackoverflow.com/q/48610132
tags question: http://stackoverflow.com/q/48628314
tags question: http://stackoverflow.com/q/48637688
tags question: http://stackoverflow.com/q/48510229
tags question: http://stackoverflow.com/q/48543486
tags question: http://stackoverflow.com/q/48612519
tags question: http://stackoverflow.com/q/48517244
tags question: http://stackoverflow.com/q/48511058
tags question: http://stackoverflow.com/q/48617771
tags question: http://stackoverflow.com/q/48599464
tags question: http://stackoverflow.com/q/48600160
tags question: http://stackoverflow.com/q/48525733
tags question: http://stackoverflow.com/q/48507778
tags question: http://stackoverflow.com/q/48616893
tags question: http://stackoverflow.com/q/48510264
tags question: http://stackoverflow.com/q/48514105
tags question: http://stackoverflow.com/q/48527153
tags question: http://stackoverflow.com/q/48612170
tags question: http://stackoverflow.com/q/48594888
tags question: http://stackoverflow.com/q/48557788
tags question: http://stackoverflow.com/q/48505674
tags question: http://stackoverflow.com/q/48568918
tags question: http://stackoverflow.com/q/48617656
tags question: http://stackoverflow.com/q/48534517
tags question: http://stackoverflow.com/q/48615037
tags question: http://stackoverflow.com/q/48579159
tags question: http://stackoverflow.com/q/48554874
tags question: http://stackoverflow.com/q/48636576
tags question: http://stackoverflow.com/q/48626246
tags question: http://stackoverflow.com/q/48509253
tags question: http://stackoverflow.com/q/48494356
tags question: http://stackoverflow.com/q/48611497
tags question: http://stackoverflow.com/q/48624974
tags question: http://stackoverflow.com/q/48571475
tags question: http://stackoverflow.com/q/48609168
tags question: http://stackoverflow.com/q/48636133
tags question: http://stackoverflow.com/q/48495899
tags question: http://stackoverflow.com/q/48490259
tags question: http://stackoverflow.com/q/48598431
tags question: http://stackoverflow.com/q/48562282
tags question: http://stackoverflow.com/q/48538404
tags question: http://stackoverflow.com/q/48619774
tags question: http://stackoverflow.com/q/48492079
tags question: http://stackoverflow.com/q/48496356
tags question: http://stackoverflow.com/q/48612987
tags question: http://stackoverflow.com/q/48610669

http://stackoverflow.com/comment/84464608
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48629638
has text: Please select the answer if it helped. Thanks for cooperation
type: AnswerComment

http://stackoverflow.com/comment/120728947
has text: Thanks, that works for me. Making a copy unfortunately considerably slows down my process though.
type: Comment
comment on: http://stackoverflow.com/a/48641097
type: AnswerComment
score: 0

http://stackoverflow.com/q/48599207
has body: I have grouped a DataFrame using data.groupby('column) and now I want to create a dataframe from each group: for i in data_group.indices: i = data_group.get_group(i) I can print the dataframes out within the for-loop, but I can't access them otherwise... Somehow the naming of the DataFrame with a variable is not working. Does anyone have a solution?
tagged with: pandas
has comment: http://stackoverflow.com/comment/84195009
answer count: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84195082
has comment: http://stackoverflow.com/comment/84195088
type: Question
has answer: http://stackoverflow.com/a/48599269
type: UnansweredQuestion
tagged with: python
has title: Python: How to get Dataframes with get_groups in for loops
linked to: http://stackoverflow.com/q/13603215
score: 0

http://stackoverflow.com/q/48520690
type: UnansweredQuestion
tagged with: firefox
downvote count: 0
tagged with: python
has body: Same setup was working in another Linux server. I just migrated to AWS (Centos 7) and am now facing this problem. Mozilla Firefox 52.6.0 Selenium 3.8.1 Python 2.7 My code: from pyvirtualdisplay import Display from selenium import webdriver display = Display(visible=0, size=(1366, 768)) display.start() browser = webdriver.Firefox() browser.set_window_size(1366, 768) browser.get('http://www.vionblog.com/') browser.set_script_timeout(30) browser.set_page_load_timeout(30) # seconds browser.save_screenshot('vionblog.png') browser.quit() display.stop() Error: Traceback (most recent call last): File "test.py", line 11, in &lt;module&gt; browser = webdriver.Firefox() File "/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 158, in __init__ keep_alive=True) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 237, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: connection refused
score: 1
answer count: 1
tagged with: selenium
upvote count: 1
tagged with: webdriver
tagged with: connection-refused
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48521378
has title: Selenium Firefox webdriver results in error: connection refused

http://stackoverflow.com/q/48557613
has comment: http://stackoverflow.com/comment/84111358
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84110975
type: Question
has comment: http://stackoverflow.com/comment/84116470
has comment: http://stackoverflow.com/comment/84116748
has comment: http://stackoverflow.com/comment/84111293
has comment: http://stackoverflow.com/comment/84123608
has comment: http://stackoverflow.com/comment/84111654
has comment: http://stackoverflow.com/comment/84111403
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84113041
tagged with: python
tagged with: calculation
has comment: http://stackoverflow.com/comment/84111777
has comment: http://stackoverflow.com/comment/84111274
has comment: http://stackoverflow.com/comment/84110909
has comment: http://stackoverflow.com/comment/84111686
has body: I am trying to extract an array of ndvi values for each pixel of an blue-filtered image (.jpg format). I used the NDVI=(arrayR-arrayB)/(arrayR+arrayB) however as a result I get a long list of arrays containing different values: array([ 0.44554455, 0.48387097, 0.47368421, ..., 0.14 , 0.14285714, 0.14285714]), array([ 0.45454545, 0.49450549, 0.48387097, ..., 0.14583333, 0.13207547, 0.14583333]), array([ 0.48314607, 0.46391753, 0.45454545, ..., 0.14583333, 0.13461538, 0.14583333]), array([ 0.40186916, 0.44554455, 0.46938776, ..., 0.125 , 0.12280702, 0.18681319]), array([ 0.40540541, 0.46391753, 0.49473684, ..., 0.16666667, 0.16 , 0.16363636]), array([ 0.39823009, 0.42056075, 0.47474747, ..., 0.17021277, 0.20454545, 0.15789474]), array([ 0.51111111, 0.47916667, 0.46 , ..., 0.1588785 , 0.16831683, 0.16190476]), The code used to get these results is: from PIL import Image from sense_hat import SenseHat import numpy as numpy img= Image.open('foo.jpg') imgR, imgB, imgG = img.split() #get channels arrR = numpy.asarray(imgR).astype('float64') arrB = numpy.asarray(imgB).astype('float64') num = (arrR - arrB) denom = (arrR + arrB) if denom.any() == 0: #preventing division by zero. denom = [0.000001, 0.000001] arr_ndvi = num/denom Which is actually the NDVI value of each pixel? Is it the average of the numbers inside each array?
has title: NDVI Value of a pixel calculation - Python
has comment: http://stackoverflow.com/comment/84111475
answer count: 0
tagged with: pixel
has comment: http://stackoverflow.com/comment/84111208
score: 1
downvote count: 0

http://stackoverflow.com/a/48575748
score: 0
answers question: http://stackoverflow.com/q/48573871
has body: Could you please try with by adding build() function in-between such as: action.move_to_element(click_me).move_by_offset(4,0).click().build().perform() The build() function is used for stitching Actions class functions together.
type: Answer

http://stackoverflow.com/comment/84190190
type: AnswerComment
score: 0
type: Comment
has text: Thanks @larsks. However, I have edited my question and included my altered script in conjunction with your answer, but I am still not receiving anything that I publish. What is it that I may be doing wrong?
comment on: http://stackoverflow.com/a/48584999

http://stackoverflow.com/q/48613592
has comment: http://stackoverflow.com/comment/84224079
has answer: http://stackoverflow.com/a/48613715
accepted answer: http://stackoverflow.com/a/48613715
has comment: http://stackoverflow.com/comment/84224056
upvote count: 2
type: AnsweredQuestion
score: 0
answer count: 2
downvote count: 2
linked to: http://stackoverflow.com/q/48738556
has title: how to serialize python classes?
linked to: http://stackoverflow.com/q/3768895
tagged with: flask
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/3768895
has answer: http://stackoverflow.com/a/48613637
possible better answer: http://stackoverflow.com/a/48613637
has comment: http://stackoverflow.com/comment/84224105
tagged with: http://stackoverflow.com/tag/json
has body: I have a model class defined as; class SiteConfig(object): def __init__(self,command,category,frequency,delay): self.command=command self.category=category self.frequency=frequency self.delay=delay im calling this model from another class like; from flask import Flask,request,jsonify import httplib from models.SiteConfig import * app = Flask(__name__) @app.route('/') def index(): return "Endpoint is not configured", 500 @app.route('/SitePollingConfiguration',methods=['GET']) def SitePollingConfiguration(): response = jsonify(statusCode=httplib.OK, config=BuildSiteConfig()) response.status_code = httplib.OK return response def BuildSiteConfig(): a= SiteConfig('20c','1',60,60) print (a) return a if __name__ == '__main__': app.run() But im getting SiteConfig is not JSON serializable error. How can i serialize the class object in python? EDIT i try to use existing flask json encoder; modified my siteconfig class like; from flask import Flask, jsonify from flask.json import JSONEncoder class JsonSerializable(object): def toJson(self): return JSONEncoder.default(self.__dict__) class SiteConfig(JsonSerializable): def __init__(self,command,category,frequency,delay): self.command=command self.category=category self.frequency=frequency self.delay=delay And then calling in my main class like; def ATGSitePollingConfiguration(): response = jsonify(statusCode=httplib.OK, config=BuildATGSiteConfig()) response.status_code = httplib.OK return response def BuildATGSiteConfig(): a= SiteConfig('20c','1',60,60) print (a) return a But still serializable issue. Sorry im new to python; can anyone provide simple code sample on how to achieve this?
tagged with: python

http://stackoverflow.com/a/52503114
score: 0
has body: You could also use Dask to extract and then load the data into, let's say, a Jupyter Notebook running on GCP. Make sure you have Dask is installed. conda install dask #conda pip install dask[complete] #pip import dask.dataframe as dd #Import dataframe = dd.read_csv('gs://bucket/datafile.csv') #Read CSV data dataframe2 = dd.read_csv('gs://bucket/path/*.csv') #Read parquet data This is all you need to load the data. You can filter and manipulate data with Pandas syntax now. dataframe['z'] = dataframe.x + dataframe.y dataframe_pd = dataframe.compute()
answers question: http://stackoverflow.com/q/48569618
type: Answer

http://stackoverflow.com/q/48514110
has comment: http://stackoverflow.com/comment/84022937
has comment: http://stackoverflow.com/comment/84023028
has comment: http://stackoverflow.com/comment/84023127
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84023129
has title: Python Array printing
has comment: http://stackoverflow.com/comment/84022961
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84022992
has comment: http://stackoverflow.com/comment/84023344
has comment: http://stackoverflow.com/comment/84023225
has comment: http://stackoverflow.com/comment/84023174
tagged with: python
has comment: http://stackoverflow.com/comment/84023084
has body: def testCheat(): current = 1 msg = ['I',' ','L','o','v','e',' ','L','o','l','i','s','!'] #message while a == 1: if current &lt;= 13: print(msg[current]) current+1 if current == 14: current = 1 testCheat() The problem is this. I and a friend (currently in discord call working on random stuff) are messing around attempting to work on mostly pointless code. After the following, It Only prints Black spaces. Could someone explain why? Im bit of an idiot right now and its 12 AM so...Yea..Usually Im not this dumb but oh well I just need a fix for the issue..In fact Im pretty sure this is completely wrong but It is pretty much cleaner then the stuff he made: def loopSpin(): while a == 1: print(" ") time.sleep(0.1) clear() print("L") time.sleep(0.1) clear() print("Lo") time.sleep(0.1) clear() print("Lol") time.sleep(0.1) clear() print("Loli") time.sleep(0.1) clear() print("Lolis") time.sleep(0.1) clear() print("Lolis f") time.sleep(0.1) clear() print("Lolis fo") time.sleep(0.1) clear() print("Lolis for") time.sleep(0.1) clear() print("Lolis for l") time.sleep(0.1) clear() print("Lolis for li") time.sleep(0.1) clear() print("Lolis for lif") time.sleep(0.1) clear() print("Lolis for life") time.sleep(0.1) clear() print("Lolis for life!") time.sleep(0.1) clear() print("Lolis for life!!") time.sleep(1) clear()
score: 0
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84023114
downvote count: 2
has comment: http://stackoverflow.com/comment/84023313

http://stackoverflow.com/a/48727108
accepted answer of: http://stackoverflow.com/q/48625299
answers question: http://stackoverflow.com/q/48625299
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: For that scenario you could consider to grant access via SharePoint App-Only flow. In the latest version of library the support for SharePoint App-Only access has been introduced: AuthenticationContext.acquire_token_for_app(client_id,client_secret) Follow this article on how to grant access using SharePoint App-Only, below i will summarize the main points: First of all, you need to setup your app-only principal Next step is granting permissions to the newly created principal Once the principal is created and consented you can use the principal's id and secret to request an access as demonstrated below: Example: from office365.runtime.auth.authentication_context import AuthenticationContext app_settings = { 'url': 'https://contoso.sharepoint.com/', 'client_id': '8efc226b-ba3b-4def-a195-4acdb8d20ca9', 'client_secret': '', } context_auth = AuthenticationContext(url=app_settings['url']) context_auth.acquire_token_for_app(client_id=app_settings['client_id'], client_secret=app_settings['client_secret']) ctx = ClientContext(app_settings['url'], context_auth) web = ctx.web ctx.load(web) ctx.execute_query() print("Web site title: {0}".format(web.properties['Title']))
has comment: http://stackoverflow.com/comment/85022176
type: Answer
has comment: http://stackoverflow.com/comment/129414818
has comment: http://stackoverflow.com/comment/85022459

http://stackoverflow.com/a/48602710
accepted answer of: http://stackoverflow.com/q/48593071
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48593071
has body: The problem is not with your python interpreter - it's with your python libraries setup. Look at the line that's causing the exception: File "/Users/judgej4/anaconda3/lib/python3.6/site-packages/concurrent/futures/_base.py", line 381 raise exception_type, self._exception, self._traceback This is python 2 code but it's under python3.6/site-packages/.... It looks like you've installed the futures package in your python3, which is a python2 package, a backport that you definitely don't need. You mention that root's PYTHONPATH doesn't contain /Users/judgej4/anaconda3/lib/python3.6/site-packages This is why your script works with sudo: it gets the distribution version of concurrent which is in /Users/judgej4/anaconda3/lib/python3.6/ rather than the incompatible futures version which is in /Users/judgej4/anaconda3/lib/python3.6/site-packages. If you remove the /Users/judgej4/anaconda3/lib/python3.6/site-packages/concurrent/ directory that should take care of your problem.
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/84204369
has comment: http://stackoverflow.com/comment/84204332
upvote count: 3

http://stackoverflow.com/a/48597722
has comment: http://stackoverflow.com/comment/84235092
has comment: http://stackoverflow.com/comment/84224258
accepted answer of: http://stackoverflow.com/q/48553427
type: Answer
score: 9
type: AcceptedAnswer
downvote count: 0
has body: Try this one using Selenium : import time from selenium import webdriver browser = webdriver.Firefox(executable_path="C:\\Users\\Vader\\geckodriver.exe") # Must install geckodriver (handles your browser)- see instructions on # http://selenium-python.readthedocs.io/installation.html. # Change the path to where your geckodriver file is. browser.get('https://www.tripadvisor.co.uk/Attraction_Review-g304551-d4590508-Reviews-Ashok_s_Taxi_Tours-New_Delhi_National_Capital_Territory_of_Delhi.html') browser.find_element_by_css_selector('.blEntry.website').click() #browser.window_handles # Results is 2 tabs opened. browser.switch_to.window(browser.window_handles[1]) # changes the browser to # the second one time.sleep(1) # When I went directly I was getting a 'blank' result, so I put # a little delay and it worked (I really do not know why). res = browser.current_url # the URL print(res) browser.quit() # Closes the browser Selenium
answers question: http://stackoverflow.com/q/48553427
upvote count: 9

http://stackoverflow.com/a/48629104
has body: The key to efficiency with pandas is performing operations for a whole dataframe/series, not go row by row. So, let's do this. for index, row1 in tqdm(df1.iterrows()): for index, row2 in df2.iterrows(): Here you calculate Cartesian product of two dataframes. This can be done much faster like this: df_product = pd.merge(df1.assign(key=0, index=df1.index), df2.assign(key=0), on='key').drop('key', axis=1) (Code was taken from here). I also added a column with indices of df1, we will need it later to calculate min of distances for every entity from df1. Now calculating all the deltas, latitudes in radians, a, c and distances in vectorized manner using numpy: dLat = np.radians(df_product['Latitude'] - df_product['lat']) dLong = np.radians(df_product['Longitude'] - df_product['lng']) lat1 = np.radians(df_product['lat']) lat2 = np.radians(df_product['Latitude']) a = (np.sin(dLat / 2) ** 2 + (np.sin(dLong / 2) ** 2) * np.cos(lat1) * np.cos(lat2)) c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) df_product['d'] = R * c Now, from df_product we leave only column with indices that we added before and column with distances. We group distances by indices, calculate corresponding minimum values and assign them to df1['schools'] as you did in your code. df1['schools'] = df_product.loc[:, ['index', 'd']].groupby('index', axis=0).min() This is it. For 1000 rows in each dataframe everything takes less than a second for me.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84255614
has comment: http://stackoverflow.com/comment/84278858
downvote count: 0
answers question: http://stackoverflow.com/q/48620355
has comment: http://stackoverflow.com/comment/84255195
has comment: http://stackoverflow.com/comment/84273295
type: Answer
has comment: http://stackoverflow.com/comment/84255384

http://stackoverflow.com/comment/84295291
type: QuestionComment
comment on: http://stackoverflow.com/q/48644810
has text: @ImportanceOfBeingErnest: It seems Warlock is saving a reference to the `FuncAnimation`. But your other two suggestions do apply. Would you like to reopen and post that as an answer?
type: Comment
score: 0

http://stackoverflow.com/comment/84180552
has text: I can see the outline of what you're proposing, and I get it, it makes sense. Question is - is this significantly different from a simple ord(s)+1==ord(s+1)? If so, how? If not, what tangible benefit is there to using regex over ord?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48591004

http://stackoverflow.com/a/49094790
accepted answer of: http://stackoverflow.com/q/48507946
upvote count: 4
has body: I solved this problem by using --video-on-top flag with vlc.Instance: class Player(): def __init__(self): self._instance = vlc.Instance(['--video-on-top']) self._player = self._instance.media_player_new() self._player.set_fullscreen(True) def play(self, path): media = self._instance.media_new(path) self._player.set_media(media) self._player.play() def stop(self): self._player.stop()
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48507946
type: Answer

http://stackoverflow.com/comment/84059300
has text: The problem isn't necessarily the end-of-line characters. Those are a problem when I use other means/tools to process the files to make them more readable by Python's csv module, since it would require regular expressions, which usually require some sort of newline delimiter (I think it's fixed on `sed` for Mac, at least) in order to avoid scanning the entire file.
type: Comment
comment on: http://stackoverflow.com/q/48530835
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84215185
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48609398
has text: Or, better: `y = random.choice(counts.keys())`
score: 0

http://stackoverflow.com/comment/84198642
comment on: http://stackoverflow.com/a/48600839
type: AnswerComment
score: 0
has text: @TheLatinist it does the same thing as `self.configure(menu=self.menu)`.
type: Comment

http://stackoverflow.com/comment/83996054
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48501080
has text: Have a look at [this answer](https://stackoverflow.com/a/4098938/2454357) for another way how to do this.
score: 0

http://stackoverflow.com/comment/84222339
type: Comment
comment on: http://stackoverflow.com/a/48611468
score: 0
type: AnswerComment
has text: Thank you, I will check it out! I am planning on writing a regex for each token so I can not only split the log via regex, but also break down dates and times so python can work with the data. Once complete I will open source it.

http://stackoverflow.com/a/48576788
answers question: http://stackoverflow.com/q/48572380
upvote count: 2
type: Answer
score: 2
downvote count: 0
has body: Try giving the complete path to pip - C:\Python27\Scripts\pip install &lt;the library you want to install&gt; Example: C:\Python27\Scripts\pip install numpy-1.14.0-cp27-none-win_amd64.whl or give the path to library you want to install as well. C:\Python27\Scripts\pip install C:\Python27\pillow

http://stackoverflow.com/comment/83980300
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48493545
has text: hmm... add `print(0)` ?
score: 1

http://stackoverflow.com/a/55058578
answers question: http://stackoverflow.com/q/48552343
type: Answer
has body: Best way is to Use a Python Web Frame Work you can choose Django/Flask. I will suggest you to Use Django because it's more powerful. Here is Step by guide to get complete your task : pip install django django-admin createproject buttonpython then you have to create a file name views.py in buttonpython directory. write below code in views.py: from django.http import HttpResponse def sample(request): #your python script code output=code output return HttpResponse(output) Once done navigate to urls.py and add this stanza from . import views path('', include('blog.urls')), Now go to parent directory and execute manage.py python manage.py runserver 127.0.0.1:8001 Step by Step Guide in Detail: Run Python script on clicking HTML button
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/comment/84286974
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48644605
type: Comment
has text: Thanks for editing the question to include your code. Can you now edit the question again to include examples of lines from the input file and how you want them to appear in the output file?

http://stackoverflow.com/comment/84212226
comment on: http://stackoverflow.com/q/48607975
type: QuestionComment
has text: Is there *any* input data with which this works? When it doesn't work, *how* does the result differ from what was expected? At what point in your debugging did things start to stray from what was expected?
score: 0
type: Comment

http://stackoverflow.com/q/48488665
tagged with: glmnet
has answer: http://stackoverflow.com/a/77615236
upvote count: 2
downvote count: 0
tagged with: scipy
tagged with: sparse-matrix
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48489191
accepted answer: http://stackoverflow.com/a/55328694
tagged with: rpy2
has answer: http://stackoverflow.com/a/55328694
tagged with: python
possible better answer: http://stackoverflow.com/a/48489191
answer count: 4
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51576425
has body: I have a python snippet which works just fine to run GLMNET on np.array X and y. However, when X is a column sparse matrix from scipy, the code fails as rpy2 is not able to convert X. Am I making an obvious mistake? A MCVE is: import numpy as np from scipy import sparse from rpy2 import robjects import rpy2.robjects.packages as rpackages from rpy2.robjects import numpy2ri from rpy2.robjects import pandas2ri if __name__ == "__main__": X = sparse.rand(5, 20, density=0.1) y = np.random.randn(5) numpy2ri.activate() pandas2ri.activate() utils = rpackages.importr('utils') utils.chooseCRANmirror(ind=1) if not rpackages.isinstalled('glmnet'): utils.install_packages("glmnet") glmnet = rpackages.importr('glmnet') glmnet = robjects.r['glmnet'] glmnet_fit = glmnet(X, y, intercept=False, standardize=False) And when I run it I get a NotImplementedError: Conversion 'py2ri' not defined for objects of type '&lt;class 'scipy.sparse.csc.csc_matrix'&gt;' Could I provide X in a different way? I'd be surprised if rpy2 could not handle sparse matrices.
has title: Running glmnet with rpy2 on sparse design matrix?

http://stackoverflow.com/comment/84046343
score: 0
has text: Try asking on https://math.stackexchange.com. You definitely need to learn some trigonometry before asking.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48525583

http://stackoverflow.com/q/48489044
has answer: http://stackoverflow.com/a/48489509
has body: I have a pandas.DataFrame with a Multiindex, thus: a val dog 1 cat 2 b fox 3 rat 4 And I want a series whose entries are the lists of the index values at level 1, so: a [dog, cat] b [fox, rat] the following does work, but is quite slow and inelegant: fff = df.groupby(level=0)['val'].agg(lambda x:[i[1] for i in list(x.index.values)]) So I am hoping there is a better way.
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
has title: groupby() and index values in pandas
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48489149
downvote count: 0
has answer: http://stackoverflow.com/a/48489149
possible better answer: http://stackoverflow.com/a/48489509
favorite count: 0
type: Question

http://stackoverflow.com/comment/83991944
type: Comment
comment on: http://stackoverflow.com/q/48498889
score: 0
has text: Done, thanks for the help.
type: QuestionComment

http://stackoverflow.com/comment/84091736
type: AnswerComment
comment on: http://stackoverflow.com/a/48527606
type: Comment
score: 0
has text: Thank you. I was able to solve my problem. I have one more question. Is "id" required in body? I was able to insert a post without id.

http://stackoverflow.com/comment/84091637
has text: still same error @mattdonders
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48544236
type: QuestionComment

http://stackoverflow.com/a/48553099
has body: You can use defaultdict from collections import defaultdict diction = defaultdict(lambda:0, {}) for item in your_list: diction[item] += 1 All your keys will be initialized to 1 if they are not in the dict already or incremented otherwise.
has comment: http://stackoverflow.com/comment/84102705
answers question: http://stackoverflow.com/q/48553077
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84102922
has comment: http://stackoverflow.com/comment/84102716
type: Answer
accepted answer of: http://stackoverflow.com/q/48553077
score: 0

http://stackoverflow.com/comment/84104165
comment on: http://stackoverflow.com/q/48553891
score: 0
type: Comment
type: QuestionComment
has text: Create a class containing the fields you need to share

http://stackoverflow.com/a/48622029
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48608576
type: Answer
has body: So I discovered the issue, I didn't give the app permissions to access the Internet in buildozer. In buildozer.spec I uncommented the line below. # (list) Permissions android.permissions = INTERNET
score: 2

http://stackoverflow.com/q/48571923
type: Question
upvote count: 4
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84142695
has comment: http://stackoverflow.com/comment/84142176
tagged with: javascript
tagged with: python
has title: Run same code in python and javascript
score: 4
has body: I have a special case in some application code where I need to run some non-trivial validation/math on the frontend (for responsiveness) as well as on the backend (for data integrity). I want to make sure they're in sync, and not write the code twice. Is there a way to compile something to both python and javascript? I'm currently looking at Transcrypt (python -> javascript transpiler), but the main problem is that it doesn't have very much of the stdlib available, and I'm not sure how to go about stubbing out my own versions. There are also some footguns that would be annoying to dance around, like changing methods called "get" to "py_get". I've also seen Js2Py, which takes the opposite approach of running javascript inside python. This seems potentially better, since I could write my shared code as a library using regular old javascript tooling, then import it and call it from python. So here's what I'm looking for: I want to be able to write a stateless application library in a single language. Clojure, python, javascript preferred, or a common business logic DSL that has bindings in both languages. I want to compile to both python and javascript, and run my tests in both places to make sure it all worked. I want it to be fast in both places (I currently call a pure js library from python using subprocess, but it's kinda slow). I want access to the source language's stdlib (short of browser apis/system apis), e.g. unittest, functools. Additional libraries are a plus.
has answer: http://stackoverflow.com/a/67495875
tagged with: transpiler
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/84169181
comment on: http://stackoverflow.com/q/48586111
type: QuestionComment
has text: Are you looking for ´F´ or ´P´ or ´S´ in text?
type: Comment
score: 1

dkpro-core
tag name: dkpro-core
tags question: http://stackoverflow.com/q/48518050
type: Tag

http://stackoverflow.com/comment/84003025
has text: 2. for output from solution 1 `df1 = df.drop_duplicates(['ticker', 'year'])` add `df1['year'] = df1['year'].astype(str) + 'first'` and similar for `df2`
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48489771

http://stackoverflow.com/q/48490316
has comment: http://stackoverflow.com/comment/83976304
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83977201
downvote count: 0
has comment: http://stackoverflow.com/comment/83973659
has title: Is it better to set global variables as instance variables in classes or not?
tagged with: python
has comment: http://stackoverflow.com/comment/83974598
answer count: 0
score: 1
upvote count: 1
has body: So i have a module called config.py which contains my global variables for a pygame tower defence game. When i define a class in a different module, is it better to set those global variables to an instance variable of the same name or to just use config.variable_name whenever i need to use that global variable? For example: Setting the global variables to an instance variable in __init__: self.map_height = config.map_height self.map_width = config.map_width Using them without the method above: for rw in range (config.map_height): for cl in range (config.map_width):
has comment: http://stackoverflow.com/comment/83973826
has comment: http://stackoverflow.com/comment/83976168

http://stackoverflow.com/q/48571463
has answer: http://stackoverflow.com/a/48571572
has comment: http://stackoverflow.com/comment/84139848
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84139766
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48571572
score: 3
tagged with: terminal
has comment: http://stackoverflow.com/comment/84140351
has answer: http://stackoverflow.com/a/48607488
tagged with: sed
accepted answer: http://stackoverflow.com/a/48571662
tagged with: python
has answer: http://stackoverflow.com/a/48571662
tagged with: regex
answer count: 4
has answer: http://stackoverflow.com/a/48571877
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4396974
has title: Remove lines between patterns and print all if any of patterns doesn't exists
has body: I have next file: G H A B C D N Let's delete lines from A to D and we will get next output: G H N It's very easy to do with sed '/A/,/D/d, but if my file don't have D, then output will be empty. I want if there isn't second pattern (D) do not delete anything and show full file. Second question - how to delete lines between patterns and next line after (N)? Kind of sed '/A/,+1d, but sed '/A/,/D/+1d will not work. There is no different for me to use sed, awk or python/bash scripts.
tagged with: bash

http://stackoverflow.com/a/48577329
has body: In this case, array a is vectorized and sent one element at a time. Declare a as 2D array[:,3] then send as a[0]. it may work.
type: Answer
answers question: http://stackoverflow.com/q/48575783
score: 0

http://stackoverflow.com/q/48595169
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/48595279
has answer: http://stackoverflow.com/a/48595279
favorite count: 0
type: Question
answer count: 2
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/84188703
has answer: http://stackoverflow.com/a/48595243
has comment: http://stackoverflow.com/comment/84188606
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84188640
has title: How to read multiple values in a column with a comma separator using python?
has body: how to read multiple values in a column with a comma separator using python ? Column 1 has numerical values, Column 2 has alphabets with comma separator. col1 col2 11 a, b, c 22 d, e, f 33 g, h, i
has comment: http://stackoverflow.com/comment/84188575
possible better answer: http://stackoverflow.com/a/48595243

scrapy
tags question: http://stackoverflow.com/q/48607540
tags question: http://stackoverflow.com/q/48517276
tags question: http://stackoverflow.com/q/48641437
tags question: http://stackoverflow.com/q/48611884
tags question: http://stackoverflow.com/q/48595585
tags question: http://stackoverflow.com/q/48592476
tags question: http://stackoverflow.com/q/48608698
tags question: http://stackoverflow.com/q/48623494
tags question: http://stackoverflow.com/q/48507771
tags question: http://stackoverflow.com/q/48615852
tag name: scrapy
tags question: http://stackoverflow.com/q/48542823
tags question: http://stackoverflow.com/q/48494796
tags question: http://stackoverflow.com/q/48614548
tags question: http://stackoverflow.com/q/48561819
tags question: http://stackoverflow.com/q/48542449
tags question: http://stackoverflow.com/q/48565669
tags question: http://stackoverflow.com/q/48595155
tags question: http://stackoverflow.com/q/48553427
tags question: http://stackoverflow.com/q/48492618
tags question: http://stackoverflow.com/q/48577626
tags question: http://stackoverflow.com/q/48556919
tags question: http://stackoverflow.com/q/48537040
tags question: http://stackoverflow.com/q/48644014
tags question: http://stackoverflow.com/q/48544207
type: Tag
tags question: http://stackoverflow.com/q/48523267
tags question: http://stackoverflow.com/q/48573298
tags question: http://stackoverflow.com/q/48611682
tags question: http://stackoverflow.com/q/48639783
tags question: http://stackoverflow.com/q/48536249
tags question: http://stackoverflow.com/q/48587429
tags question: http://stackoverflow.com/q/48630681
tags question: http://stackoverflow.com/q/48567063

http://stackoverflow.com/q/48544859
has body: I am trying to find a solution to download a CSV file from an internal company website. My first thought was throught the API but it doesn't exit, at least not yet. Second I figured, I would try a direct link to the CSV file on the website, that's also a No Go as the link is sort of static and even copy pasting to a new tab doesn't work. My third idea was to record a mouse movement, but that's just too inefficient as I would like this process to happen in the background. Please, I welcome any ideas, codes, software, anything.... most preferable solution would be in VBA after that python and then anything else. I'm sorry if this is not stack overflow worthy question :/
has comment: http://stackoverflow.com/comment/84085083
has title: downloading a CSV file without a direct link or API
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84085167
has comment: http://stackoverflow.com/comment/84085464
tagged with: python
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: vba
tagged with: excel
score: 0

http://stackoverflow.com/comment/84050107
type: AnswerComment
has text: Would I add `on_press=("Screen")` so when you click it its going go to that screen?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48511823

http://stackoverflow.com/comment/84158436
comment on: http://stackoverflow.com/q/48579740
type: Comment
has text: just some links to get you started. you should hit the official docs first.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84205060
comment on: http://stackoverflow.com/q/48604116
type: Comment
score: 0
has text: @bernieyum I'm so sorry, I forgot to rename above. I have fixed it.
type: QuestionComment

http://stackoverflow.com/comment/84332491
has text: What objects do you want to pickle in particular?
score: 0
comment on: http://stackoverflow.com/q/48624987
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48494814
answer count: 0
upvote count: 2
downvote count: 0
has body: There are two versions of the scipy.stats.ks_2samp function. scipy.stats.ks_2samp is the standard version, and scipy.stats.mstats.ks_2samp is the version in which "Missing values are discarded". Given distributions in which no entires are missing, the results are different. Why? Code: import numpy as np from scipy.stats import ks_2samp from scipy.stats.mstats import ks_2samp as ks_2sampm a = np.array([1, 3, 6, 8, 8]) b = np.array([2, 3, 4, 6]) ks_2samp(a, b)# statistic=0.40000000000000002, pvalue=0.75428850089034016 ks_2sampm(a, b) #(statistic=0.39999999999999997, pvalue=0.86916357240334474) Why the different p-values? I'm using scipy v1.0.0
tagged with: scipy
favorite count: 0
has title: scipy.stats.ks_2samp for masked and unmasked data give different results when no values are masked
type: Question
has comment: http://stackoverflow.com/comment/83983149
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83982795
tagged with: python
score: 2

http://stackoverflow.com/a/48504788
type: Answer
has comment: http://stackoverflow.com/comment/84010188
has body: The issue is that you are not calling pygame.display.update() anywhere in your code. You are indeed drawing these Rects but they will not be seen on your monitor unless this line is in your main event loop/main game loop. To fix this problem: Simply add the line pygame.display.update() at the end of your main loop after all drawing has been done. In your repo, I looked at UI.py. In the __main_loop method of the Window class, there is no line pygame.display.update() which is of course needed. Here is the fixed code: def __main_loop(self): while self.running: # Draw all the elements for element in self.elements: element.draw() for event in pygame.event.get(): if event.type is pygame.QUIT: self.running = False pygame.display.update() I hope this answer helped you and if you have any further questions please feel free to leave a comment below!
score: 2
answers question: http://stackoverflow.com/q/48503501
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48503501

http://stackoverflow.com/q/48537953
has comment: http://stackoverflow.com/comment/84071081
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84076861
has answer: http://stackoverflow.com/a/48540837
type: UnansweredQuestion
score: -4
has title: How to modify the value of index while trying to fecth it?
has body: For example there is a list called Demo_list. Demo_list = [4,5,6,7] If i give Demo_list[0] we will get value as 4. But if i gave only Demo_list[0] i want to get square of that value and the list should not be modified. Is it possible?
has comment: http://stackoverflow.com/comment/84070861
tagged with: python
has comment: http://stackoverflow.com/comment/84071040
answer count: 4
has answer: http://stackoverflow.com/a/48538045
has answer: http://stackoverflow.com/a/48537990
has answer: http://stackoverflow.com/a/48538043
linked to: http://stackoverflow.com/q/12555443
downvote count: 4
upvote count: 0

http://stackoverflow.com/q/48527321
has comment: http://stackoverflow.com/comment/84092503
has title: GridSearchCV did not find the best parameter with random forest
type: Question
tagged with: numpy
answer count: 0
has comment: http://stackoverflow.com/comment/84078687
has comment: http://stackoverflow.com/comment/84094677
has comment: http://stackoverflow.com/comment/84086361
tagged with: random-forest
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84117070
has comment: http://stackoverflow.com/comment/84104598
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/84052173
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/84119186
has comment: http://stackoverflow.com/comment/84092450
has comment: http://stackoverflow.com/comment/84053267
has comment: http://stackoverflow.com/comment/84052730
has comment: http://stackoverflow.com/comment/84094430
favorite count: 0
has body: As I understand the GridSearchCV should find the best parameter for model based on average cross_val_score() evaluation (please see a description of best_score_ result field here). However I get a such max_depth that looks not optimal. Say, if I pass max_depth=2 manually I get a little better result then the result returned by GridSearchCV where 2 is in list of max_depth grid. The GridSearchCV, however, find that 8 is better than 2 for max_depth. When I manually test the result of found 'best' max_depth parameter I find that it's not best. Please, could you explain me why could GridSearchCV find parameter with 'accuracy' result worse then I get with cross_val_score with a first arbitrary parameter? For details, please, look to the code below. UPDATE. I have updated the code having added the parameter random_state for RandomForestClassifier (as Nain tell me kindly). Now scores are very close but not exactly same. Why aren't they same?.. import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV DATA_LEN = 500 NUM_CLASSES = 3 NUM_VARS = 20 np.random.seed(0) # data generation (some feature rows are equal to target y, some of these rows are random) y = np.random.choice(NUM_CLASSES, DATA_LEN) xs = [] for j in range(DATA_LEN): row = [] for i in range(NUM_VARS): rand_int = np.random.choice(NUM_CLASSES) if j &lt; int(DATA_LEN / (i + 2)): row.append(y[j]) else: row.append(rand_int) xs.append(row) X = np.array(xs).reshape(DATA_LEN, -1) # predict: cross_val_score with max_depth=2 and max_depth=8 (the last one is found by GridSearchCV) np.random.seed(0) clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0) clf.fit(X, y) np.random.seed(0) # average accuracy is '0.579718326935' print np.average(cross_val_score(clf, X, y, cv=5, scoring='accuracy')) np.random.seed(0) clf = RandomForestClassifier(n_est…
downvote count: 0
has comment: http://stackoverflow.com/comment/84086273
score: 1
has comment: http://stackoverflow.com/comment/84093421
has comment: http://stackoverflow.com/comment/84093910
has comment: http://stackoverflow.com/comment/84093049

http://stackoverflow.com/comment/84198045
type: Comment
has text: Any reason - if you're going to ask for a four digit year and ignore the century, why not just ask for a two digit year to start with? And while I think I've got a guess at what you're trying to do here, the single letter variables names don't help - what are you trying to do here?
type: QuestionComment
comment on: http://stackoverflow.com/q/48600653
score: 0

http://stackoverflow.com/comment/84081677
comment on: http://stackoverflow.com/q/48542674
type: Comment
type: QuestionComment
score: 2
has text: t = datetime('now'); s = datestr(t);

http://stackoverflow.com/q/48528404
has answer: http://stackoverflow.com/a/48528492
answer count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/84052637
has title: Create index dictionary from integer list
downvote count: 0
has comment: http://stackoverflow.com/comment/84053679
has comment: http://stackoverflow.com/comment/84053714
favorite count: 0
type: Question
score: 9
has answer: http://stackoverflow.com/a/48528704
has answer: http://stackoverflow.com/a/48528964
has body: I have a (long) array a of a handful of different integers. I would now like to create a dictionary where the keys are the integers and the values are arrays of indices where in a the respective integer occurs. This import numpy a = numpy.array([1, 1, 5, 5, 1]) u = numpy.unique(a) d = {val: numpy.where(a==val)[0] for val in u} print(d) {1: array([0, 1, 4]), 5: array([2, 3])} works fine, but it seems rather wasteful to first call unique, followed by a couple of wheres. np.digitize doesn't seem to be ideal either as you have to specify the bins in advance. Any ideas of how to improve the above?
upvote count: 9
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84053590
has answer: http://stackoverflow.com/a/48557487
has comment: http://stackoverflow.com/comment/84109908
tagged with: python

http://stackoverflow.com/comment/84044505
type: Comment
comment on: http://stackoverflow.com/q/48524196
type: QuestionComment
score: 0
has text: @SrdjanGrubor I don't see why an alias would be bad (assuming you don't want to manually run python2 at some point). It's not a symlink.

http://stackoverflow.com/comment/84128787
comment on: http://stackoverflow.com/a/48563630
score: 0
has text: You are welcome! Do you wand percentile for multiple columns? Checl last edit.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48573402
accepted answer: http://stackoverflow.com/a/48573625
tagged with: css
tagged with: slick.js
type: Question
upvote count: 2
answer count: 2
downvote count: 0
tagged with: selenium
tagged with: web-scraping
tagged with: python
has body: I am trying to display all the prices in this page using Selenium and Chrome and then take a screenshot. By default, we can see only 3 prices. Is it anyway to disable the slick-slider so I could see all the 5 prices. I tried removing each of plansSlider slick-initialized slick-slider from div class="plansSlider slick-initialized slick-slider" but it does not seem to work. What would be the right way to do it? Here is the HTML: &lt;div class="plansSlider slick-initialized slick-slider" role="toolbar"&gt;&lt;button type="button" class="planTable-prev ico-arrow-left slick-arrow slick-disabled" aria-disabled="true" style="display: block;"&gt;Previous&lt;/button&gt; &lt;div aria-live="polite" class="slick-list draggable"&gt;&lt;div class="slick-track" style="opacity: 1; width: 1640px; left: 0px;" role="listbox"&gt;&lt;div class="slick-slide slick-current slick-active" data-slick-index="0" aria-hidden="false" style="width: 328px;" tabindex="-1" role="option" aria-describedby="slick-slide00"&gt; &lt;div class="swiper-slide columns"&gt; &lt;div class="plan"&gt; &lt;div data-equalizer-listener="plan-heading" class="plan-header"&gt; &lt;div class="prices"&gt; &lt;div class="col total"&gt; &lt;div class="price"&gt;&lt;sup&gt;$&lt;/sup&gt;&lt;span class="amount"&gt;15&lt;/span&gt; &lt;span class="caption"&gt;per month&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;p class="min-payment"&gt;Min. Total Cost is $360 over 24 months excluding any discounts.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="features"&gt; &lt;div class="feature first" data-equalizer-selector="included-data" style="min-height: 160px;"&gt; &lt;div class="description"&gt;&lt;span class="highlight-text"&gt;2GB DATA&lt;/span&gt;&lt;br&gt; &lt;span class="legal"&gt;Cost of 1MB included data $0.0073&lt;/span&gt; &lt;span class="legal"&gt;$10 per extra 1 GB&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="feature first" data-equalizer-selector="data-pool" style="min-height: 76px;"&gt; &lt;div class="descriptio…
has comment: http://stackoverflow.com/comment/84144283
has title: Adding new CSS using Selenium
has answer: http://stackoverflow.com/a/48574357
possible better answer: http://stackoverflow.com/a/48574357
favorite count: 0
has comment: http://stackoverflow.com/comment/84144391
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48573625

http://stackoverflow.com/comment/84193835
comment on: http://stackoverflow.com/q/48598429
score: 0
type: Comment
has text: Model code is included!? Relevant section should be there.
type: QuestionComment

http://stackoverflow.com/q/48624832
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/48629328
has comment: http://stackoverflow.com/comment/84247145
has answer: http://stackoverflow.com/a/48625714
has body: I'm making an inventory app in which I could update the values of the products from my 'home.html'. My proj name is Inventory App name is myapp Problem I am facing is that every time I update the value of a Stock from my homepage, it adds a new Product instead of updating the one that I want! I am using the ModelsForm Class provided by Django. Using Django=1.11 and Python=3.6 My project's urls.py: from django.conf.urls import url,include from django.contrib import admin from myapp.views import home urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls', namespace="myapp")), url(r'^myapp/home/', home, name='home'), ] My forms.py: from django import forms from .models import Inventory class Operations(forms.ModelForm): class Meta: model = Inventory fields = ('stocks_left',) My app's Model.py: from django.db import models import uuid class Inventory(models.Model): """ Model representing a the inventory. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4) inventory_name = models.CharField("INVENTORY NAME" ,max_length=200, help_text="This contains the Inventory name:") short_name = models.CharField(max_length=20, help_text="This contains an abbreviation:") inventory_code = models.IntegerField("INVENTORY CODE" ,default = '0', help_text="This contains the Inventory code:") price = models.IntegerField(default = '0') stocks_left = models.IntegerField("STOCKS LEFT",default = '0') def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return '{0} ({1}) ({2})'.format(self.inventory_name,self.inventory_code,self.stocks_left) My app's urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login app_name= 'myapp' urlpatterns = [ url(r'^$', login, {'template_name': 'myapp/login.html'}), ] and my views.py from django.shortcuts import render,redirect from django.contrib import auth from django.contrib.auth.models import User from django.views import generic from d…
tagged with: python
has title: Django button in Modelclass
type: Question

http://stackoverflow.com/comment/84487135
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48743473
has text: Ah, I am getting amysql related error: `Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'example_db.users_user_groups.group_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by`
type: AnswerComment

http://stackoverflow.com/comment/84279922
type: Comment
type: QuestionComment
has text: Yes, `my_dec` is to be designed after it is determined whether something like this is possible at all.
comment on: http://stackoverflow.com/q/48641456
score: 0

http://stackoverflow.com/q/48597252
tagged with: python
linked to: http://stackoverflow.com/q/48441705
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has answer: http://stackoverflow.com/a/48597281
accepted answer: http://stackoverflow.com/a/48597281
favorite count: 0
type: Question
has body: I have a Dataframe and I am trying to combine two columns (one has numeric IDs and the other one strings). So, let's give an example: What I am trying to do is to create a list that will show all the columnB values for each value of the columnA (just pasting an excel version and not a list output): Initially that was my code: #Group the results by the columns given scenario = df.groupby(['ColumnA', 'ColumnB', 'ColumnC', 'ColumnD']).agg({'Start_Date': 'min', 'End_Date': 'max', 'Number': 'sum', 'Number2': 'sum'}) scenario1 = list() for row in scenario.itertuples(): scenario1.append(row[0][0]," ",row[0][1]) And that returned this error: unsupported operand type(s) for +: 'int' and 'str' which is a common one. So, I tried the following scenario too: scenario1.append(row[0][0]," ",row[0][1]) with the error: append() takes exactly one argument (3 given) and I found a solution (not tested 100%): scenario1.append(str(row[0][0])+" "+row[0][1]) When I was trying to find a solution, I converted the dataframe into a json: json_data =json.loads(df.to_json(orient="records")) scenario2 = [{"columna": x["ColumnA"], "columnb": x["ColumnB"]} for x in json_data if "columnC" in x and x["ColumnC"] == "one"] print(scenario2) which returns an empty list. Please note that I have added a filter for a third column here. I cannot understand why this does not work. UPD: After jezrael's answer I tried editing it: df = pd.DataFrame({'columnA':[1111,1111,2222,3333,4444,4444,5555,6666], 'columnB':['AAAA','BBBB','AAAA','BBBB','AAAA','CCCC','BBBB','CCCC'], 'columnC':['one','one','one','one','one','one','two','one'], 'NUM1':[1,3,5,7,1,0,4,5], 'NUM2':[5,3,6,9,2,4,1,1], 'W':list('aaabbbbb')}) print (df) d = {'columnB':lambda x: x.tolist(), 'columnC':'first'} df1 = df.groupby('columnA').agg(d) print (df1) and I am returning this:
upvote count: 1
has title: Python list: For each columnA value show all the ColumnB values

http://stackoverflow.com/comment/83975287
type: QuestionComment
has text: The input would give a location to a folder, which holds subfolders, I want the script to create a list for each subfolder, which will show the whole path and every file within the subfolder
score: 0
comment on: http://stackoverflow.com/q/48491018
type: Comment

http://stackoverflow.com/q/48535166
score: 1
has body: I'm trying to write a dictionary app, with user input word, return definition. Also, if a typo was made, the program loops through 3 top closest matches of the typed and ask user if that is what they meant. My control flow is not running correctly, since 'y' does not break out of the loop or return definition. I don't get any error message. Can someone tell me how to fix? I also what to be able to return 'no close matches' if none of 3 suggestions was what the user meant. So there are 3 scenarios in the function: word, non-word with close matches(likely to be a typo), non-words without close matches (likely to be random inputs).It's the second scenario I'm having problem with. key=input('Enter the word: ') key=key.lower() dym=get_close_matches(key,data.keys()) def find_meaning(): if key in data: return data[key] elif len(dym)&gt;0: for i in dym: choice=input('Did you mean '+i + ' Y/N ') if choice=='Y' or 'y': break return data[i] elif choice=='N' or 'n': continue else: return 'Word does not exist!' print(find_meaning()) After removing 'break' from the above script, I get this output when I run: Tokas-MBP:Python_Mega_Course tzhu9$ python3 dictionary.py Enter the word: rainn Did you mean rain Y/N n ['Precipitation in the form of liquid water drops with diameters greater than 0.5 millimetre s.', 'To fall from the clouds in drops of water.'] The results I intend to see is that program will ask me 'Did you mean' with the second closest match, not outputting the definition of the word I didn't mean to ask.
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48535622
upvote count: 1
answer count: 1
has title: Python control flow with user input
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48535622

http://stackoverflow.com/q/48523365
tagged with: python
has answer: http://stackoverflow.com/a/48621546
has comment: http://stackoverflow.com/comment/84087023
tagged with: gtk
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
tagged with: gtk3
has body: environment: Ubuntu Gnome 16.04.3 GNOME Builder 3.26.3 The GNOME Builder generated project use GtkTemplate to interpret ui, But I change it to use Gtk.Builder to interpret. After modifying, it does not work. And I can not see any error message. class Application(Gtk.Application): def __init__(self): super().__init__(application_id='org.gnome.Ee', flags = Gio.ApplicationFlags.FLAGS_NONE) def do_startup(self): print('do_startup') Gtk.Application.do_startup(self) builder = Gtk.Builder() builder.add_from_resource("/org/gnome/Ee/window.ui") print(builder) self.builder = builder def do_activate(self): print("do_activate") win = self.props.active_window if not win: win = self.builder.get_object("EeWindow") print(win) win.present() # not work, can not see the window I have upload the demo code to Github: https://github.com/Honghe/gnome_builder_demo Any help will be appreciated!
upvote count: 1
favorite count: 0
type: Question
has title: Python Gtk+3 Window.present not work with GNOME Builder
accepted answer: http://stackoverflow.com/a/48621546
has comment: http://stackoverflow.com/comment/84044744

http://stackoverflow.com/q/48534197
favorite count: 0
has answer: http://stackoverflow.com/a/48542341
has comment: http://stackoverflow.com/comment/84064197
tagged with: beautifulsoup
has body: Does anyone know how to use bs4 in python to search for multiple tags, one of which will need an attribute? For example, to search for all occurrences of one tag with an attribute, I know I can do this: tr_list = soup_object.find_all('tr', id=True) And I know I can also do this: tag_list = soup_object.find_all(['a', 'b', 'p', 'li']) But I can not figure out how to combine the two statements, which in theory would give me a list, in order of occurrence of all of those html tags, with each 'tr' tag having an id. html snippet would be something like below: A_time_as_text some_text a_headline_as_text a_number_as_text more_text_text_text more_text_text_text more_text_text_text more_text_text_text more_text_text_text more_text_text_text Thanks for all help in advance!
type: Question
has comment: http://stackoverflow.com/comment/84064043
upvote count: 5
score: 5
has title: How to use BeautifulSoup to search for a list of tags, with one item in the list having an attribute?
has comment: http://stackoverflow.com/comment/84076379
has comment: http://stackoverflow.com/comment/84064057
tagged with: python
has comment: http://stackoverflow.com/comment/84063963
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/48542341
has comment: http://stackoverflow.com/comment/84064938
answer count: 1

http://stackoverflow.com/comment/83986229
type: AnswerComment
has text: I'm sorry but that is too advance for me. We don't use that much def. Our teacher said one while loop is good enough and just put if statements.
comment on: http://stackoverflow.com/a/48496318
type: Comment
score: 0

http://stackoverflow.com/q/48565924
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84127881
accepted answer: http://stackoverflow.com/a/48566288
has comment: http://stackoverflow.com/comment/84127970
tagged with: scatter-plot
has body: I have to make the following scatterplot in python. The code for this plot is : n = 1024 X = np.random.normal(0,1,n) Y = np.random.normal(0,1,n) plt.scatter(X,Y) But as espected, this wont give the colours. I've tried a lot, but can't find the solution. I know it has something to do with the angle of X/Y in the plot, but can't find out how to do this.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48566288
score: 1
has title: Rainbow scatter plot Python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84128523
answer count: 1
downvote count: 0

django
tags question: http://stackoverflow.com/q/48568065
tags question: http://stackoverflow.com/q/48606037
tags question: http://stackoverflow.com/q/48621130
tags question: http://stackoverflow.com/q/48591267
tags question: http://stackoverflow.com/q/48553384
tags question: http://stackoverflow.com/q/48600413
tags question: http://stackoverflow.com/q/48624641
tags question: http://stackoverflow.com/q/48568959
tags question: http://stackoverflow.com/q/48598870
tags question: http://stackoverflow.com/q/48493647
tags question: http://stackoverflow.com/q/48519881
tags question: http://stackoverflow.com/q/48593821
tags question: http://stackoverflow.com/q/48620168
tags question: http://stackoverflow.com/q/48554190
tags question: http://stackoverflow.com/q/48521128
tags question: http://stackoverflow.com/q/48526153
tags question: http://stackoverflow.com/q/48632520
tags question: http://stackoverflow.com/q/48605567
tags question: http://stackoverflow.com/q/48605163
tags question: http://stackoverflow.com/q/48526425
tags question: http://stackoverflow.com/q/48621678
tags question: http://stackoverflow.com/q/48507800
tags question: http://stackoverflow.com/q/48545392
tags question: http://stackoverflow.com/q/48573306
tags question: http://stackoverflow.com/q/48548098
tags question: http://stackoverflow.com/q/48564948
tags question: http://stackoverflow.com/q/48639234
tags question: http://stackoverflow.com/q/48508000
tags question: http://stackoverflow.com/q/48591708
tags question: http://stackoverflow.com/q/48523309
tags question: http://stackoverflow.com/q/48629262
tags question: http://stackoverflow.com/q/48637178
tags question: http://stackoverflow.com/q/48641121
tags question: http://stackoverflow.com/q/48605270
tags question: http://stackoverflow.com/q/48527646
tags question: http://stackoverflow.com/q/48525645
tags question: http://stackoverflow.com/q/48616380
tags question: http://stackoverflow.com/q/48601660
tags question: http://stackoverflow.com/q/48551574
tags question: http://stackoverflow.com/q/48614579
tags question: http://stackoverflow.com/q/48558957
tags question: http://stackoverflow.com/q/48560539
tags question: http://stackoverflow.com/q/48546688
tags question: http://stackoverflow.com/q/48529455
tags question: http://stackoverflow.com/q/48556041
tags question: http://stackoverflow.com/q/48509586
tags question: http://stackoverflow.com/q/48491168
tags question: http://stackoverflow.com/q/48554886
tags question: http://stackoverflow.com/q/48541819
tags question: http://stackoverflow.com/q/48600473
tags question: http://stackoverflow.com/q/48497115
tags question: http://stackoverflow.com/q/48561052
tags question: http://stackoverflow.com/q/48513611
tags question: http://stackoverflow.com/q/48597920
tags question: http://stackoverflow.com/q/48642476
tags question: http://stackoverflow.com/q/48508530
tags question: http://stackoverflow.com/q/48604710
tags question: http://stackoverflow.com/q/48641340
tags question: http://stackoverflow.com/q/48544394
tags question: http://stackoverflow.com/q/48599075
tags question: http://stackoverflow.com/q/48549589
tags question: http://stackoverflow.com/q/48534047
tags question: http://stackoverflow.com/q/48551674
tags question: http://stackoverflow.com/q/48612316
tags question: http://stackoverflow.com/q/48530306
tags question: http://stackoverflow.com/q/48602239
tags question: http://stackoverflow.com/q/48644069
tags question: http://stackoverflow.com/q/48535543
tags question: http://stackoverflow.com/q/48589210
tags question: http://stackoverflow.com/q/48566279
tags question: http://stackoverflow.com/q/48500339
tags question: http://stackoverflow.com/q/48629072
tags question: http://stackoverflow.com/q/48633475
tags question: http://stackoverflow.com/q/48591040
tags question: http://stackoverflow.com/q/48537906
tags question: http://stackoverflow.com/q/48492329
tags question: http://stackoverflow.com/q/48559875
tags question: http://stackoverflow.com/q/48536993
tags question: http://stackoverflow.com/q/48540267
tags question: http://stackoverflow.com/q/48506031

http://stackoverflow.com/comment/84047087
type: Comment
type: AnswerComment
score: 1
has text: Thanks. I added a note to that effect to the answer.
comment on: http://stackoverflow.com/a/48525838

http://stackoverflow.com/q/48637930
has answer: http://stackoverflow.com/a/48640172
score: 0
has answer: http://stackoverflow.com/a/48638655
has body: I have installed bs4 on my system successfully (using python setup.py install). Now the problem is while importing BeautifulSoup in python I'm getting below errors: C:\Users\dipankar&gt;python Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from bs4 import BeautifulSoup Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\dipankar\AppData\Local\Programs\Python\Python36\lib\site-packages\bs4\__init__.py", line 29, in &lt;module&gt; from .builder import builder_registry File "C:\Users\dipankar\AppData\Local\Programs\Python\Python36\lib\site-packages\bs4\builder\__init__.py", line 294, in &lt;module&gt; from . import _htmlparser File "C:\Users\dipankar\AppData\Local\Programs\Python\Python36\lib\site- packages\bs4\builder\_htmlparser.py", line 7, in &lt;module&gt; from html.parser import ( ImportError: cannot import name 'HTMLParseError' &gt;&gt;&gt;
tagged with: beautifulsoup
type: Question
has title: unable to import BeautifulSoup (python 3.6 and bs4-4.1.0)
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84276941
has comment: http://stackoverflow.com/comment/84280348
has comment: http://stackoverflow.com/comment/84275413
answer count: 2

http://stackoverflow.com/comment/84150993
has text: @JahongirRahmonov I tried to include /auth/ and /register/ inside the root urls by using include.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48577186
score: 0

http://stackoverflow.com/comment/84276941
score: 0
comment on: http://stackoverflow.com/q/48637930
type: QuestionComment
type: Comment
has text: yes, we were right. beautiful :)

http://stackoverflow.com/a/48506102
has comment: http://stackoverflow.com/comment/84032808
type: Answer
has body: Adapting your code. Using writestr works for me: import zipfile, os def show_jar_classes(jar_file): """prints out .class files from jar_file""" zf = zipfile.ZipFile(jar_file, 'w') try: #Code to write inside org folder in inside z.jar filename = 'Org\\India.txt' # name of the file fcontent = b'India is a great country' # content zf.writestr(filename,fcontent,zipfile.ZIP_DEFLATED) finally: zf.close() jar_file = 'D:/pyt/z.jar' show_jar_classes(jar_file)
answers question: http://stackoverflow.com/q/48504003
has comment: http://stackoverflow.com/comment/84046494
has comment: http://stackoverflow.com/comment/84033741
has comment: http://stackoverflow.com/comment/84037616
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84023119
upvote count: 1
has comment: http://stackoverflow.com/comment/84034771
accepted answer of: http://stackoverflow.com/q/48504003

http://stackoverflow.com/q/48491431
has answer: http://stackoverflow.com/a/48538985
has body: Noob here. I am using https://github.com/Seedstars/django-react-redux-base which is great and straight forward Django REST + React.js starter project. This is Django 1.11. My problem is with the Django REST backend not resolving the API endpoints correctly. I have added an application profiles that should return a user profile when queried by: /api/v1/profiles/getprofile/(some_name) Here is my top-level urls.py: from django.conf import settings from django.conf.urls import include, url from django.views.decorators.cache import cache_page from base import views as base_views urlpatterns = [ url(r'^api/v1/accounts/', include('accounts.urls', namespace='accounts')), url(r'^api/v1/getdata/', include('base.urls', namespace='base')), url(r'^api/v1/profiles/', include('profiles.urls', namespace='profiles')), url(r'', cache_page(settings.PAGE_CACHE_SECONDS)(base_views.IndexView.as_view()), name='index'), ] My profiles/urls.py: from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from . import views urlpatterns = [ url(_(r'^getprofile/(?P&lt;display_name&gt;.*)/$'), views.PublicProfileView.as_view(), name='getprofile'), ] With This setup, when I query http://localhost:8000/api/v1/profiles/getprofile/test, I get the IndexView in the response, basically html containing the frontend. However if I comment out r'' from the top level urls.py I get the expected JSON payload for the 'test' profile that I have in the database. Why would the resolver skip r'^api/v1/profiles/ and resolve straight to r''? Am I doing this wrong?
possible better answer: http://stackoverflow.com/a/48497427
tagged with: django
tagged with: django-urls
tagged with: python
has answer: http://stackoverflow.com/a/48497427
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83994854
has title: django REST urls.py does not resolve endpoint
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/48538985
type: Question

http://stackoverflow.com/q/48614280
tagged with: python
has comment: http://stackoverflow.com/comment/84225801
has answer: http://stackoverflow.com/a/48614553
score: 0
has comment: http://stackoverflow.com/comment/84225599
has comment: http://stackoverflow.com/comment/84225665
has comment: http://stackoverflow.com/comment/84225866
upvote count: 1
has comment: http://stackoverflow.com/comment/84225620
has comment: http://stackoverflow.com/comment/84225659
downvote count: 1
has comment: http://stackoverflow.com/comment/84225770
answer count: 1
has comment: http://stackoverflow.com/comment/84226046
has comment: http://stackoverflow.com/comment/84225545
has comment: http://stackoverflow.com/comment/84225893
favorite count: 0
has comment: http://stackoverflow.com/comment/84225811
type: Question
has comment: http://stackoverflow.com/comment/84225633
has comment: http://stackoverflow.com/comment/84225531
has comment: http://stackoverflow.com/comment/84225736
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84225914
has title: How to import a file in the same folder in python?
has comment: http://stackoverflow.com/comment/84225704
has body: My directory structure is as follows; ATGWS |-models |-SiteConfig.py |-__init__.py |-atgws.py |-CustomEncoder.py |-__init__.py I want to call customencoder.py within atgws.py. i try like this; from CustomEncoder import CustomEncoder .. app.json_encoder = CustomEncoder but not working. I get Traceback (most recent call last): File "/Users/ratha/projects/test711/ATGWS/atgws.py", line 3, in &lt;module&gt; from CustomEncoder import CustomEncoder ImportError: cannot import name CustomEncoder How can i call this?
has comment: http://stackoverflow.com/comment/84225753
has comment: http://stackoverflow.com/comment/84225760

http://stackoverflow.com/comment/84006553
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48504867
type: QuestionComment
has text: It's documented [here](https://docs.scipy.org/doc/numpy/reference/generated/numpy.isnat.html).

http://stackoverflow.com/q/48578512
has answer: http://stackoverflow.com/a/48578636
has comment: http://stackoverflow.com/comment/84153183
tagged with: pycharm
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 3
has title: PyCharm unresolved reference when importing from the same folder
has body: When I just created a new project I had two py files - main.py and functions.py - in the project folder "my project". In main.py I imported functions.py and it worked fine. But then I created some folders in "my project" folder and put main.py and functions.py in one of them. They are still in the same folder, but in main.py it says that functions.py is an unresolved reference. P.S. Using PyCharm on macos
upvote count: 3
answer count: 1
accepted answer: http://stackoverflow.com/a/48578636
favorite count: 0
type: Question

http://stackoverflow.com/comment/84030201
comment on: http://stackoverflow.com/q/48517735
score: 1
has text: it gets weird results: `2018-01-30 03:22:28,904,904.217 asdf`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48500372
duplicate of: http://stackoverflow.com/q/4700614
tagged with: pandas
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83994291
has body: I'm currently working on a pandas plot. It is my desire to move the legend of the plot to the right of my plot, unfortunately the solution I have found seems to crop the legend, rather than resizing the plot to fit the width of the legend. My Code: data = [ ['Sted 1',9,101,30,50,23,30], ['Sted 2',-13,83,31,44,36,31], ['Sted 3',17,93,22,42,23,35], ['Sted 4',-6,89,24,41,34,29] ] headers = [ 'Sted', 'Køb af grise og andre indægter', 'Foderomkostninger', 'Dyrlæge, medicin og diverse', 'Arbejdsomkostninger', 'Energi, vedl. bygn. mv.', 'Forrentning driftskapital og øvrige omk.' ] df = pd.DataFrame(data, columns=headers) df = df.set_index('Sted') df.plot(kind='bar', stacked=True, rot=0, figsize=(10,6), legend=False, zorder=3) plt.grid(zorder=0) plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) plt.show() Resulting Plot How would I go about resizing the plot to fit the legend with. (the overall figsize is fixed)
favorite count: 0
has comment: http://stackoverflow.com/comment/83994473
type: Question
has comment: http://stackoverflow.com/comment/83994461
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/4700614
has title: proper way to display legend outside pandas plot
tagged with: python
has comment: http://stackoverflow.com/comment/83994239
score: 3

http://stackoverflow.com/comment/84156904
comment on: http://stackoverflow.com/q/48579891
has text: You are trying to fit a linear model to a quadratic function. Is this intentional?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48622457
type: Answer
score: 0
has body: it was solved by using join inside of pd.read_csv.read_csv() -> append(dataFrames) -> concat: def get_merged_files(files_list, **kwargs): dataframes = [] for file in files_list: df = pd.read_csv(os.path.join(file), **kwargs) dataframes.append(df) return pd.concat(dataframes, axis=1)
answers question: http://stackoverflow.com/q/48603448

http://stackoverflow.com/q/48608570
tagged with: boto3
answer count: 6
has answer: http://stackoverflow.com/a/67836253
tagged with: python-3.6
possible better answer: http://stackoverflow.com/a/56090535
has answer: http://stackoverflow.com/a/48674021
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56090535
has answer: http://stackoverflow.com/a/64156936
has answer: http://stackoverflow.com/a/78613489
upvote count: 35
downvote count: 0
has answer: http://stackoverflow.com/a/55639095
has body: I need to retrieve an public object URL directly after uploading a file, this to be able to store it in a database. This is my upload code: s3 = boto3.resource('s3') s3bucket.upload_file(filepath, objectname, ExtraArgs={'StorageClass': 'STANDARD_IA'}) I am not looking for a presigned URL, just the URL that always will be publicly accessable over https. Any help appreciated.
tagged with: amazon-web-services
has title: Python 3 Boto 3, AWS S3: Get object URL
favorite count: 0
type: Question
score: 35
tagged with: amazon-s3
linked to: http://stackoverflow.com/q/48196784
accepted answer: http://stackoverflow.com/a/48674021
tagged with: python

http://stackoverflow.com/q/48532194
has title: Django Filter Not Returning Right Results
has comment: http://stackoverflow.com/comment/84060093
type: Question
tagged with: django-templates
answer count: 2
has comment: http://stackoverflow.com/comment/84060223
has comment: http://stackoverflow.com/comment/84060143
has answer: http://stackoverflow.com/a/48532274
score: 1
downvote count: 0
upvote count: 1
tagged with: django
has answer: http://stackoverflow.com/a/48544174
favorite count: 0
has comment: http://stackoverflow.com/comment/84060366
possible better answer: http://stackoverflow.com/a/48532274
type: AnsweredQuestion
tagged with: django-views
has body: I have a view where I am trying to filter a product by category. class ProductListView(ListView): context_object_name = 'products' model = models.Product template_name = "catalogue/catalogue.html" products = Product.objects.filter(category__name="Biryani Dishes") So I have a category called 'Biryani Dishes'. I get the error ValueError: invalid literal for int() with base 10: 'Biryani Dishes' If I change the query to (name='Chicken Biryani') I get back all the products. (I am expecting just Chicken Biryani). Ideally, I would like to create a generic query that takes in the category as an argument and I can specify the actual name on the HTML template. Any help is really appreciated. Models.py from django.db import models from django.core.urlresolvers import reverse class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name # def get_absolute_url(self): # return reverse('shop:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) index_together = (('id', 'slug'),) def __str__(self): return self.name # def get_absolute_url(self): # return reverse('shop:product_detail', args=[self.id, self.slug]) template code: {% for product in products %} {{ product.name }} Cooked with chicken and mutton cumin spices £ {{ product.price }} {% endfor %}
accepted answer: http://stackoverflow.com/a/48544174
has comment: http://stackoverflow.com/comment/84060164
tagged with: django-models
tagged with: python

http://stackoverflow.com/comment/84200983
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48600983
type: Comment
has text: Thank you. Bonus karma points for the added pointer on the list naming.

automation
tags question: http://stackoverflow.com/q/48636256
tags question: http://stackoverflow.com/q/48617746
tags question: http://stackoverflow.com/q/48621628
tag name: automation
tags question: http://stackoverflow.com/q/48626713
type: Tag

message-queue
type: Tag
tags question: http://stackoverflow.com/q/48521576
tag name: message-queue

http://stackoverflow.com/comment/84247941
comment on: http://stackoverflow.com/a/48625503
type: Comment
has text: @bikuser did you assign it back ? df_rg['y']=df_rg['y'][df_rg['y'].fillna(predict(df_rg['x'])
type: AnswerComment
score: 2

http://stackoverflow.com/comment/84088655
score: 0
type: AnswerComment
has text: No, forget the last comment, I can use ',' as a delimiter and deal with the two commas as they were delimiting a missing value and get rid of it
comment on: http://stackoverflow.com/a/48546106
type: Comment

http://stackoverflow.com/comment/83996616
type: Comment
has text: It works! And I just add `print('\033[0m')` at the end of the program to restore the default console color.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48501440

http://stackoverflow.com/comment/84219009
type: Comment
score: 4
has text: Thought: you often use **bold** in your code, I've never seen anyone else do this (at least not regularly), do people like this? could be worth a meta post?
type: AnswerComment
comment on: http://stackoverflow.com/a/48611312

http://stackoverflow.com/q/48627970
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48634744
accepted answer: http://stackoverflow.com/a/48634744
downvote count: 0
tagged with: python
tagged with: python-requests
tagged with: azure-virtual-machine
type: AnsweredQuestion
has body: from oauthlib.oauth2 import BackendApplicationClient from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import requests client_id = *CLIENT_ID* client_secret = *CLIENT_SECRET* auth = HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token =oauth.fetch_token(token_url='https://login.microsoftonline.com/*TENANT_ID*/oauth2/token', auth=auth,resource= 'https://management.azure.com/') data = {'Content-Type':'application/json', 'Authorization': 'Bearer ' + token['access_token']} r =requests.post('https://management.azure.com/subscriptions/' '*SUBSCRIPTION_ID*/providers/Microsoft.Compute/' 'locations/eastus/vmSizes?api-version=2016-04-30-preview', headers=data) I'm trying to get list of available VM's, but I'm getting an error: {'error': {'code': 'AuthorizationFailed', 'message': "The client 'X' with object id 'X' does not have authorization to perform action 'Microsoft.Compute/locations/vmSizes/read' over scope '/subscriptions/Y'."}}
tagged with: azure
upvote count: 1
has title: How to deal with Microsoft Azure error during authorization?
score: 1

http://stackoverflow.com/a/63792590
answers question: http://stackoverflow.com/q/48571995
score: 0
type: Answer
has body: you can create lambda function in any language. I don't have idea about greengrass but you can go through the official documentation here. The best source for AWS related query is their own documentation. C++ AWS Lambda functions

http://stackoverflow.com/a/48642738
accepted answer of: http://stackoverflow.com/q/48642572
downvote count: 0
answers question: http://stackoverflow.com/q/48642572
upvote count: 7
type: AcceptedAnswer
score: 7
has body: As the error message suggests, your __iter__ function does not return an iterator, which you can easily fix using the built-in iter function class Temp: def __init__(self): self.d = {} def __iter__(self): return iter(self.d.items()) This will make your class iterable. Alternatively, you may write a generator yourself, like so: def __iter__(self): for key,item in self.d.items(): yield key,item If you want to be able to iterate over keys and items separately, i.e. in the form that the usual python3 dictionary can, you can provide additional functions, for example class Temp: def __init__(self, dic): self.d = dic def __iter__(self): return iter(self.d) def keys(self): return self.d.keys() def items(self): return self.d.items() def values(self): return self.d.values() I'm guessing from the way you phrased it that you don't actually want the next() method to be implemented if not needed. If you would, you would have to somehow turn your whole class into an iterator and somehow keep track of where you are momentarily in this iterator, because dictionaries themselves are not iterators. See also this answer.
type: Answer

http://stackoverflow.com/comment/84216130
has text: Does it need to?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48609752
type: Comment

http://stackoverflow.com/comment/84109171
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48512300
type: Comment
has text: Well, that’s completely different problem, isn’t it? Don’t extend this question till infinity - if answer to original question fix your original problem - accept it and ask another. SO is not for interactive tutorials.

http://stackoverflow.com/q/48510264
has answer: http://stackoverflow.com/a/48521054
tagged with: google-cloud-ml
downvote count: 0
score: 6
tagged with: python
accepted answer: http://stackoverflow.com/a/48514402
favorite count: 0
has answer: http://stackoverflow.com/a/48514402
type: AnsweredQuestion
tagged with: tensorflow-serving
has title: In Tensorflow for serving a model, what does the serving input function supposed to do exactly
upvote count: 6
tagged with: tensorflow
has body: So, I've been struggling to understand what the main task of a serving_input_fn() is when a trained model is exported in Tensorflow for serving purposes. There are some examples online that explain it but I'm having problems defining it for myself. The problem I'm trying to solve is a regression problem where I have 29 inputs and one output. Is there a template for creating a corresponding serving input function for that? What if I use a one-class classification problem? Would my serving input function need to change or can I use the same function? And finally, do I always need serving input functions or is it only when I use tf.estimator to export my model?
possible better answer: http://stackoverflow.com/a/48521054
type: Question
answer count: 2

http://stackoverflow.com/comment/84001787
type: Comment
comment on: http://stackoverflow.com/a/48503607
type: AnswerComment
has text: Use them as they are. For example, `size in l_size`, not `size in "l_size"`.
score: 0

points
tag name: points
type: Tag
tags question: http://stackoverflow.com/q/48606898

http://stackoverflow.com/a/48641740
has body: The outputs tensor that you get from tf.nn.dynamic_rnn is the list of outputs of all cells. If you want to compute the sum of them, just call tf.reduce_sum on outputs: n_steps = 2 n_inputs = 3 n_neurons = 5 X = tf.placeholder(dtype=tf.float32, shape=[None, n_steps, n_inputs]) basic_cell = tf.nn.rnn_cell.BasicRNNCell(num_units=n_neurons) outputs, states = tf.nn.dynamic_rnn(basic_cell, X, dtype=tf.float32) # outputs = [?, n_steps, n_neurons], e.g. outputs from all cells sum = tf.reduce_sum(outputs, axis=1) # sum = [?, n_neurons] In case of MultiRNNCell, it will be the sum of outputs from the last layer, which is again what you generally want. Update: Summing up the tensors across the hidden layers would be more difficult because tensorflow MultiRNNCell reuses the same tensor for output from each cell, so the hidden layers are never exposed out of RNN. The simplest solution is to write your own MultiRNNCell that would sum up the outputs from each layer, instead of remembering only the last one. Here's how you can do that: from tensorflow.python.util import nest class MyMultiRNNCell(tf.nn.rnn_cell.MultiRNNCell): def call(self, inputs, state): cur_state_pos = 0 cur_inp = inputs new_states = [] new_outputs = [] for i, cell in enumerate(self._cells): with tf.variable_scope("cell_%d" % i): if self._state_is_tuple: if not nest.is_sequence(state): raise ValueError("Expected state to be a tuple of length %d, but received: %s" % (len(self.state_size), state)) cur_state = state[i] else: cur_state = tf.slice(state, [0, cur_state_pos], [-1, cell.state_size]) cur_state_pos += cell.state_size cur_inp, new_state = cell(cur_inp, cur_state) new_states.append(new_state) new_outputs.append(cur_inp) new_states = (tuple(new_states) if self._state_is_tuple else tf.concat(new_states, 1)) new_outputs_sum = tf.reduce_sum(new_outputs, axis=0) return new_outputs_sum, new_states
score: 2
has comment: http://stackoverflow.com/comment/84322444
has comment: http://stackoverflow.com/comment/84418125
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48639348
has comment: http://stackoverflow.com/comment/84322686
answers question: http://stackoverflow.com/q/48639348
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84323101

http://stackoverflow.com/q/48488519
has title: How can I load into a pandas DataFrame tweets from a json file?
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48488813
type: Question
has body: I'm trying to read my Twitter data saved in json format using the following code: import json with open(file, 'r') as f: line = f.readline() tweet = json.loads(line) df1 = pd.DataFrame(tweet) This code reads only one tweet and it works, but when I'm trying to read all file by: with open(file, 'r') as f: for line in f: tweet = json.loads(line) I receive an error: JSONDecodeError: Expecting value: line 2 column 1 (char 1) What should I change to read this file properly? My main task is to find creation dates for those tweets and I found it using following filters (I just used one tweet which worked at the beginning): df2 = df"user" df3 = df2.loc'created_at' df3 Is there a better way than DataFrames to handle this data?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48488624
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: 0

http://stackoverflow.com/a/48554526
type: Answer
has comment: http://stackoverflow.com/comment/84108353
score: 0
has body: Use the import foo as bar syntax to assign different names: from x import a as ax from y import a as ay
answers question: http://stackoverflow.com/q/48554256

wtforms
tags question: http://stackoverflow.com/q/48571304
type: Tag
tag name: wtforms
tags question: http://stackoverflow.com/q/48592639

http://stackoverflow.com/q/48597756
answer count: 1
favorite count: 0
type: Question
has body: I have installed a package, django_celery_beat. I can import it in the shell: &gt;&gt;import django_celery_beat &gt;&gt; But Pycharm shows me an error, it underlines the import as if the package wasn't installed. Why could this be?
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/48597826
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84192136
has title: Pycharm not recognizing package that shell does recognize. Django
linked to: http://stackoverflow.com/q/19885821
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48597826
score: 1
upvote count: 1

http://stackoverflow.com/comment/84269860
type: QuestionComment
comment on: http://stackoverflow.com/q/48625239
type: Comment
has text: Is that a project which was created with IBM COS as the backing storage, or a project backend by Swift object storage from which you are accessing IBM COS? That information might help to track down the problem in the code generation.
score: 0

http://stackoverflow.com/comment/87275698
type: Comment
comment on: http://stackoverflow.com/a/48562835
type: AnswerComment
has text: You don’t need python3-virtualenv to do dependency isolation between containers.
score: 1

http://stackoverflow.com/a/48639634
accepted answer of: http://stackoverflow.com/q/48639106
type: Answer
answers question: http://stackoverflow.com/q/48639106
score: 1
has body: I assume what you need is Principal Component Analysis(PCA) which is a statistical technique to reduce the dimension of a dataset while preserving their variance in the high dimension to the low dimension. In python : from sklearn.decomposition import PCA pca_x=PCA(n_components=1) X1D=pca.fit_transform(X) pca_y=PCA(n_components=1) y1D=pca.fit_transform(y) plt.plot(X1D,y1D) n_components=d where d is the required reduced dimension link to PCA in sklearn -->here An alternative could be t-distributed Stochastic Neighbor Embedding in short t-sne which is also used to visualize high dimensional data, find python implementation here
has comment: http://stackoverflow.com/comment/84276279
has comment: http://stackoverflow.com/comment/84276795
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48589857
has body: Here is one method, starting with the data in the text format you have: import pandas as pd import numpy as np df = pd.DataFrame([['S1', 'no diagnosis'], ['S2', 'fungus'], ['', 'squamous lesion'], ['S3', 'fungus'], ['S4', 'squamous lesion'], ['', 'glandular lesion']], columns=['CASE', 'Diagnosis']) # front fill CASE series df.CASE = df.CASE.replace('', np.nan).ffill() # pivot data df = pd.pivot_table(df, index=['CASE'], values=['Diagnosis'], aggfunc=lambda x: list(x)).reset_index() # split columns of lists into separate columns df = pd.concat([df'CASE', pd.DataFrame(df['Diagnosis'].values.tolist())], axis=1) # CASE 0 1 # 0 S1 no diagnosis None # 1 S2 fungus squamous lesion # 2 S3 fungus None # 3 S4 squamous lesion glandular lesion
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48588960
type: Answer

http://stackoverflow.com/comment/84113133
type: AnswerComment
comment on: http://stackoverflow.com/a/48552841
score: 0
type: Comment
has text: Now suppose that I want to do the same for "images", assuming images can also have multiple sub node "image"; how could I do that? I'm very sorry but I starting in Python.. :( Thank you so much

http://stackoverflow.com/q/48574781
has body: I have a script with the following: UPDATE table SET column to update = ? WHERE condition = ?", "text to insert", "text to test condition" For some reason SQL is not executing or even reading this line. When I misspell any of the reserved words or column names I do not get an error. HOWEVER, when I have UPDATE table SET column to update = "text to insert" WHERE Name = "text to test condition" SQL behaves as expected. The problem is the second method,which works, is not adequate for my needs. Am I missing something? Thanks
score: 0
has comment: http://stackoverflow.com/comment/84147830
has comment: http://stackoverflow.com/comment/84146308
has title: SQL Server variables not working
linked to: http://stackoverflow.com/q/7505808
tagged with: local
has answer: http://stackoverflow.com/a/48602700
has answer: http://stackoverflow.com/a/48575675
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84146242
tagged with: python
tagged with: variables
type: UnansweredQuestion
tagged with: pyodbc
linked to: http://stackoverflow.com/q/5957774
tagged with: sql-server

http://stackoverflow.com/q/48522880
tagged with: java
accepted answer: http://stackoverflow.com/a/48522978
tagged with: python
has title: ArrayList creation with Java 8 Lambda
tagged with: lambda
type: Question
has comment: http://stackoverflow.com/comment/84040397
upvote count: 3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48522978
favorite count: 0
has body: I would like to find a one-liner expression in Java that allows to instantiate an ArrayList and to insert some specific elements inside it. For example, an expression that creates an ArrayList containing the numbers in the interval [0, n] divisible by 3. I manage to insert the filtered elements into the ArrayList, but only using the forEach expression in the following way: ArrayList&lt;Integer&gt; numberList = new ArrayList&lt;Integer&gt;; IntStream.range(0, n + 1) .filter(number -&gt; number % 3 == 0) .forEach(number -&gt; numberList.add(number)); As you can see, it's necessary to separately instantiate the ArrayList and then insert the elements. In Python, we can use the following one-liner: numberList = [number for number in range(0, n + 1) if number % 3 == 0] Is there something equivalent or similar to the code below in Java 8? Thanks in advance.
tagged with: arraylist
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/84430411
score: 0
comment on: http://stackoverflow.com/q/48502153
type: Comment
type: QuestionComment
has text: StackOverflow encourages to post an **MCVE**-formulated Question. ( Where MCVE stands for a **M**inimum **C**omplete **V**erifiable **E**xample ). Would you mind to also post the the full DataSET, that was collected for this? Without a DataSET, the **MCVE** is simply in-**C**-omplete and un-**V**-erifiable, is it?

http://stackoverflow.com/comment/84212448
type: QuestionComment
comment on: http://stackoverflow.com/q/48607966
has text: Why not post expected output?
score: 0
type: Comment

http://stackoverflow.com/q/48562952
tagged with: mongoengine
has title: MongoEngine - Have a 'virtual' model with complex dependencies?
answer count: 0
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84128329
has body: I have an issue where there are two sets of users for one set of MongoEngine documents. One of these uses sets wants complex helper functions to be part of the document definition, the other user set cannot install the dependencies that the those functions require. I want to achieve something like a clean model and a dirty model where the user can select for themselves, but the actual database document definition is maintained in only one place. E.g. CleanModel/my_document.py class MyDocument(Document): my_field = StringField() DirtyModel/my_document.py from CleanModel import MyDocument as _MyDocument class MyDocument(_MyDocument): def some_function_that_relies_on_compiled_code(): pass The use could then do: from DirtyModel import MyDocument or from CleanModel import MyDocument and work with exactly the same Mongo document. The way I've written it above, DirtyModel.MyDocument.objects() can't get at documents created with the CleanModel. Any ideas on the best way to solve this? (I don't think that moving the helper methods outside of the document definition is practical in this case)
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48559172
has comment: http://stackoverflow.com/comment/84114087
has comment: http://stackoverflow.com/comment/84114905
score: 2
has comment: http://stackoverflow.com/comment/84114232
has comment: http://stackoverflow.com/comment/84116803
accepted answer of: http://stackoverflow.com/q/48558918
answers question: http://stackoverflow.com/q/48558918
has comment: http://stackoverflow.com/comment/84114656
has body: Without looking into the logic of your code. The following can produce your desired output: result = ( df.groupby('page_id') .apply(lambda dfg: dfg.drop('page_id', axis=1).to_dict(orient='list')) .apply(lambda x: x['accessed_time']) .to_dict() ) result Out[63]: {1: [20171223, 20171224], 2: [20171226], 3: [20171227]} It seems it can be simplified to: df.groupby('page_id').apply(lambda x: x.accessed_time.tolist()).to_dict() {1: [20171223, 20171224], 2: [20171226], 3: [20171227]} Or: df.groupby('page_id').accessed_time.apply(list).to_dict() Out[65]: {1: [20171223, 20171224], 2: [20171226], 3: [20171227]}
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/48642159
has answer: http://stackoverflow.com/a/48642304
has comment: http://stackoverflow.com/comment/84280993
downvote count: 1
favorite count: 0
type: Question
has title: Trying to print the factorial of natural numbers using generators .Getting the output as 1 1 1 1 1 instead of 1 1 2 6 24 120 ......?
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/54214986
has answer: http://stackoverflow.com/a/48642414
answer count: 4
has comment: http://stackoverflow.com/comment/84280946
has answer: http://stackoverflow.com/a/60601332
type: UnansweredQuestion
upvote count: 0
has body: def my_gen(): number = 1 fact = 1 fact = fact * number //Trying to calculate factorial yield fact number = number + 1 a = my_gen() print(next(a)) print(next(a)) print(next(a)) print(next(a)) print(next(a)) Trying to print the output for the first five natural numbers. Expected output: 1 1 2 6 24 obtained output: 1 1 1 1 1 How can i do this??.Any help is appreciated

http://stackoverflow.com/comment/84154599
comment on: http://stackoverflow.com/q/48579152
score: 0
has text: platform is object (argumentParser object) not string
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84002187
has text: @Thomas8 OP seems to indicate there's an obvious error in this code. Which means it's most definitely a big no-no to post it on Code Review. Code Review only accepts working code.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48503761

http://stackoverflow.com/a/48587411
downvote count: 0
type: Answer
has body: I would like to link back from a data point in a scatterplot to the image that the numerical value for this data point was derived from. See https://plot.ly/dash/interactive-graphing. You can assign a callback to selectedData, hoverData, or clickData property of the dash_core_components.Graph. linking image selections to data points: e.g. Display an image. Update a plot according to the selection in the image (e.g. a simple histogram). You could display a background image on a plotly graph and then use the same selectedData tools to update callbacks based off of the selected region. Here is a simple example: import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import base64 import json app = dash.Dash() app.css.append_css({'external_url': 'https://codepen.io/chriddyp/pen/dZVMbK.css'}) RANGE = [0, 1] def InteractiveImage(id, image_path): encoded_image = base64.b64encode(open(image_path, 'rb').read()) return dcc.Graph( id=id, figure={ 'data': [], 'layout': { 'xaxis': { 'range': RANGE }, 'yaxis': { 'range': RANGE, 'scaleanchor': 'x', 'scaleratio': 1 }, 'height': 600, 'images': [{ 'xref': 'x', 'yref': 'y', 'x': RANGE[0], 'y': RANGE[1], 'sizex': RANGE[1] - RANGE[0], 'sizey': RANGE[1] - RANGE[0], 'sizing': 'stretch', 'layer': 'below', 'source': 'data:image/png;base64,{}'.format(encoded_image) }], 'dragmode': 'select' # or 'lasso' } } ) app.layout = html.Div([ html.Div(className='row', children=[ html.Div(InteractiveImage('image', 'dash_app.png'), className='six columns'), html.Div(dcc.Graph(id='graph'), className='six columns') ]), html.Pre(id='console') ]) # display the event data for debugging @app.callback(Output('console', 'children'), [Input('image', 'selectedData')]) def display_selected_data(selectedData): return json.dumps(selectedData, indent=2) @app.callback(Output('graph', 'figure'), [Input('image', 'selectedData')]) def update_histogram(selectedData): x_range = selectedData['range']['x']…
has comment: http://stackoverflow.com/comment/84223703
score: 2
answers question: http://stackoverflow.com/q/48586208
upvote count: 2

http://stackoverflow.com/a/48598663
has comment: http://stackoverflow.com/comment/84194222
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48598639
has comment: http://stackoverflow.com/comment/84194285
has comment: http://stackoverflow.com/comment/84194294
has comment: http://stackoverflow.com/comment/84194382
has comment: http://stackoverflow.com/comment/84194263
has body: You usually multiply a number with the asterisk (*). So we can multiply the i-th number with: numbers[i] *= M To multiply every N-th element except the first one, we can construct a range: for i in range(N, len(numbers), N): numbers[i] *= M The last argument of the range is the step, it means that we thus each time increment i, until reach len(numbers)
type: Answer

http://stackoverflow.com/q/48600622
tagged with: mysql
has body: I need some help in order to deal with NULL values in MySQL using Python. This is my code: import MySQLdb # This function connects to the MySQL database def db_connect(): try: db = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DATABASE, charset="utf8") except Exception as e: print(e) sys.exit("Can't connect to database") return db def store(project_title, description, website, start_date): try: cursor = db.cursor() insert_projects_query = "INSERT INTO projects (title, description, website, start_date) VALUES ('"+project_title+"','"+description+"','"+website+"','"+start_date+"') ON DUPLICATE KEY UPDATE `title`='"+project_title+"'" cursor.execute(insert_projects_query) db.commit() except Exception as e: print e I don't know how to store NULL if a field, e.g. start_date has the value "NA". Can I somehow directly assign null to start_date or should I just exclude it from INSERT query? My table in the database is created in such a way that by default these fields are NULL values.
type: Question
has comment: http://stackoverflow.com/comment/84197925
has title: How to deal with NULL values in MySQL from Python
has comment: http://stackoverflow.com/comment/84200915
has comment: http://stackoverflow.com/comment/84198433
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0

http://stackoverflow.com/comment/84006934
type: QuestionComment
comment on: http://stackoverflow.com/q/48505862
score: 0
has text: [md-johirul-islam](https://stackoverflow.com/users/3416272/md-johirul-islam), so this is an intended update? Also would you please point out which line in `jupyter_notebook_config.py` I need to update?
type: Comment

http://stackoverflow.com/q/48587696
downvote count: 0
answer count: 1
has title: Unable to import Tokenizer from Keras
tagged with: machine-learning
tagged with: keras
has body: Currently working through a Deep Learning example and they are using a Tokenizer package. I am getting the following error: AttributeError: 'Tokenizer' object has no attribute 'word_index' Here is my code: from keras.preprocessing.text import Tokenizer samples = ['The cat say on the mat.', 'The dog ate my homework.'] tokenizer = Tokenizer(num_words=1000) tokenizer.fit_on_sequences(samples) sequences = tokenizer.texts_to_sequences(samples) one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary') word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) Could anyone help me catch my mistake?
favorite count: 0
accepted answer: http://stackoverflow.com/a/48587891
type: AnsweredQuestion
score: 3
tagged with: deep-learning
has answer: http://stackoverflow.com/a/48587891
tagged with: python
type: Question
upvote count: 3

http://stackoverflow.com/q/48617247
score: 0
has answer: http://stackoverflow.com/a/48618388
answer count: 1
tagged with: machine-learning
has body: I found this information in tensorflow's doc: tf.layers.max_pooling1d? Max Pooling layer for 1D inputs. Arguments: inputs: The tensor over which to pool. Must have rank 3. And: tf.layers.max_pooling2d? Max pooling layer for 2D inputs (e.g. images). Arguments: inputs: The tensor over which to pool. Must have rank 4. My confusion is why the inputs require rank 3 and rank 4, respectively?
tagged with: tensorflow
type: Question
has title: Confusion about tensorflow's max_pooling function
tagged with: python
tagged with: computer-vision
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48618388

http://stackoverflow.com/comment/84131142
type: Comment
type: QuestionComment
score: 0
has text: @GOD kindly post the full code. How do you get speedOfVehicle where is it defined; so that community can help you write a python code.
comment on: http://stackoverflow.com/q/48567396

http://stackoverflow.com/comment/84021058
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48513058
has text: @user2864740 That _would_ work if we were only accepting numbers and strs, but arbitrary objects might not str to the same thing every time (and if repr is not overridden, by default they don't!)

http://stackoverflow.com/q/48522852
tagged with: range
has title: How to fix the error :'range' object is not callable in python3.6
tagged with: python
accepted answer: http://stackoverflow.com/a/48522969
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48522969
downvote count: 2
answer count: 1
tagged with: loops
favorite count: 0
type: Question
has body: my code looks like: list_var = ['rh','temp','tl','Tt','DPD','PAR'] for L in range(1, len(list_var)): for subset in itertools.combinations(list_var, L): f = 'inf ~ {} + C(area)'.format(' * '.join(list(subset))) error 'range' object is not callable jumped up even I changed len(list_var) into a number. Can you identify the problem and fix it? Thank you in advance!!!
has comment: http://stackoverflow.com/comment/84040286
upvote count: 9
score: 7

http://stackoverflow.com/comment/83987537
score: 0
comment on: http://stackoverflow.com/q/48497201
type: Comment
type: QuestionComment
has text: if i am having the list as dict with same key values. can you tell me the code for that. example:{'0/RP0': ['OPERATIONAL'], '0/PM1': ['OPERATIONAL'], '0/PM0': ['FAILED'], '0/FT2': ['OPERATIONAL'], '0/FT0': ['OPERATIONAL'], '0/FT1': ['OPERATIONAL']}

http://stackoverflow.com/a/48573962
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48573933
accepted answer of: http://stackoverflow.com/q/48573933
score: 7
type: AcceptedAnswer
upvote count: 7
has body: pickle is old enough that it was present in Python 1.4, the oldest version for which python.org still has documentation. That was all the way back in 1996. It's way older than pip.
has comment: http://stackoverflow.com/comment/84145325

http://stackoverflow.com/q/48528084
has answer: http://stackoverflow.com/a/48528187
possible better answer: http://stackoverflow.com/a/48528187
has comment: http://stackoverflow.com/comment/84051191
has body: I have two columns with dates(mm/dd/yy). I need to validate if DateColumn_A comes before DateColumn_B. I used the following code and I got this error "TypeError: must be string, not Series". Please help a beginner. Code: Column_A = datetime.strptime(df['DateColumn_A'], '%m %d %y') Column_B = datetime.strptime(df['DateColumn_B'], '%m %d %y') for index, row in dataframe.iterrows(): if row[Column_A] &lt; row[Column_B] print (index,row[Column_A]) else: pass
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/48528423
accepted answer: http://stackoverflow.com/a/48528423
type: AnsweredQuestion
has title: Compare two date columns and validate if DateA is earlier than DateB
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84051146
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48528309

http://stackoverflow.com/a/48547567
answers question: http://stackoverflow.com/q/48547230
type: Answer
has comment: http://stackoverflow.com/comment/84090986
downvote count: 0
has body: Another possible solution would be to get a list of the line2D objects and then change the linewidths using set_linewidth() lines = ax.lines for line in lines: line.set_linewidth(2)
score: 5
upvote count: 5

http://stackoverflow.com/comment/84193974
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48598646
has text: Sorry actually `image_path = '/home/atin/test/ОД Д.bmp'.encode('utf8')` works, but when I try `plt.imread('/home/atin/test/ОД Д.bmp'.encode('utf8'))` then it throws the above error.
score: 0

http://stackoverflow.com/comment/84161278
has text: @Basj, answered in the related question: https://stackoverflow.com/questions/48581455/run-a-multiprocessing-job-with-python-2-7-windows
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48580406
type: AnswerComment

http://stackoverflow.com/comment/84143394
type: Comment
has text: @juanpa.arrivillaga: I will be sure to read them carefully. Thanks for your input!
comment on: http://stackoverflow.com/q/48556239
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84165746
type: QuestionComment
comment on: http://stackoverflow.com/q/48583455
score: 2
type: Comment
has text: The problem is at your end. Don't worry about it.

http://stackoverflow.com/comment/84230928
type: AnswerComment
comment on: http://stackoverflow.com/a/48617070
score: 0
has text: Hi mate, thanks for your first answer! This is great! I was wondering if you could tell me the answer to my second question regarding asking a user for input and then checking if the key exists?
type: Comment

http://stackoverflow.com/comment/83984194
type: QuestionComment
has text: @advay.umare: I'll try that!
comment on: http://stackoverflow.com/q/48495451
score: 1
type: Comment

http://stackoverflow.com/comment/84456879
type: Comment
comment on: http://stackoverflow.com/a/48609549
type: AnswerComment
score: 1
has text: Yep, that's what I meant.

http://stackoverflow.com/q/48628181
tagged with: python-3.x
has title: Compare paragraph word by word
score: 0
has comment: http://stackoverflow.com/comment/84253713
answer count: 1
has comment: http://stackoverflow.com/comment/84253321
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84253366
accepted answer: http://stackoverflow.com/a/48628498
has body: I am trying to compare line in a paragraph line by line and word by word but I feel like this is not the most efficient way can you help me out please. If there is a difference I want to return both words. file_1 = open("file1.txt").readlines() file_2 = open("file2.txt").readlines() if file_1 == file_2: print("Same") if file_1[0] != file_2 [0]: listone = file_1[0].split() listtwo = file_2[0].split() if listone[0] == listtwo[0] and listone[1] == listtwo[1]: pass elif listone[0] != listtwo[0] and listone[1] == listtwo[1]: print('line 1:\n', listone[0]+"\n", listtwo[0]) elif listone[0] == listtwo[0] and listone[1] != listtwo[1]: print('line 1:\n', listone[1]+"\n", listtwo[1]) Edit: By efficient I mean going through an entire paragraph without righting every single line.
tagged with: python
has answer: http://stackoverflow.com/a/48628498
type: Question

http://stackoverflow.com/q/48582311
has body: My current goal is to clone a single layer from an already trained model. The first problem is that the clone() method clones the entire graph from the supplied node which is not what I want. So I tried cloning it manually (in this case a Dense layer) by retrieving its weights from the node as follows: node = C.logging.graph.find_by_name(model, 'node') C.layers.Dense(node.shape, init=node.W.value, init_bias=node.b.value) Unfortunately this does not work since I get the following shady error: TypeError: in method 'random_initializer_with_rank', argument 1 of type 'CNTK::ParameterInitializer const &amp;'
has comment: http://stackoverflow.com/comment/84166170
has comment: http://stackoverflow.com/comment/84162681
has title: CNTK: cloning a single layer
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48594235
tagged with: deep-learning
has answer: http://stackoverflow.com/a/48594235
tagged with: cntk
has comment: http://stackoverflow.com/comment/84163814
answer count: 1
tagged with: machine-learning
type: Question

http://stackoverflow.com/q/48553745
score: 0
tagged with: list
tagged with: performance
has comment: http://stackoverflow.com/comment/84103899
has comment: http://stackoverflow.com/comment/84104212
has comment: http://stackoverflow.com/comment/84103986
duplicate of: http://stackoverflow.com/q/41313413
upvote count: 1
linked to: http://stackoverflow.com/q/23487307
downvote count: 1
has comment: http://stackoverflow.com/comment/84104238
has comment: http://stackoverflow.com/comment/84104022
has body: There are 2 functions. def f1(n): t = time() m = [] for i in range(n): m.insert(0, 0) return time() - t def f2(n): t = time() m = [] for i in range(n): m[:0] = [0] return time() - t They both insert many elements to list. But the second uses slice. I know that these algorithms are bad(because O(N^2)) but looks like f2 faster than f1(I tried both Python 2 and Python 3). (You can see time here http://rextester.com/XSPGVO38315) Is it random or there is a reson for which f2 is better than f1? Are these function equal? If no, what is better(faster)?
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: insertion
tagged with: python
has title: Is inserting to head of a list using slice faster than insert(0,...)?
linked to: http://stackoverflow.com/q/41313413

http://stackoverflow.com/comment/84020049
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48512467
has text: three-pineapples, that your for the instructions. I will review and try, but if unsuccessful, I will create a sample code and post. Thanks again.

http://stackoverflow.com/comment/84201255
type: AnswerComment
comment on: http://stackoverflow.com/a/48602058
score: 0
type: Comment
has text: Hi. I tired your method and it seems no working. When I submit nothing in any field the form validate itself and flash name/message error. But when I fill in the name and message, leave email/phone empty, the form was posted.

http://stackoverflow.com/comment/84077560
score: 0
has text: Can you add the script you are using?
comment on: http://stackoverflow.com/q/48540442
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84059124
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48531633
type: Comment
has text: Never heard of [repl.it](https://repl.it). Great site! I will add that to my answer.

http://stackoverflow.com/q/48601396
tagged with: entropy
type: Question
type: AnsweredQuestion
tagged with: math
has body: I have a set of data for which has an ID, timestamp, and identifiers. I have to go through it, calculate the entropy and save some other links for the data. At each step more identifiers are added to the identifiers dictionary and I have to re-compute the entropy and append it. I have really large amount of data and the program gets stuck due to growing number of identifiers and their entropy calculation after each step. I read the following solution but it is about the data consisting of numbers. Incremental entropy computation I have copied two functions from this page and the incremental calculation of entropy gives different values than the classical full entropy calculation at every step. Here is the code I have: from math import log # ---------------------------------------------------------------------# # Functions copied from https://stackoverflow.com/questions/17104673/incremental-entropy-computation # maps x to -x*log2(x) for x&gt;0, and to 0 otherwise h = lambda p: -p*log(p, 2) if p &gt; 0 else 0 # entropy of union of two samples with entropies H1 and H2 def update(H1, S1, H2, S2): S = S1+S2 return 1.0*H1*S1/S+h(1.0*S1/S)+1.0*H2*S2/S+h(1.0*S2/S) # compute entropy using the classic equation def entropy(L): n = 1.0*sum(L) return sum([h(x/n) for x in L]) # ---------------------------------------------------------------------# # Below is the input data (Actually I read it from a csv file) input_data = [["1","2008-01-06T02:13:38Z","foo,bar"], ["2","2008-01-06T02:12:13Z","bar,blup"], ["3","2008-01-06T02:13:55Z","foo,bar"], ["4","2008-01-06T02:12:28Z","foo,xy"], ["5","2008-01-06T02:12:44Z","foo,bar"], ["6","2008-01-06T02:13:00Z","foo,bar"], ["7","2008-01-06T02:13:00Z","x,y"]] total_identifiers = {} # To store the occurrences of identifiers. Values shows the number of occurrences all_entropies = [] # Classical way of calculating entropy at every step updated_entropies = [] # Incremental way of calculating entropy at every step for item in input_data: temp = item[…
accepted answer: http://stackoverflow.com/a/48676056
tagged with: python
has answer: http://stackoverflow.com/a/48629359
favorite count: 0
has title: Calculating Incremental Entropy for Data that is not real numbers
tagged with: python-3.x
answer count: 2
linked to: http://stackoverflow.com/q/17104673
tagged with: python-3.5
possible better answer: http://stackoverflow.com/a/48629359
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48676056

http://stackoverflow.com/comment/84227589
type: Comment
type: QuestionComment
score: 0
has text: Do you know the year? That would be important for leap days
comment on: http://stackoverflow.com/q/48615285

http://stackoverflow.com/comment/84276578
comment on: http://stackoverflow.com/a/48639614
has text: for example if the date entered is 2010-01-01 then it should be wrong
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/48645464
upvote count: 3
type: Question
downvote count: 0
tagged with: python
has title: Simultanious Iteration via 4 Indexes
tagged with: iteration
favorite count: 0
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48645978
has answer: http://stackoverflow.com/a/48645978
tagged with: loops
possible better answer: http://stackoverflow.com/a/48645774
tagged with: python-3.x
has body: I worte a code to iterate trough a string or list via multiple indexes and in reverse order, 2 going forward and 2 going backwords. However due to the range limitiation given to the for loop in Iteration 1 and Iteration 3 I can't get the final char or list element. Here is the code: mix = 'fdsfef232' for i in range(len(mix)-1): print('Iter 1:&gt;&gt;&gt;',mix[i],'\tIter 2:&gt;&gt;&gt;',mix[i+1],'\tIter 3:&gt;&gt;&gt;',mix[-1-i],'\tIter 4:&gt;&gt;&gt;',mix[-2-i]) Here is the Output: Iter 1:&gt;&gt;&gt; f Iter 2:&gt;&gt;&gt; d Iter 3:&gt;&gt;&gt; 2 Iter 4:&gt;&gt;&gt; 3 Iter 1:&gt;&gt;&gt; d Iter 2:&gt;&gt;&gt; s Iter 3:&gt;&gt;&gt; 3 Iter 4:&gt;&gt;&gt; 2 Iter 1:&gt;&gt;&gt; s Iter 2:&gt;&gt;&gt; f Iter 3:&gt;&gt;&gt; 2 Iter 4:&gt;&gt;&gt; f Iter 1:&gt;&gt;&gt; f Iter 2:&gt;&gt;&gt; e Iter 3:&gt;&gt;&gt; f Iter 4:&gt;&gt;&gt; e Iter 1:&gt;&gt;&gt; e Iter 2:&gt;&gt;&gt; f Iter 3:&gt;&gt;&gt; e Iter 4:&gt;&gt;&gt; f Iter 1:&gt;&gt;&gt; f Iter 2:&gt;&gt;&gt; 2 Iter 3:&gt;&gt;&gt; f Iter 4:&gt;&gt;&gt; s Iter 1:&gt;&gt;&gt; 2 Iter 2:&gt;&gt;&gt; 3 Iter 3:&gt;&gt;&gt; s Iter 4:&gt;&gt;&gt; d Iter 1:&gt;&gt;&gt; 3 Iter 2:&gt;&gt;&gt; 2 Iter 3:&gt;&gt;&gt; d Iter 4:&gt;&gt;&gt; f How can I make sure that Iter 1 and Iter 3 they both reach the end of the string? Thanks
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/48645774

http://stackoverflow.com/q/48568886
has title: Jupyter: ImportError: libcusolver.so.8.0: cannot open shared object file: No such file or directory
tagged with: python
has body: While I run the following code in Jupyter notebook: import tensorflow as tf a = tf.constant("hello world!") sess = tf.Session() print(sess.run(a)) I got the following error messages: ImportError: Traceback (most recent call last): File "/home/ac/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/home/ac/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/home/ac/anaconda3/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/home/ac/anaconda3/lib/python3.6/imp.py", line 242, in load_module return load_dynamic(name, filename, file) File "/home/ac/anaconda3/lib/python3.6/imp.py", line 342, in load_dynamic return _load(spec) ImportError: libcusolver.so.8.0: cannot open shared object file: No such file or directory However, the same code if I run directly through python, it works as expected. Here is my environment: Ubuntu 16.04 Tensorflow 1.5 Cuda 9.0 Cudnn 7 Nvidia Driver 390.12 Python 3.6 Anaconda 3 The issue happens after I recently upgrade the Tensorflow. Before I was using Tensorflow 1.4 with Cuda 8 and Cudnn 6. However, I feel this is more like Jupyter notebook issue than Tensorflow installation. I also tried other solution like export LD_LIBRARY_PATH, no luck. I wonder if the Jupyter using the different library than the avocado environment? Or this issue is caused by some failure installation?
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48587367
favorite count: 0
tagged with: jupyter
accepted answer: http://stackoverflow.com/a/48587367
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/48493008
score: 0
accepted answer: http://stackoverflow.com/a/48493068
tagged with: python
tagged with: regex
has body: I have data in python that needs to convert string from string = "[-8.27104300e-02 9.09485668e-02 7.72242993e-02]" to this converted_string = "-8.27104300e-02, 9.09485668e-02, 7.72242993e-02" Basically removing brackets [] and putting in comma for the spaces How do I achieve this ?
type: Question
has answer: http://stackoverflow.com/a/48493068
answer count: 1
has comment: http://stackoverflow.com/comment/83979290
tagged with: string
has title: python - string conversion array and comma delimited
has comment: http://stackoverflow.com/comment/83979519
type: AnsweredQuestion
tagged with: format

http://stackoverflow.com/comment/84249699
has text: Maybe convert the dict to a suffix-tree?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48626313

http://stackoverflow.com/q/48490157
type: Question
tagged with: scikit-learn
tagged with: python
has title: Python SGDregressor, different results of RMSLE
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48490200
tagged with: linear-regression
score: 0
answer count: 1
has body: I'm trying to implement SDGregressor from scikit-learn for simple linear regression problem, but my code gives a different value of RMSLE each time? I wonder why this is so? Also, I'm wondering how to get the least value of the RMSLE? from sklearn import linear_model from sklearn.metrics import mean_squared_error from math import sqrt import math import matplotlib.pyplot as plt #load data train = pd.read_csv('Train.csv') test = pd.read_csv('Test.csv') #split data x_train = train.GrLivArea[:1000].values.reshape(-1,1) y_train = train.SalePrice[:1000].values.reshape(-1,1) x_train_normal = np.log(x_train) y_train_normal = np.log(y_train) #Normalization x_test = train.GrLivArea[1000:].values.reshape(-1,1) y_test = train.SalePrice[1000:].values.reshape(-1,1) x_test_normal = np.log(x_test) y_test_normal = np.log(y_test) # Normalization y_test_transform = np.exp(y_test_normal) Model = linear_model.SGDRegressor() Model.n_iter = np.ceil(10**7 / len(y_train_normal)) Model.fit(x_train_normal,y_train_normal) Sale_Prices_Predicted = Model.predict(x_test_normal) Sale_Prices_Prediceted_Transform = np.exp(Sale_Prices_Predicted) rmslee = rmsle(y_test_transform, Sale_Prices_Prediceted_Transform) print("RMSLE: ", rmslee) For example: 0.28153047299638045 0.28190513681658363 0.28207666380009233 0.28126007334118047
accepted answer: http://stackoverflow.com/a/48490200

http://stackoverflow.com/comment/84144571
score: 0
comment on: http://stackoverflow.com/a/48573753
type: AnswerComment
has text: I implemented it as a descriptor because I would like to reuse and not copy the complex setter code in other classes. So I thought a custom descriptor would be the right way to go.
type: Comment

http://stackoverflow.com/comment/85241115
type: QuestionComment
comment on: http://stackoverflow.com/q/48632167
type: Comment
score: 0
has text: were you able to achieve this?

http://stackoverflow.com/comment/84026263
comment on: http://stackoverflow.com/q/48516013
has text: Your second last line create an array.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49618181
accepted answer of: http://stackoverflow.com/q/48566400
answers question: http://stackoverflow.com/q/48566400
score: 0
type: Answer
has body: The django cache was the way to go. See the above link for an example.
type: AcceptedAnswer

http://stackoverflow.com/a/48561055
has comment: http://stackoverflow.com/comment/84118287
has body: You should change your checkdate function to return the actual (status, date) pair instead of just whether such a pair exists. For this, you can translate your any expression almost 1:1 into a next statement, using None as the default in case no such pair exists. For example, like this (I also changed the function to take parameters instead of using global variables, but that's not essential for this to work). import datetime result_set = ((0, datetime.date(2018, 1, 29)), (1, datetime.date(2018, 1, 30)), (0, datetime.date(2018, 1, 31)), (0, datetime.date(2018, 2, 1))) cd = datetime.date(2018, 1, 30) def checkdate(dates, date): return next(((s, d) for (s, d) in dates if d == date), None) entry = checkdate(result_set, cd) if entry is not None and entry[0] == 1: print("found") Or like this, if you prefer using the global result_set and cd variables: def checkdate(): return next(((s, d) for (s, d) in result_set if d == cd), None) entry = checkdate() if entry is not None and entry[0] == 1: print("found")
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84118030
accepted answer of: http://stackoverflow.com/q/48560624
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48560624
upvote count: 1

http://stackoverflow.com/a/48514660
score: 0
has body: value = '$20' float(value) will produce an error because of the '$' symbol float(value.replace('$','')) will work propably better to not have the '$' symbol in the fixed rates array
type: Answer
answers question: http://stackoverflow.com/q/48514509

http://stackoverflow.com/a/48625647
has comment: http://stackoverflow.com/comment/84251148
has comment: http://stackoverflow.com/comment/84250026
score: 0
answers question: http://stackoverflow.com/q/48625470
has comment: http://stackoverflow.com/comment/84249534
has comment: http://stackoverflow.com/comment/138707060
has comment: http://stackoverflow.com/comment/84248387
has comment: http://stackoverflow.com/comment/84248552
has body: what you're after is being able to just call something like, math.sin(x) right? you make it a static method. and you just simply don't make any instances. @staticmethod def awesome_method(x): return x if you're thinking why can't you actually do a = math() because math, isn't a class. it's a separate script with all those functions in it. so you may want to make a separate script with all your static things in it. ;) if you want everything in the same script, then it's just local variables. and if you're like me, you'd rather them be organised properly with classes, looks like you'd probably be best just making a normal class, and creating just one instance of it
has comment: http://stackoverflow.com/comment/84249228
has comment: http://stackoverflow.com/comment/84250281
type: Answer

http://stackoverflow.com/comment/129546773
score: 0
comment on: http://stackoverflow.com/a/48585487
has text: This is a clever idea; however, it will not produce a sample that follows the distribution specified by the weights. Consider a DF with two tuples "A" and "B" with weights 1 and 2 respectively. If you do a little math (or simulation) you will notice that tuple A will be sampled with probability 0.25, which is smaller than expected given the distribution of weights.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/133882923
score: 0
type: AnswerComment
has text: This is true. For the difference between socket and http timeout, uwsgi supports running its own http server and if you run it that way, you usually will not run it behind a big webserver like e.g. nginx, apache. For that, you want to configure with http timeout. But if you do employ a reverse proxy, you will want to run it in socket mode. And in that case, you configure with socket timeout. This is explained better here, bullet point 2: https://uwsgi-docs.readthedocs.io/en/latest/ThingsToKnow.html
type: Comment
comment on: http://stackoverflow.com/a/63392042

http://stackoverflow.com/a/48632716
has comment: http://stackoverflow.com/comment/84264052
has body: Potential cause: the inline code, outside of the functions, is running before the event handler. Unrelated: rather than use environment variables for credentials, you should use IAM roles for AWS credentials and use Parameter Store for other, non-AWS, credentials.
has comment: http://stackoverflow.com/comment/84265783
has comment: http://stackoverflow.com/comment/84264616
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/48632576
has comment: http://stackoverflow.com/comment/84292787
has comment: http://stackoverflow.com/comment/84294284
downvote count: 0

http://stackoverflow.com/comment/84146273
comment on: http://stackoverflow.com/a/48558991
type: Comment
type: AnswerComment
has text: @Brett7533 Hi, I just test in python2.7 and it works without the 'r'. However, it also works with the 'r'
score: 0

http://stackoverflow.com/comment/107078184
score: 1
type: QuestionComment
has text: looks like someone else already did... https://stackoverflow.com/a/53035144
type: Comment
comment on: http://stackoverflow.com/q/48602128

http://stackoverflow.com/comment/84287763
has text: Right :) The value is an index of the best parameter.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48631050
type: AnswerComment

http://stackoverflow.com/comment/84109140
score: 0
type: QuestionComment
has text: Are first 2 columns `MultiIndex` ?
type: Comment
comment on: http://stackoverflow.com/q/48556510

http://stackoverflow.com/a/48611415
has body: what I will do unique d = {'columnB':'unique', 'columnC':'unique' } df1 = df.groupby('columnA').agg(d) df1 Out[573]: columnB columnC columnA 1111 [AAAA] [one, two] 2222 [BBBB] [one] 3333 [BBBB] [one] 4444 [CCCC] [one] 5555 [BBBB] [two] 6666 [CCCC] [one]
has comment: http://stackoverflow.com/comment/84238666
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48611234
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84237448
answers question: http://stackoverflow.com/q/48611234
upvote count: 3
score: 3

http://stackoverflow.com/comment/84087353
score: 1
comment on: http://stackoverflow.com/q/48545807
has text: please dont put any code in comment section, update your post and put it in there, make sure to edit the format as well
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48598742
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48574254
type: Answer
answers question: http://stackoverflow.com/q/48574254
has body: Figured it out. Had to convert train_set[0] and test_set[0] into a theano array variable
score: 0

http://stackoverflow.com/comment/84212388
comment on: http://stackoverflow.com/q/48607966
score: 0
type: Comment
type: QuestionComment
has text: @honda, post the expected result

http://stackoverflow.com/q/48514897
score: 0
has comment: http://stackoverflow.com/comment/84035660
answer count: 0
tagged with: validation
has body: I am validation KMS ARN value by String and pattern match in Regular Expression. Sample Input: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab Rules: Start with “arn:aws:kms:” string value. Followed by Region Name. c. Followed by colon “:” d. Followed by numeric value. Followed by colon “:” Followed by “key” string value. Followed by Alphabets and/or numbers and/or underscore string value. Which is again validate against UUD. Code to get AWS Regions: &gt;&gt;&gt; import boto3 &gt;&gt;&gt; session_obj = boto3.session.Session() &gt;&gt;&gt; session_obj.get_available_regions('lambda') Code for KMS Validation: def validate_aws_kms_arns(kms_arns_str): """ Validate KMS ARNS Format: arn:aws:kms:$RegionCode$:$AccountNumber$:key/$UUID$ $RegionCode$ : list of region Ids $AccountNumber$ : Interger account number. $UUID$: uuid """ # Get Region Value list from AWS. lambda_region_list = ['ap-northeast-1', 'ap-northeast-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2'] pattern = re.compile("\Aarn:aws:kms:({}):\d+:key/([\w-]+)\Z".format( '|'.join(lambda_region_list)) ) match_obj = pattern.match(kms_arns_str) if bool(pattern.match(kms_arns_str)): uuid_value = match_obj.groups()[1] else: print("Invalid KMS ARNS value: {}".format(kms_arns_str)) return False # UUID Validation. # ... return True but I saw https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces this. We need to validate KMS ARNS value for partition and service also? And above code is correct to validate KMS value?
tagged with: amazon-kms
type: Question
has comment: http://stackoverflow.com/comment/84050922
has title: Validate AWS KMS value at start of code
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84060755
tagged with: regex
tagged with: amazon-web-services

http://stackoverflow.com/comment/84137825
type: AnswerComment
has text: Or in another words - you cannot assign to new column, because errors or `NaN`s.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48563630

http://stackoverflow.com/a/51254224
downvote count: 1
has body: settings.py should be like this: DJOSER = { 'SERIALIZERS': { 'user_create': 'api.serializers.UserSerializer', 'user': 'api.serializers.UserSerializer' } }
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48594918
upvote count: 1

http://stackoverflow.com/comment/84256106
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48629483
type: Comment
has text: so here we no need to specify whether its string or integer it will automatically picks based on the initialization?

http://stackoverflow.com/comment/84104887
comment on: http://stackoverflow.com/q/48553974
type: QuestionComment
has text: How do you run it and what does "not running" actually mean?
score: 0
type: Comment

http://stackoverflow.com/comment/84001552
type: QuestionComment
has text: What are `X` and `y`?
score: 1
comment on: http://stackoverflow.com/q/48503816
type: Comment

http://stackoverflow.com/comment/84260553
has text: The best library I found for maxima is `peakutils`: https://pypi.python.org/pypi/PeakUtils . It allows you to select sensitivity and threshold to make it robust to noise.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48631113
score: 0

http://stackoverflow.com/q/48632520
has body: I have a Django application which is using Django CMS. I had built custom plugins, pages, users etc. in the application using CMS. I want to export the CMS data from my application to another instance of the same application which doesn't have any cms related data. I am using the following command: python manage.py dumpdata cms djangocms_column djangocms_file djangocms_googlemap djangocms_link djangocms_picture djangocms_style djangocms_text_ckeditor djangocms_video &gt; cms_export.json --indent=2 I copied that file to the other app instance and tried to load it using the following command: python manage.py loaddata cms_export.json I got the following error: django.core.serializers.base.DeserializationError: Problem installing fixture '/cms_export.json': Page has no field named 'path' cms_export.json snippet: [{ "model": "cms.usersettings", "pk": 1, "fields": { "user": 2, "language": "en", "clipboard": 1 } }, { "model": "cms.usersettings", "pk": 2, "fields": { "user": 1, "language": "en", "clipboard": 7 } }, { "model": "cms.page", "pk": 4, "fields": { "path": "0004", "depth": 1, "numchild": 0, "created_by": "script", "changed_by": "xxxx", "parent": null, "creation_date": "2018-01-27T18:51:08.122Z", "changed_date": "2018-02-04T19:48:21.804Z", "publication_date": "2018-01-27T18:52:43.340Z", "publication_end_date": null, "in_navigation": true, "soft_root": false, "reverse_id": null, "navigation_extenders": null, "template": "base.html", "site": 1, "login_required": false, "limit_visibility_in_menu": null, "is_home": true, "application_urls": "", "application_namespace": null, "publisher_is_draft": true, "publisher_public": 5, "languages": "en", "revision_id": 0, "xframe_options": 0, "placeholders": [ 3, 9 ] } }, { "model": "cms.page", "pk": 5, "fields": { "path": "0005", "depth": 1, "numchild": 0, "created_by": "admin", "changed_by": "xxxx", "parent": null, "creation_date": "2018-01-27T18:52:43.345Z", "changed_date": "2018-02-04T19:48:21.792Z", "publication_date": "201…
type: AnsweredQuestion
score: 1
has title: Django CMS:: Deserialization Error :: page has no field named 'path'
accepted answer: http://stackoverflow.com/a/48636484
upvote count: 1
favorite count: 0
type: Question
answer count: 2
tagged with: django-cms
has answer: http://stackoverflow.com/a/48649188
possible better answer: http://stackoverflow.com/a/48649188
downvote count: 0
has answer: http://stackoverflow.com/a/48636484
tagged with: django
tagged with: python

http://stackoverflow.com/a/48630250
has comment: http://stackoverflow.com/comment/84257689
has body: Shuffle is shuffling the list l in place. You have multiple instances of that same list in the list of lists so they all get shuffled at the same time. To demonstrate, add a print in your loop: def init_par (pop_size): ''' generate the 1st generation of parents pop_size should be an positive integer number''' if not (isinstance(pop_size, int) and pop_size&gt;1): raise TypeError('bad operand type') else: par = [] l=list(range(1,11)) for i in range(pop_size): print i,l, par shuffle(l) par.append(l) return par Prints: 0 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [] 1 [9, 6, 5, 7, 2, 4, 3, 1, 8, 10] [[9, 6, 5, 7, 2, 4, 3, 1, 8, 10]] 2 [4, 5, 6, 2, 9, 3, 7, 8, 1, 10] [[4, 5, 6, 2, 9, 3, 7, 8, 1, 10], [4, 5, 6, 2, 9, 3, 7, 8, 1, 10]] [[6, 8, 7, 1, 5, 4, 9, 3, 2, 10], [6, 8, 7, 1, 5, 4, 9, 3, 2, 10], [6, 8, 7, 1, 5, 4, 9, 3, 2, 10]] Since each entry in par is just a view of the same list, when you shuffle one it seems to shuffle all of them. To fix, make a new list each time through the loop: def init_par (pop_size): ''' generate the 1st generation of parents pop_size should be an positive integer number''' if not (isinstance(pop_size, int) and pop_size&gt;1): raise TypeError('bad operand type') else: par = [] for i in range(pop_size): l=list(range(1,11)) # each one is a new list shuffle(l) par.append(l) return par The faster way would be to use sample vs shuffle like so: def init_par (pop_size): ''' generate the 1st generation of parents pop_size should be an positive integer number''' if not (isinstance(pop_size, int) and pop_size&gt;1): raise TypeError('bad operand type') else: l=range(1,11) return [sample(l, k=len(l)) for _ in range(pop_size)]
answers question: http://stackoverflow.com/q/48630181
has comment: http://stackoverflow.com/comment/84257520
score: 0
has comment: http://stackoverflow.com/comment/84257514
has comment: http://stackoverflow.com/comment/84257568
has comment: http://stackoverflow.com/comment/84257840
type: Answer

http://stackoverflow.com/comment/84160633
type: AnswerComment
comment on: http://stackoverflow.com/a/48563630
type: Comment
has text: OK, I try explain problem. If use `a = dataframe['close'].quantile([.1,.5,.4,.75,.8])` it return array with same legth as `[.1,.5,.4,.75,.8]` - so `5`. And column `close` have `7` rows (`dataframe = pd.DataFrame({'row':[2,0,8,1,7,4,5]})`). So there is logical problem - how get `5 items array` to `7 items array`, because each new column have `7 values` ? It is imposible - only solution is `5 values + 2xNaNs` for `7` values. So it is reason whay I need what you need instaed `10` in `dataframe = pd.DataFrame({'row':[2,0,8,1,7,4,5], 'expected':[10,10,10,10,10,10,10]})`
score: 0

http://stackoverflow.com/a/48586030
upvote count: 2
downvote count: 0
has body: For your given example, maybe is is an option to match the consecutive capitalized words until you encounter a space and a lower case character or the end of the string. ^(?:[A-Z][^A-Z]+?)+(?= [a-z]|$) Explanation from the beginning of the string ^ a non capturing group (?: match an uppercase character [A-Z] match not an uppercase character one or more times non greedy [A-Z]+? close capturing group )+ and repeat one or more times a positive lookahead (?= which asserts that what follows is a white space followed by a lowercase character [a-z] | or the end of the string $ close positive lookahead ) In this case the matching stops until you encounter a white space and a lowercase character, but you could for example extend the character class to [a-z&amp;] to stop matching when you encounter a white space and an ampersand.
score: 2
type: Answer
answers question: http://stackoverflow.com/q/48585330

http://stackoverflow.com/a/48535520
accepted answer of: http://stackoverflow.com/q/48534965
has comment: http://stackoverflow.com/comment/84094233
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48534965
has body: You can use below line to get all team pairs: matches = [pair.text for pair in driver.find_elements_by_css_selector("td&gt;a[href^='/soccer/germany/bundesliga/']") if pair.text] Output: ['FC Koln - Dortmund', 'Freiburg - Bayer Leverkusen', 'Hertha Berlin - Hoffenhei m', 'Mainz - Bayern Munich', 'Schalke - Werder Bremen', 'Wolfsburg - Stuttgart', 'B. Monchengladbach - RB Leipzig', 'Augsburg - Eintracht Frankfurt', 'Hamburger SV - Hannover', 'RB Leipzig - Augsburg', 'Bayer Leverkusen - Hertha Berlin', 'D ortmund - Hamburger SV', 'Eintracht Frankfurt - FC Koln', 'Hannover - Freiburg', 'Hoffenheim - Mainz', 'Bayern Munich - Schalke', 'Stuttgart - B. Monchengladbac h', 'Werder Bremen - Wolfsburg'] There are some hidden links in table. If you want to get those links also, try: matches = [pair.get_attribute('textContent') for pair in driver.find_elements_by_css_selector("td&gt;a[href^='/soccer/germany/bundesliga/']")]

http://stackoverflow.com/comment/91306547
comment on: http://stackoverflow.com/a/50011971
score: 2
type: AnswerComment
has text: i wonder, what is the use of app_name = "main" is? and how django uses this variable
type: Comment

http://stackoverflow.com/comment/84002019
comment on: http://stackoverflow.com/a/48503581
type: Comment
has text: I think the problem resides on my openssl version.. on the help I got only this:
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84120532
comment on: http://stackoverflow.com/q/48562470
type: Comment
has text: delete from existing list I'm running a for loop on that and the list has about 650,000 records the execution is very slow if i find one such occurrence have to remove all the elements that occurs with that user id and continue iterating the loop
score: 0
type: QuestionComment

http://stackoverflow.com/a/48574716
type: Answer
score: 0
has body: IDLE is an interface for running Python code. You can only enter Python statements in the shell. Python statements do not begin with '%'. I believe IPython uses '%' as an escape to run system commands. If so, your question would make more sense if 'IDLE' were replaced by 'IPython'. I believe the answer would still be 'No', but I don't know for sure. Try searching for IPython docs. Windows 10 now has 'Ubuntu on Windows' (or something like that) for running linux shell commands on Windows. I do not know more than this. Again, do a web search. If you install Git for Windows Git, a bash shell, compiled with mingw64, is included. I have used it a tiny bit. I don't know which unix utilities are included, or translated into Windows equivalents. I also don't know if it is available separately.
answers question: http://stackoverflow.com/q/48566080

http://stackoverflow.com/q/48503540
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84234950
accepted answer: http://stackoverflow.com/a/48583218
has comment: http://stackoverflow.com/comment/84000749
has body: I'm looking for a way to implement a partially undirect graph. This is, graphs where edges can be directed (or not) and with different type of arrow (>, *, #, etc.). My problem is that when I try to use undirect grpah from Networkx and stored arrow type as an attribute, I don't find an efficient way to tell networkx if that attribute (type arrorw) is from a to b or from b to a. Does anyone know how to handle this?
downvote count: 1
has comment: http://stackoverflow.com/comment/84000670
has answer: http://stackoverflow.com/a/48583218
favorite count: 0
possible better answer: http://stackoverflow.com/a/48504499
type: Question
has title: Partially undirect graphs in Networkx
tagged with: graph
answer count: 2
has answer: http://stackoverflow.com/a/48504499
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84005251
tagged with: networkx

http://stackoverflow.com/comment/84190140
type: QuestionComment
has text: Why is python-2.7 tagged?
comment on: http://stackoverflow.com/q/48596560
score: 0
type: Comment

pipeline
type: Tag
tag name: pipeline
tags question: http://stackoverflow.com/q/48507651
tags question: http://stackoverflow.com/q/48491566

http://stackoverflow.com/comment/84060142
has text: @SergGr: It's not possible to start with an irrational number. For any possible `Decimal` inputs to `+`, "enough precision" exists. `π` is not a possible `Decimal` value in the first place.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48530730

http://stackoverflow.com/a/55823303
type: Answer
answers question: http://stackoverflow.com/q/48610132
score: 1
downvote count: 0
upvote count: 1
has body: I encountered the same problem, then I found out that because I'm also using GPU for run other stuffs even it doesn't show on task manager (windows) using GPU. Maybe even things like (rendering videos, video encoding or play heavy workload game, coin mining...). If you think it's still using heavy GPU, just close it off and problem solve.

http://stackoverflow.com/q/48537028
tagged with: python
has comment: http://stackoverflow.com/comment/84069842
score: 15
favorite count: 0
has title: Selenium: How to use Headless Chrome on AWS?
has answer: http://stackoverflow.com/a/49809785
type: Question
has body: Today I saw the message UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead. I am willing to for for Chrome route. How do I install on AWS and run it on my remote AWS instance? I will be using selenium in Python.
upvote count: 15
has comment: http://stackoverflow.com/comment/84078427
answer count: 2
linked to: http://stackoverflow.com/q/46085270
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84078340
downvote count: 0
tagged with: selenium
tagged with: google-chrome-headless
has comment: http://stackoverflow.com/comment/84069878
has answer: http://stackoverflow.com/a/58985427

http://stackoverflow.com/a/48703155
has body: This is a matter for django's settings, not the model: settings doc. Check your TIME_INPUT_FORMATS in MyProject/MySite/settings.py and add this as necessary: TIME_INPUT_FORMATS = [ '%I:%M:%S %p', # 6:22:44 PM '%I:%M %p', # 6:22 PM '%I %p', # 6 PM '%H:%M:%S', # '14:30:59' '%H:%M:%S.%f', # '14:30:59.000200' '%H:%M', # '14:30' ] If the display of the time format on the changelist page is still wrong, check your LANGUAGE_CODE and USE_L10N settings.
type: Answer
upvote count: 18
accepted answer of: http://stackoverflow.com/q/48514222
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48514222
downvote count: 0
score: 18

http://stackoverflow.com/comment/84218595
score: 0
type: Comment
has text: Should I erase my question?
comment on: http://stackoverflow.com/a/48610759
type: AnswerComment

http://stackoverflow.com/a/48537995
score: 1
type: AcceptedAnswer
has body: Solution Inputs import pandas as pd import numpy as np df_1 = pd.DataFrame({'SPEED1':np.random.uniform(1,600,100)) df_2 = pd.DataFrame({'SPEED2':np.random.uniform(1,600,100)) Code To my mind a better approach would be to store your dfs into a list and enumerate over it for augmenting informations into your dfs to create a valid column: for idx, df in enumerate([df_1, df_2]): col = 'SPEED'+str(idx+1) df['valid'] = df[col] &lt;= 500 print(df_1) SPEED valid 0 516.395756 False 1 14.643694 True 2 478.085372 True 3 592.831029 False 4 1.431332 True You can then filter for valid or invalid with df_1[df_1.valid] or df_1[df_1.valid == False] It is a solution to fit your problem, see Another solution that may be more clean and Notes below for explanations you need. Another (better?) solution If it is possible for you re-think your code. Each DataFrame has one column speed, then name it SPEED: dfs = dict(df_1=pd.DataFrame({'SPEED':np.random.uniform(0,600,100)}), df_2=pd.DataFrame({'SPEED':np.random.uniform(0,600,100)})) It will allow you to do the following one liner: dfs = dict(map(lambda key_val: (key_val[0], key_val[1].assign(valid = key_val[1]['SPEED'] &lt;= 500)), dfs.items())) print(dfs['df_1']) SPEED valid 0 516.395756 False 1 14.643694 True 2 478.085372 True 3 592.831029 False 4 1.431332 True Explanations: dfs.items() returns a list of key (i.e. names) and values (i.e. DataFrames) map(foo, bar) apply the function foo (see this answer, and DataFrame assign) to all the elements of bar (i.e. to all the key/value pairs of dfs.items(). dict() cast the map to a dict. Notes About modify Notice that your function modify is not returning anything... I suggest you to have more readings on mutability and immutability in Python. This article is interesting. You can then test the following for instance: def modify(df): df=df[df.SPEED1&lt;0.5] #The change in df is on the scope of the function only, #it will not modify your input, return the df... return df #... and affect the output …
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48536802
answers question: http://stackoverflow.com/q/48536802
type: Answer
upvote count: 2

http://stackoverflow.com/q/48629989
possible better answer: http://stackoverflow.com/a/48630234
has title: Reshape dataframe to dataframe with unlimited rows and filling zeroes where no values
has comment: http://stackoverflow.com/comment/84256866
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48630063
tagged with: pandas
has body: Is there a way to reshape DataFrame to another with unrestricted rows. I just want a DataFrame with 3 columns, no matter how many rows is going to be in DataFrame? For example, letters = pd.DataFrame({'Letters' : ['A', 'B', 'C','D', 'E', 'F', 'G', 'H', 'I','J']}) Letters 0 A 1 B 2 C 3 D 4 E 5 F 6 G 7 H 8 I 9 J and I want to reshape it like this with filling zeroes, where there is no value. first second third A B C D E F G H I J 0 0 In numpy reshape method as far as I know you need to explicitly identify, how much columns and rows you want..
accepted answer: http://stackoverflow.com/a/48630063
tagged with: reshape
tagged with: dataframe
tagged with: python
score: 2
upvote count: 2
tagged with: numpy
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48630234

http://stackoverflow.com/comment/84142453
score: 0
comment on: http://stackoverflow.com/q/48572606
type: Comment
type: QuestionComment
has text: Sorry I misunderstood your question and assumed the check was for each row separately. Can you [edit](https://stackoverflow.com/posts/48572606/edit) your question to add your desired output?

http://stackoverflow.com/q/48554855
tagged with: pandas
tagged with: bokeh
has comment: http://stackoverflow.com/comment/84127790
type: Question
has comment: http://stackoverflow.com/comment/84123109
type: UnansweredQuestion
has title: Bokeh Multi line plots doesn't show
has comment: http://stackoverflow.com/comment/84128105
tagged with: python
has comment: http://stackoverflow.com/comment/84127555
has comment: http://stackoverflow.com/comment/84127816
has body: I have a dataframe like below data_date created_time order_number 0 2017-02-01 00:00 204 1 2017-02-01 10:00 85 2 2017-02-02 20:00 73 3 2017-02-02 13:00 79 4 2017-02-03 14:00 166 So what I want to do is to visualize the booking amount in hourly basis each day . The line plot will differ based on the data_date column, so there should be 3 lines on the graph. Here is the code I made with bokeh library source = ColumnDataSource(hourly_booking) colormap = CategoricalColorMapper(factors=hourly_booking['data_date'].unique(), palette=['red', 'green', 'blue']) p = figure(x_axis_label = 'Time (24-Hour)', y_axis_label = 'Amount of order') p.multi_line(xs='created_booking', ys='order_number', source=source, line_color=dict(field='data_date', transform=colormap), line_width=5, line_alpha=0.6, legend='data_date') output_file('graph.html') show(p) However the page goes blank so I don't know what went wrong with the codes. What should I do? Any suggestion would be appreciated :)
score: 0
answer count: 0

http://stackoverflow.com/comment/84214495
has text: Can you point me to a document or guide?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48599891
type: Comment

http://stackoverflow.com/comment/84045479
has text: I seem to remember a time when pip did not work in anaconda. The installation worked, but now it says `No module named 'azure.mgmt'` - I'll try to uninstall everything and give it another shot.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48525198
type: Comment

continuations
tag name: continuations
tags question: http://stackoverflow.com/q/48526687
type: Tag

http://stackoverflow.com/comment/84277213
type: Comment
has text: paste error _as text_ please
type: QuestionComment
comment on: http://stackoverflow.com/q/48640323
score: 0

http://stackoverflow.com/a/48547618
has comment: http://stackoverflow.com/comment/84091295
score: 1
has body: So what you are going to need here is browser.find_element_by_xpath('//a[contains(text(), 'Download file in csv format')]').click() An absolute xpath, with a lot of elements in it, is very sensitive to change.
type: Answer
accepted answer of: http://stackoverflow.com/q/48546675
has comment: http://stackoverflow.com/comment/84092219
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84091859
answers question: http://stackoverflow.com/q/48546675

http://stackoverflow.com/q/48524573
type: Question
tagged with: linux
has answer: http://stackoverflow.com/a/48548392
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/84043926
score: 0
answer count: 1
has title: Is there a best-practice way to implement a Python script that handles Windows and Linux environments differently?
has body: Apologies if this has been answered on here before, but I did some searching and was unable to find an answer. I'm taking over a Python application that runs on a remote Linux box, but need to do development locally on Windows. Naturally, I want the code I develop locally to match what gets deployed in production, but there are sections of the code that need to be handled differently between environments (due to library dependencies and OS minutiae). Right now I'm simply handling this via if statements and sys.platform like the following: if platform == "linux" and this works but seems to me like there would be a better way to implement it. Is there a more canonical or fault-tolerant way to do this?
has comment: http://stackoverflow.com/comment/84043916

http://stackoverflow.com/a/48594674
score: 12
downvote count: 0
has body: return stops the control flow of your function and returns back the flow. You may use yield here which will convert your function into a generator. For example: def posnegzero(nulist): for x in nulist: if x &gt; 0: yield "positive" elif x &lt; 0: yield "negative" else: yield "zero" It will yield the next result every time next() is called on the returned object: &gt;&gt;&gt; result = posnegzero([-20, 1, 2, -3, -5, 0, 100, -123]) &gt;&gt;&gt; next(result) 'negative' &gt;&gt;&gt; next(result) 'positive' &gt;&gt;&gt; next(result) 'positive' Or you may get all the result at once as: &gt;&gt;&gt; result = posnegzero([-20, 1, 2, -3, -5, 0, 100, -123]) &gt;&gt;&gt; list(result) ['negative', 'positive', 'positive', 'negative', 'negative', 'zero', 'positive', 'negative'] You can also iterate it using for loop. for loop repeatedly calls the next() method until it receives a StopIteration exception. For example: for result in posnegzero([-20, 1, 2, -3, -5, 0, 100, -123]): print(result) # which will print negative positive positive negative negative zero positive negative For more information on yield, please refer: What does the “yield” keyword do?
answers question: http://stackoverflow.com/q/48594611
upvote count: 12
accepted answer of: http://stackoverflow.com/q/48594611
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/84023010
type: QuestionComment
has text: Haha, I want static types too :)
score: 1
comment on: http://stackoverflow.com/q/48514105
type: Comment

http://stackoverflow.com/q/48615037
score: 0
tagged with: deep-learning
answer count: 1
has answer: http://stackoverflow.com/a/48615209
has body: I want to predict images with the nets from tf slim. But I get random results for inceptionv3. For resnet50 everything works fine. resnet50: import tensorflow as tf import cv2 import numpy as np import tensorflow.contrib.slim.nets as nets slim = tf.contrib.slim with tf.device('/gpu:1'): inputs = tf.placeholder(tf.float32, shape=[None,299,299,3]) with slim.arg_scope(nets.resnet_v1.resnet_arg_scope()): features,net = nets.resnet_v1.resnet_v1_50(inputs=inputs, num_classes=1000) saver = tf.train.Saver() config = tf.ConfigProto() config.gpu_options.allow_growth = True config.allow_soft_placement=True with tf.Session(config=config) as sess: saver.restore(sess, 'weights/resnet_v1_50.ckpt') img = cv2.imread('images/dog_ball.jpg') img = cv2.resize(img,(299,299)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = img/255.0 curr_features, curr_net = sess.run([features, net], feed_dict={inputs: [img,img, img]}) for curr_feature in curr_features: f_ind = np.argsort(curr_feature[0][0])[-4:] # resnet50v1 for i in f_ind: print i print ' ' But if I try inception_v3, it's not working. The results are not even the same, even if the images are the same. First I thought, the weights didn't load properly, but everything looks fine. inceptionv3: import tensorflow as tf import cv2 import numpy as np import tensorflow.contrib.slim.nets as nets slim = tf.contrib.slim with tf.device('/gpu:1'): inputs = tf.placeholder(tf.float32, shape=[None,299,299,3]) with slim.arg_scope(nets.inception.inception_v3_arg_scope()): features,net = nets.inception.inception_v3(inputs=inputs, num_classes=1001) saver = tf.train.Saver() config = tf.ConfigProto() config.gpu_options.allow_growth = True config.allow_soft_placement=True with tf.Session(config=config) as sess: saver.restore(sess, 'weights/inception_v3.ckpt') img = cv2.imread('images/dog_ball.jpg') img = cv2.resize(img,(299,299)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = img/255.0 curr_features, curr_net = sess.run([features, net], feed_dict={inputs: …
tagged with: tensorflow
type: Question
tagged with: tensorflow-slim
type: UnansweredQuestion
has title: tf slim inceptionv3 gives wrong output
tagged with: resnet
tagged with: python

http://stackoverflow.com/comment/84181153
score: 0
type: AnswerComment
has text: this didn't work either, the `Popen` fails to run a multi line string
type: Comment
comment on: http://stackoverflow.com/a/48591522

http://stackoverflow.com/q/48492242
score: 0
has title: python syntax error (s for s in X if not in Z)
answer count: 1
accepted answer: http://stackoverflow.com/a/48492266
has comment: http://stackoverflow.com/comment/83977637
has answer: http://stackoverflow.com/a/48492266
type: Question
has body: ok this is not my code it's a code from GitHub there is a syntax error at this line unique_items = np.unique(df_clean[item_columns].values).tolist() items_headers = ['item-' + s for s in unique_items if not in consumables] I think it's a simple error but i am pretty noob in python (consumables is defined at the top)
type: AnsweredQuestion
tagged with: anaconda
tagged with: python
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/83977700
has comment: http://stackoverflow.com/comment/83977704
tagged with: python-2.7

http://stackoverflow.com/q/48557373
has body: In the following piece of code I 'add on' a class to some base class. The idea is to use this pattern to 'add on' classes as needed, but I am not sure if this is good pythonic code or not... class Driver(object): def __init__(self): self.var=1 class Extra(object): def __init__(self, driver): self.driver = driver def foo(self): print self.driver.var driver = Driver() driver.extra = Extra(driver) driver.extra.foo() The general idea is to use this pattern in py.test so I can pass the object easily around to other functions in the tests like foo(driver) instead of foo(driver, extra1, extra2, extra3)
score: 0
has comment: http://stackoverflow.com/comment/84110582
has comment: http://stackoverflow.com/comment/84110847
has comment: http://stackoverflow.com/comment/84110530
has comment: http://stackoverflow.com/comment/84110876
type: Question
has comment: http://stackoverflow.com/comment/84110690
has comment: http://stackoverflow.com/comment/84110985
answer count: 0
has comment: http://stackoverflow.com/comment/84110767
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84111332
has title: Is this a good design of creating a pythonic 'add-on'?

http://stackoverflow.com/comment/84291113
comment on: http://stackoverflow.com/a/48636313
has text: the last (weird one) doesn't give the correct answer. I'm going to post some speed test results to show you how I tested it. Turns out, OP's code was the fastest.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48577236
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48577136
has body: You can use enumerate if the return value is their index. your_list = ['sathya','varna','summi'] Method 1 def return_value(key): for index, key_ in enumerate(your_list, start=-5): if key == key_: return index return "Not found" print(return_value('sathya')) # return -5 print(return_value('invalid item')) # return not found Method 2(Using Dict Comprehension) def return_value(key): return { value: index for index, value in enumerate(your_list ,start=-5) }.get(key, "Not found") print(return_value('sathya')) # return -5 print(return_value('invalid item')) # return not found
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48577136

http://stackoverflow.com/comment/84281367
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48642444
type: QuestionComment
has text: Are you creating this list of dictionaries? You might want to remove that last dictionary inside of the list because you're trying to store two different things in one list

http://stackoverflow.com/comment/84080349
type: QuestionComment
has text: @VikasDamodar Spark 2.2
comment on: http://stackoverflow.com/q/48542501
score: 0
type: Comment

http://stackoverflow.com/comment/84252032
has text: From the docs: `a.reshape(shape, order='C')`; the `reshape` method accept either a shape tuple or its *args. IT's fine to suggest that `reshape` was the problem, but you should demonstrate that it can produce the given error message.
comment on: http://stackoverflow.com/a/48620708
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48585082
accepted answer of: http://stackoverflow.com/q/48584403
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/48584403
type: Answer
has comment: http://stackoverflow.com/comment/84258675
has comment: http://stackoverflow.com/comment/84166902
downvote count: 0
type: AcceptedAnswer
has body: pandas has padding ability, which is what you are describing, but you would have to cast your array as a float because numpy int arrays cannot hold np.nan values. import pandas as pd import numpy as np upper = 10 lower = 1 v=np.array([1,-77,3,4,5,13213,6,7,8,1024]) s = pd.Series(v) s[~((s&gt;lower) &amp; (s&lt;upper))] = np.nan s = s.fillna(method='pad') # at this point the series is padded but the values are floats instead of # ints, you can cast back to an int array if you wish v2 = s.values.astype(int) v2 # outputs: array([1, 1, 3, 4, 5, 5, 6, 7, 8, 8]) update: a numpy only solution # first we identify elements that are out of bounds and need to be filled from the data mask = (v&lt;lower) | (v&gt;upper) oob = np.where(mask)[0] # for each oob value, we calculate the index that provides the fill-value using a forward fill or backward fill def fillidx(i, mask_oob): try: if i == 0 or np.all(mask_oob[:i]): # all elements from start are oob raise IndexError() n = -1 * (1 + np.argmin(mask_oob[:i][::-1])) except (IndexError): n = 1 + np.argmin(mask_oob[i+1:]) return i + n fill = [fillidx(i, mask) for i in oob] v[mask] = v[fill] print(v) with the first test array v = np.array([1,-77,3,4,5,13213,6,7,8,1024]), the following is output: [1 1 3 4 5 5 6 7 8 8] with the second test array v = np.array([-7,1,2,3,-77]) the following is output: [1 1 2 3 3] with an array where consecutive values are out of bounds and the first few elements are also out of bounds, i.e. v = np.array([-200,20,1,-77,3,4,5,13213,-200,6,7,8,1024]) we get the following output: [1 1 1 1 3 4 5 5 5 6 7 8 8]

http://stackoverflow.com/q/48616387
type: UnansweredQuestion
answer count: 1
has title: Add index weekday to pandas dataframe
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48616439
tagged with: python
has body: I have a following data frame, which is indexed by date_time: date_time rsvp_limit rsvp_yes dropout 2017-11-30 19:00:00 240 229 0.045833 2017-10-19 19:00:00 300 300 0.000000 2017-06-26 19:00:00 300 300 0.000000 When I try to add weekday column to it, somehow it does not seem to succeed: weekday_dropoouts = events['dropout'].copy() weekday_dropoouts['weekday'] = weekday_dropoouts.index.weekday_name weekday_dropoouts[:3] Gives me: date_time 2017-11-30 19:00:00 0.0458333 2017-10-19 19:00:00 0 2017-06-26 19:00:00 0 Name: dropout, dtype: object What I'm trying achieve is to create a bar plot per weekday i.e. basically I'm trying to figure out which weekday the event experiences the highest drop out. I'm sure I'm missing something fundamental here, but I can't figure out what it is.
type: Question

http://stackoverflow.com/comment/83984130
has text: Just out of curiosity, what do you mean by outgrow my solution? Is threading a more CPU intensive process or is it only suitable for a small number or functions to be efficient or something? I'm new to this specific concept so I'm learning as I go.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48494269

http://stackoverflow.com/q/48516018
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: anaconda
has comment: http://stackoverflow.com/comment/84186983
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84107935
tagged with: python
has comment: http://stackoverflow.com/comment/84053978
has body: I get this error while running a sample code from Google Cloud API, but i assume this has nothing related to the API. File "/Users/MyName/anaconda3/lib/python3.6/imp.py", line 271, in find_module "not {}".format(type(path))) RuntimeError: 'path' must be None or a list, not &lt;class'_frozen_importlib_external._NamespacePath'&gt; Here is the Python code that i run from google.cloud import language from google.cloud.language import enums from google.cloud.language import types import six import sys def entity_sentiment_text(text): """Detects entity sentiment in the provided text.""" client = language.LanguageServiceClient() if isinstance(text, six.binary_type): text = text.decode('utf-8') document = types.Document( content=text.encode('utf-8'), type=enums.Document.Type.PLAIN_TEXT) # Detect and send native Python encoding to receive correct word offsets. encoding = enums.EncodingType.UTF32 if sys.maxunicode == 65535: encoding = enums.EncodingType.UTF16 result = client.analyze_entity_sentiment(document, encoding) for entity in result.entities: print('Mentions: ') print(u'Name: "{}"'.format(entity.name)) for mention in entity.mentions: print(u' Begin Offset : {}'.format(mention.text.begin_offset)) print(u' Content : {}'.format(mention.text.content)) print(u' Magnitude : {}'.format(mention.sentiment.magnitude)) print(u' Sentiment : {}'.format(mention.sentiment.score)) print(u' Type : {}'.format(mention.type)) print(u'Salience: {}'.format(entity.salience)) print(u'Sentiment: {}\n'.format(entity.sentiment)) I did some research, some people suggest to add init.py, but i do have it in my directory. I wonder is there something wrong with spyder? While i run this file on Terminal using python to call the file, it works fine. Here is the error points to: def find_module(name, path=None): """**DEPRECATED** Search for a module. If path is omitted or None, search for a built-in, frozen or special module and continue search in sys.path. The module name cannot contain '.'; to search …
score: 0
answer count: 0
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/84058538
tagged with: spyder
has comment: http://stackoverflow.com/comment/84058704
has title: Anaconda Spyder RuntimeError (imp.py line 271)

http://stackoverflow.com/comment/84191563
has text: Why are you not using [`form.save()`](https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#the-save-method) to save to the model?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48597139

http://stackoverflow.com/comment/84003614
score: 0
has text: @A.Vidor No, I don't want to wait for the function to complete. Because the function has to execute for a long period time and it cause 504 Gateway timeot error.
comment on: http://stackoverflow.com/q/48501803
type: Comment
type: QuestionComment

http://stackoverflow.com/a/62410484
score: 0
answers question: http://stackoverflow.com/q/48539500
accepted answer of: http://stackoverflow.com/q/48539500
type: AcceptedAnswer
has body: Access database files (.mdb, .accdb) are not architecture-specific; there is no such thing as a "32-bit .mdb file" or a "64-bit .accdb file". There are 32-bit and 64-bit versions of the Access Database Engine (and drivers, etc.) but the database files they produce are identical. You are receiving the Cannot open a database created with a previous version of your application. error because your version of the Access Database Engine no longer supports the version (not "bitness") of the database file you are trying to use. If you are using the Access Database Engine for Access_2013 or newer then your file format must be for Access_97 or older. If you are using the Access Database Engine from Access_2010 then the format of the file you are trying to use is super-old (likely Access_2.0). As you seem to have noticed, we can still work with older database files using the legacy "Jet" database engine that ships with Windows (Microsoft Access Driver (*.mdb)) but it is a 32-bit driver and there is no 64-bit version.
type: Answer
has comment: http://stackoverflow.com/comment/113496851

http://stackoverflow.com/q/48614165
tagged with: python
has title: Introsort in Python, can anybody point out my mistake?
has comment: http://stackoverflow.com/comment/84225508
has comment: http://stackoverflow.com/comment/84230960
has comment: http://stackoverflow.com/comment/84259171
type: AnsweredQuestion
answer count: 2
has body: Trying to implement Introsort using Python. The pseudo-code given is: 1 n ←|A| 2 if n ≤ 1 3 return 4 elseif d = 0 5 Heap-Sort(A) 6 else 7 p ← Partition(A) // Partitions A and returns pivot position 8 Intro-Sort(A[0:p],d−1) 9 Intro-Sort(A[p+1:n],d−1) My source code is: import math def introSort(a,d): n = len(a) if n &lt;= 1: return elif d == 0: heapSort(a) else: p = partition(a) a1 = a[0:p] a2 = a[p+1:n] introSort(a1, d-1) introSort(a2, d-1) a = a1 + [a[p]] + a2 def heapSort (a): END = len(a) for k in range (math.floor(END/2) - 1, -1, -1): heapify(a, END, k) for k in range(END, 1, -1): swap(a, 0, k-1) heapify(a, k-1, 0) def partition(a): x = a[len(a) - 1] i = -1 for j in range(0, len(a) - 2): if a[j] &lt;= x: i = i + 1 swap(a, i, j) swap(a, i + 1, len(a) - 1) return i + 1 def swap(a, i, j): tmp = a[i] a[i] = a[j] a[j] = tmp def heapify(a,iEnd,iRoot): iL = 2*iRoot + 1 iR = 2*iRoot + 2 if iR &lt; iEnd: if (a[iRoot] &gt;= a[iL] and a[iRoot] &gt;= a[iR]): return else: if(a[iL] &gt; a[iR]): j = iL else: j = iR swap(a, iRoot, j) heapify(a, iEnd, j) elif iL &lt; iEnd: if (a[iRoot] &gt;= a[iL]): return else: swap(a, iRoot, iL) heapify(a,iEnd,iL) else: return a = [3,5,6,1,23,521,6243,632,123,53,62,421,15,672,7,435,21] introSort(a,2) print(a) The result given was wrong: &gt;python introsort.py [3, 5, 6, 1, 15, 7, 21, 632, 123, 53, 62, 421, 23, 672, 521, 435, 6243] It seems that it stopped straight after partition and the sorting on sublists was not working. It was clear that 21 was the pivot and the partition worked perfectly. Can anybody point out my mistake? Thank you very much!
upvote count: 3
possible better answer: http://stackoverflow.com/a/48617338
downvote count: 0
tagged with: introsort
has answer: http://stackoverflow.com/a/48617338
linked to: http://stackoverflow.com/q/986006
has comment: http://stackoverflow.com/comment/84225255
has comment: http://stackoverflow.com/comment/84262067
favorite count: 0
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/48631103
has comment: http://stackoverflow.com/comment/84229509
tagged with: algorithm
has comment: http://stackoverflow.com/comment/84250390
has answer: http://stackoverflow.com/a/48631103
has comment: http://stackoverflow.com/comment/84225343

http://stackoverflow.com/q/48602313
type: Question
has title: Is it possible to use a variable such as "['time']['updated']" to parse JSON?
accepted answer: http://stackoverflow.com/a/48602418
has answer: http://stackoverflow.com/a/48602418
answer count: 1
has comment: http://stackoverflow.com/comment/84201342
has comment: http://stackoverflow.com/comment/84201253
has comment: http://stackoverflow.com/comment/84201206
tagged with: python
type: AnsweredQuestion
tagged with: syntax
has body: Ok, json_tree is a variable that contains something that looks like this: json_tree = "['time']['updated']" Can you pass it as a variable.... hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' } req = urllib.request.Request(url, headers=hdr) readdata = urllib.request.urlopen(req) json_data = readdata.read() json_dict = json.loads(json_data) like so?? print(json_dict[json_tree]) My purpose is to pass one of many json_tree values from a .ini into the class that contains the above code. If this is a bad plan, what could work, instead? Thank you!
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84201411
linked to: http://stackoverflow.com/q/48629461
has comment: http://stackoverflow.com/comment/84201207
tagged with: parsing

http://stackoverflow.com/q/48561644
score: -2
has title: Is there a simple way to convert a list of integers to a formatted string in Python?
has comment: http://stackoverflow.com/comment/84118954
linked to: http://stackoverflow.com/q/42841514
accepted answer: http://stackoverflow.com/a/48562009
possible better answer: http://stackoverflow.com/a/48561792
type: AnsweredQuestion
answer count: 2
has body: I am writing a program which generates a list of integers, for example: [2, 5, 6, 7, 8, 9, 10, 15, 18, 19, 20] This list can be very long, but it contains many consecutive values, as seen in this example. In order to store it (in a database), I would like to convert it to a formatted string, in the following format: "2,5-10,15,18-20" I already have in mind a solution, which is iterating through the whole list to detect consecutive values and building the string. My question is: is there another, simpler way of doing this conversion in Python?
upvote count: 1
duplicate of: http://stackoverflow.com/q/42841514
favorite count: 0
tagged with: tostring
has answer: http://stackoverflow.com/a/48562009
tagged with: list
has comment: http://stackoverflow.com/comment/84118997
type: Question
has answer: http://stackoverflow.com/a/48561792
downvote count: 3
tagged with: python

http://stackoverflow.com/a/48607713
accepted answer of: http://stackoverflow.com/q/48607640
answers question: http://stackoverflow.com/q/48607640
has body: I believe this is what you are looking for. To check whether a value is an integer (even if in a float array), then you can test x == int(x). import numpy as np arr = np.array([1, 3, 67, 8, 7.5]) print(arr, type(arr)) for x in arr: if x != int(x): y = x.astype(int) print(y, type(y)) else: print(str(int(x)) + ' is already an integer') # [ 1. 3. 67. 8. 7.5] &lt;class 'numpy.ndarray'&gt; # 1 is already an integer # 3 is already an integer # 67 is already an integer # 8 is already an integer # 7 &lt;class 'numpy.int32'&gt;
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84174466
has text: So essentially this question was solved by another means and the answer did not help you? That means it would not help anyone else. Perhaps you want to delete it.
type: AnswerComment
comment on: http://stackoverflow.com/a/48588634
score: 0
type: Comment

http://stackoverflow.com/q/48616731
answer count: 1
score: 4
tagged with: psycopg2
has title: Installting psycopg2 package for python 3.5 on unix
favorite count: 0
type: Question
tagged with: postgresql
tagged with: python
upvote count: 4
tagged with: python-3.x
tagged with: setup.py
has answer: http://stackoverflow.com/a/48617760
type: UnansweredQuestion
has body: I am trying to install package psycopg2 to connect with postgres database but getting below error on running this command python3.5 /usr/local/bin/psycopg2-2.7.3.2/setup.py install *running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.5 creating build/temp.linux-x86_64-3.5/psycopg gcc*** command here In file included from psycopg/psycopgmodule.c:27: ./psycopg/psycopg.h:30:2: error: #error "Psycopg requires PostgreSQL client library (libpq) >= 9.1"* Current environment already have python 2.4, we installed another version 3.5. Now both versions are present. Since there no direct connectivity with external net, I got the file for psycopg2 package and installing using setup.py Please suggest, what I am missing here and how can I resolve this. Note that cannot connect to internet as this is a close environment so cannot use PIP for installation of package. My main aim is to connect to postgres database.
downvote count: 0

http://stackoverflow.com/q/48503737
has body: Edit: seems to be a known issue (https://github.com/SciTools/cartopy/issues/803#issuecomment-272286945) with certain map projections. For some reason, the NaturalEarth oceans cover the continents, as shown in the example below. If I plot 'physical', 'land' it behaves as expected (land is filled), but for 'physical', 'ocean' I would expect the opposite, but instead everything is filled. Does anyone know why this happens, and/or how it is possible to fill only the oceans? I also tried ax.add_feature(cartopy.feature.OCEAN), but then Cartopy crashes (......) import cartopy import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as pl projection = ccrs.LambertConformal(central_longitude=4.9, central_latitude=52) ax = pl.subplot(121, projection=projection) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', edgecolor='face', facecolor='g')) ax.set_extent([-8, 17, 42, 60], ccrs.PlateCarree()) ax = pl.subplot(122, projection=projection) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'ocean', '50m', edgecolor='face', facecolor='g')) ax.set_extent([-8, 17, 42, 60], ccrs.PlateCarree()) EDIT Seems to be a projection issue; with PlateCarree() it works as expected: import cartopy import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as pl projection = ccrs.LambertConformal(central_longitude=4.9, central_latitude=52) ax = pl.subplot(221, projection=projection) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', edgecolor='face', facecolor='g')) ax.set_extent([-8, 17, 42, 60], ccrs.PlateCarree()) ax = pl.subplot(222, projection=projection) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'ocean', '50m', edgecolor='face', facecolor='g')) ax.set_extent([-8, 17, 42, 60], ccrs.PlateCarree()) projection = ccrs.PlateCarree() ax = pl.subplot(223, projection=projection) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', edgecolor='face', facecolor='g')) …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84003087
tagged with: python
has comment: http://stackoverflow.com/comment/84006739
answer count: 0
score: 2
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
tagged with: cartopy
has title: Cartopy oceans cover land

http://stackoverflow.com/q/48639320
has comment: http://stackoverflow.com/comment/84275325
downvote count: 1
favorite count: 0
has body: I want to accept an argument with an equals sign in it: my_nintendo_news = Website('https://mynintendonews.com', href = re.compile('https://mynintendonews.com/2018/'), "C:/Users/charl/Pictures/toad_small_60x60.png", "C:/Users/charl/Pictures/toad_small_60x60_bw.png" ) but I keep getting SyntaxError: positional argument follows keyword argument how can I avoid this? I need to use href = re.compile('https://mynintendonews.com/2018/') as an argument in another function, and I can't do that as a string (and I've heard using eval() is bad?)
has title: How to use an equals sign in an argument for a function in python without it being recognised as introducing a keyword argument?
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48639765
has answer: http://stackoverflow.com/a/48639443
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84275234
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/84256866
score: 0
has text: So you want to spread it over three columns?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48629989

http://stackoverflow.com/a/48573440
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48573371
type: Answer
accepted answer of: http://stackoverflow.com/q/48573371
has body: You shouldn't have to write a different serializer for every view. Instead you can use several of their features to achieve what you want: 1) For creation using one single field, mark field2 and field3 as read only. This way they won't be considered when validating the input data when you create the model. 2) To decide which fields to show depending on some parameters of the input in the view, or different views, you can dynamically modify the fields of the serializer: class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name)
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48491832
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/48491493
downvote count: 1
has comment: http://stackoverflow.com/comment/83976905
has body: Are you looking for z=[[534],[345]?? Since the arrays start counting at 0?
type: Answer

http://stackoverflow.com/comment/84248996
has text: do you know why the dataframe is not creating the columns. this is basically what I am doing https://gist.github.com/mvaz/2006493
comment on: http://stackoverflow.com/q/48625141
score: 0
type: Comment
type: QuestionComment

logging
tags question: http://stackoverflow.com/q/48642111
tags question: http://stackoverflow.com/q/48517735
tags question: http://stackoverflow.com/q/48493487
tags question: http://stackoverflow.com/q/48550230
tags question: http://stackoverflow.com/q/48610824
tags question: http://stackoverflow.com/q/48531730
tags question: http://stackoverflow.com/q/48578648
tag name: logging
tags question: http://stackoverflow.com/q/48643243
tags question: http://stackoverflow.com/q/48635325
tags question: http://stackoverflow.com/q/48518413
tags question: http://stackoverflow.com/q/48515473
tags question: http://stackoverflow.com/q/48501676
tags question: http://stackoverflow.com/q/48628648
tags question: http://stackoverflow.com/q/48521754
tags question: http://stackoverflow.com/q/48587447
tags question: http://stackoverflow.com/q/48644054
tags question: http://stackoverflow.com/q/48545725
tags question: http://stackoverflow.com/q/48618974
tags question: http://stackoverflow.com/q/48638730
tags question: http://stackoverflow.com/q/48624719
tags question: http://stackoverflow.com/q/48641406
tags question: http://stackoverflow.com/q/48633847
type: Tag
tags question: http://stackoverflow.com/q/48542738
tags question: http://stackoverflow.com/q/48548937

http://stackoverflow.com/q/48540867
has body: I have html in a list called html. html = [u' \r\n\r\n \r\n\r\n \r\nFrom:\r\n\r\n\r\n\r\n'] I parse it through beautifulsoup like so: for i in email: soup = BeautifulSoup(i, "html.parser") for i in soup(text=lambda text: isinstance(text, Comment)): i.extract() scrape_selected_tags = soup.find_all(["a", "abbr", "acronym", "address", "b", "big", "br", "caption", "cite", "code", "datalist", "dd", "dfn", "dir", "dl", "dt", "div", "em", "figcaption", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "i", "img", "iframe", "label", "legend", "li", "mark", "ol", "p", "pre", "q", "small", "source", "strike", "strong", "span", "sub" , "sup", "table", "tbody", "td", "th", "time", "title", "tt", "tr", "u", "ul", "video", "wbr"], recursive = False) However, it seems to be duplicating the output? This is what I get when i print scrape_selected_tags: [ \n \nFrom:\n , \nFrom:\n , From:, From:, ] Does anyone know why this is happening and how to stop this?
has comment: http://stackoverflow.com/comment/84076902
type: Question
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/84076958
tagged with: python
has title: BeautifulSoup duplicated find_all
has comment: http://stackoverflow.com/comment/84076996
has comment: http://stackoverflow.com/comment/84076924
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84076856
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84077038

http://stackoverflow.com/q/48568994
type: Question
has comment: http://stackoverflow.com/comment/84134207
tagged with: python
tagged with: counting
answer count: 1
has title: print(i, end = ",") wont print the last i
has comment: http://stackoverflow.com/comment/84134170
accepted answer: http://stackoverflow.com/a/48569009
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48569009
has comment: http://stackoverflow.com/comment/84134197
has body: I would like to take a number and print all even numbers up to and including the number, here's my current code, def print_upto(number): for i in range(0, int(number)): if(i % 2 == 0): print(i, end = ',') my issue is that when I put print_upto(50) it prints from 0 all the way to 48, not 50. I am not sure how to get it to print 50, I have tried adding elif(i == number) and (number % 2 == 0): print(number) however, this doesn't work either. Thanks in advance

cql
tags question: http://stackoverflow.com/q/48576496
type: Tag
tag name: cql

http://stackoverflow.com/comment/84141256
type: QuestionComment
comment on: http://stackoverflow.com/q/48507879
has text: I could print in the mininet-wifi, but I would like to get it inside a text file, so I could make use of the data.
score: 1
type: Comment

http://stackoverflow.com/q/48536058
has title: Matching strings in a column of a data frame with the strings in a column of another data frame using R or Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84067874
has comment: http://stackoverflow.com/comment/84067384
linked to: http://stackoverflow.com/q/5963269
has answer: http://stackoverflow.com/a/48539384
downvote count: 0
score: 6
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/84068277
type: Question
tagged with: string-matching
tagged with: http://stackoverflow.com/tag/r
possible better answer: http://stackoverflow.com/a/48536382
accepted answer: http://stackoverflow.com/a/48540908
has answer: http://stackoverflow.com/a/48541203
has body: I am trying to match strings in a column of a data frame with the strings in a column of another data frame and map the corresponding values. The number of rows are different for both data frames df1 = data.frame(name = c("(CKMB)Creatinine Kinase Muscle &amp; Brain", "24 Hours Urine for Sodium", "Antistreptolysin O Titer", "Blood group O", lonic_code = c("27816-8-O", "27816-8-B", "1869-7", "33914-3") df2 = data.frame(Testcomponents = c("creatinine", "blood", "potassium")) Expected output Test Components lonic_code creatinine 27816-8-O blood 1869-7 potassium NA
has comment: http://stackoverflow.com/comment/84068279
has answer: http://stackoverflow.com/a/48540908
has answer: http://stackoverflow.com/a/48536382
has comment: http://stackoverflow.com/comment/84067252
tagged with: python
upvote count: 6
answer count: 4
has comment: http://stackoverflow.com/comment/84067582

http://stackoverflow.com/comment/84005796
type: AnswerComment
score: 0
has text: If anyone is interested in the inner workings of the functions just leave a comment
comment on: http://stackoverflow.com/a/48505869
type: Comment

http://stackoverflow.com/a/48601213
has comment: http://stackoverflow.com/comment/84199042
answers question: http://stackoverflow.com/q/48601018
has comment: http://stackoverflow.com/comment/84199114
accepted answer of: http://stackoverflow.com/q/48601018
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: What you want is the event.unicode attribute: if event.unicode == "!": print("!")
has comment: http://stackoverflow.com/comment/84199163

http://stackoverflow.com/q/48605331
has body: The shape of my data is (1920,60,2). Assume the batch size is 128, expected the batch data shape will be (128,60,2). but while using tf.train.batch, I got (128,1920,60,2), does that mean I have to reshape the data first? tf_X_train = tf.constant(X_train) # type(X_train):numpy.cdarray tf_Y_train = tf.constant(Y_train) tf_batch_xs, tf_batch_ys = tf.train.batch([tf_X_train, tf_Y_train], batch_size = 128, capacity = 5000) with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) batch_xs, batch_ys = sess.run([tf_batch_xs, tf_batch_ys]) print (batch_xs.shape ) got (128,1920,60,2) as output. Another question, tf.train.batch should input tensor, but why does it still work while I input numpy array?
has title: got wrong shape while using tf.train.batch
tagged with: tensorflow
favorite count: 0
type: Question
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48607473
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48607473
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/84246137
has text: it totally depends on the server you are hitting. That's the thing, you don't know how to crawl a site until you've done it. Another solution would be to contact the site and tell them you want to crawl so they can tell how to do it (most certainly they will forbid it).
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48614548
type: QuestionComment

kraken.com
tags question: http://stackoverflow.com/q/48490744
type: Tag
tag name: kraken.com

http://stackoverflow.com/comment/84052684
comment on: http://stackoverflow.com/q/48525338
score: 0
type: Comment
has text: The boto3 client.get_object() method supports a Range parameter. You can use it to request a range of bytes e.g. "bytes=1024-2048".
type: QuestionComment

http://stackoverflow.com/q/48585856
type: Question
has comment: http://stackoverflow.com/comment/84168691
upvote count: 5
has comment: http://stackoverflow.com/comment/84168994
has comment: http://stackoverflow.com/comment/84168609
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6501121
has body: According to Difference between exit() and sys.exit() in Python, the preferred way to exit from a Python application is to use sys.exit(). Python's documentation states that exit() should only be used to exit from the interactive shell. The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs. While the documentation warns against using constants from the site module, it doesn't explain why we shouldn't use them. Why shouldn't exit() be used in Python applications?
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/84168615
has title: Why shouldn't I use exit() in Python programs?
has answer: http://stackoverflow.com/a/48588489
has comment: http://stackoverflow.com/comment/84168631
tagged with: exit
downvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/19747371
favorite count: 0

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/48520393
tags question: http://stackoverflow.com/q/48620803
tags question: http://stackoverflow.com/q/48575854
tags question: http://stackoverflow.com/q/48645682
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/48489053

django-views
tags question: http://stackoverflow.com/q/48568959
tags question: http://stackoverflow.com/q/48637178
tags question: http://stackoverflow.com/q/48601660
tags question: http://stackoverflow.com/q/48535543
tags question: http://stackoverflow.com/q/48501279
tags question: http://stackoverflow.com/q/48571418
tags question: http://stackoverflow.com/q/48518194
tags question: http://stackoverflow.com/q/48559491
tags question: http://stackoverflow.com/q/48512876
tags question: http://stackoverflow.com/q/48490026
tags question: http://stackoverflow.com/q/48641130
tags question: http://stackoverflow.com/q/48508782
tags question: http://stackoverflow.com/q/48610255
tags question: http://stackoverflow.com/q/48573306
tag name: django-views
tags question: http://stackoverflow.com/q/48534047
tags question: http://stackoverflow.com/q/48506031
tags question: http://stackoverflow.com/q/48572581
tags question: http://stackoverflow.com/q/48605384
type: Tag
tags question: http://stackoverflow.com/q/48524468
tags question: http://stackoverflow.com/q/48595913
tags question: http://stackoverflow.com/q/48607309
tags question: http://stackoverflow.com/q/48614671
tags question: http://stackoverflow.com/q/48533060
tags question: http://stackoverflow.com/q/48493745
tags question: http://stackoverflow.com/q/48532194

http://stackoverflow.com/comment/84005118
has text: Ladies and Gentlemen, this human is about to quit Python because they don't like indentation. Thank you.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48505498

http://stackoverflow.com/q/48507321
tagged with: python
upvote count: 7
tagged with: opencv
has answer: http://stackoverflow.com/a/49943458
answer count: 2
has answer: http://stackoverflow.com/a/49947515
score: 7
downvote count: 0
favorite count: 0
type: Question
has title: How to specify a custom output size in cv2.pyrDown() or pyrUp() method
type: UnansweredQuestion
has body: I want to explicitly specify the output size of the image when applying cv2.pyrDown() on images. def gaussian_pyramid(image, scale=1.5, minSize=(30, 30)): yield image while True: w = int(image.shape[1] / scale) h = int(image.shape[0] / scale) image = cv2.pyrDown(image, dstsize=(w, h)) if image.shape[0] &lt; minSize[1] or image.shape[1] &lt; minSize[0]: break yield image But it is throwing an error something similar to this. OpenCV Error: Assertion failed (ssize.width &gt; 0 &amp;&amp; ssize.height &gt; 0 &amp;&amp; std::abs(dsize.width*2 - ssize.width) &lt;= 2 &amp;&amp; std::abs(dsize.height*2 - ssize.height) &lt;= 2) in pyrDown_, file /io/opencv/modules/imgproc/src/pyramids.cpp, line 873 Any idea how to specify the output size of the image as a method argument.

http://stackoverflow.com/q/48624592
tagged with: python
has answer: http://stackoverflow.com/a/48629239
score: 2
upvote count: 2
type: UnansweredQuestion
has body: Using Keras, the CCN I wish to train requires I use image augmentation and transfer learning. For the augmentation on a set of images on disk I use ImageDataGenerator.flow_from_directory. To generate augmented bottleneck features on a pre-trained network I intend using the pre-trained network's predict_generator method with flow_from_directory. This already successfully generates the augmented tensor of bottleneck features. However, there appears to me to be no way to obtain the corresponding augmentation labels array. I am really stumped as surely the designers of Keras thought of this and I'm just missing something obvious. I believe using the _generator methods in Keras have sufficient merrit to warrant persuing this route. Thanks in advance. train_path = 'data/train' train_gen = ImageDataGenerator( rotation_range=360, width_shift_range=0.10, height_shift_range=0.10, shear_range=0.52, zoom_range=0.10, channel_shift_range=0.10, fill_mode='nearest', horizontal_flip=True, vertical_flip=True, rescale=1./255, ) train_flow = train_gen.flow_from_directory( train_path, target_size=(256, 256), batch_size=32, ) train_number = 20000 train_tensor_neck = base_model.predict_generator(train_flow, verbose=1, steps=train_number // train_flow.batch_size + 1,) # Now how to generate the labels? train_labels = ...
downvote count: 0
answer count: 1
tagged with: keras
tagged with: label
favorite count: 0
type: Question
has title: Generating bottleneck feature augmentation with corresponding labels using Keras

http://stackoverflow.com/q/48593279
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48752966
downvote count: 0
upvote count: 1
tagged with: restore
has title: How to correctly reset graph and variables after Restoring Trained Model
tagged with: tensorflow
favorite count: 0
tagged with: scope
has body: I found the following code and tried to implement a Saver() for confirming the trained model can in fact be loaded an used but seems some variables or something isn't getting restored correctly (suspect variable scope items). The code in question checks if the model exists, if the model doesn't exist, it will train and save the model, if the model exists, it will try to restore the model then run the prediction on test data. Upon first training, the prediction test data works fine, but subsequent runs when running and loading the trained model, the test data predictions fail (gives garbled data [date numbers/format]). Any assistance would be greatly appreciated. import numpy as np import matplotlib.pyplot as plt import random import json import os import time from faker import Faker import babel from babel.dates import format_date import tensorflow as tf from keras.models import Sequential from keras.layers import LSTM, Embedding import tensorflow.contrib.legacy_seq2seq as seq2seq from sklearn.model_selection import train_test_split NUMBER_OF_EPOCHS = 10 BATCH_SIZE = 128 NUMBER_OF_NODES = 32 EMBEDDED_SIZE = 10 fake = Faker() fake.seed(42) random.seed(42) _modelPath = os.path.dirname(os.path.abspath(__file__)) + "\Model\date_model.ckpt" tf.reset_default_graph() inputs = tf.placeholder(tf.int32, (None, 29), 'inputs') outputs = tf.placeholder(tf.int32, (None, None), 'output') targets = tf.placeholder(tf.int32, (None, None), 'targets') FORMATS = ['short', 'medium', 'long', 'full', 'd MMM YYY', 'd MMMM YYY', 'dd MMM YYY', 'd MMM, YYY', 'd MMMM, YYY', 'dd, MMM YYY', 'd MM YY', 'd MMMM YYY', 'MMMM d YYY', 'MMMM d, YYY', 'dd.MM.YY', ] # change this if you want it to work with only a single language LOCALES = babel.localedata.locale_identifiers() LOCALES = [lang for lang in LOCALES if 'en' in str(lang)] def create_date(): """ Creates some fake dates :returns: tuple containing 1. human formatted string 2. machine formatted string 3. date object. """ dt = fake.date_object() tr…
score: 1
tagged with: python
type: Question

http://stackoverflow.com/a/48573822
has comment: http://stackoverflow.com/comment/84182614
type: Answer
has body: By using .loc df=pd.DataFrame({'Grade':['A','B','C','A','D']}) df.loc[(df.Grade=='A')&amp;(df.index&lt;3),'Grade']='Good' df Out[489]: Grade 0 Good 1 B 2 C 3 A 4 D More info (df.Grade=='A')&amp;(df.index&lt;3) Out[296]: 0 True 1 False 2 False 3 False 4 False Name: Grade, dtype: bool
has comment: http://stackoverflow.com/comment/84145459
answers question: http://stackoverflow.com/q/48573622
score: 0
has comment: http://stackoverflow.com/comment/84144828

http://stackoverflow.com/a/48589051
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48588490
answers question: http://stackoverflow.com/q/48588490
has comment: http://stackoverflow.com/comment/84349373
has comment: http://stackoverflow.com/comment/84349002
score: 10
has comment: http://stackoverflow.com/comment/84178794
type: Answer
upvote count: 10
has body: Just to demonstrate why regex is not practical for this sort of thing, here is a regex that would match ghiijk in your given example of abcghiijkyxz. Note it'll also match abc, y, x, z since they should technically be considered for longest string of alphabetical characters in order. Unfortunately, you can't determine which is the longest with regex alone, but this does give you all the possibilities. Please note that this regex works for PCRE and will not work with python's re module! Also, note that python's regex library does not currently support (*ACCEPT). Although I haven't tested, the pyre2 package (python wrapper for Google's re2 pyre2 using Cython) claims it supports the (*ACCEPT) control verb, so this may currently be possible using python. See regex in use here ((?:a+(?(?!b)(*ACCEPT))|b+(?(?!c)(*ACCEPT))|c+(?(?!d)(*ACCEPT))|d+(?(?!e)(*ACCEPT))|e+(?(?!f)(*ACCEPT))|f+(?(?!g)(*ACCEPT))|g+(?(?!h)(*ACCEPT))|h+(?(?!i)(*ACCEPT))|i+(?(?!j)(*ACCEPT))|j+(?(?!k)(*ACCEPT))|k+(?(?!l)(*ACCEPT))|l+(?(?!m)(*ACCEPT))|m+(?(?!n)(*ACCEPT))|n+(?(?!o)(*ACCEPT))|o+(?(?!p)(*ACCEPT))|p+(?(?!q)(*ACCEPT))|q+(?(?!r)(*ACCEPT))|r+(?(?!s)(*ACCEPT))|s+(?(?!t)(*ACCEPT))|t+(?(?!u)(*ACCEPT))|u+(?(?!v)(*ACCEPT))|v+(?(?!w)(*ACCEPT))|w+(?(?!x)(*ACCEPT))|x+(?(?!y)(*ACCEPT))|y+(?(?!z)(*ACCEPT))|z+(?(?!$)(*ACCEPT)))+) Results in: abc ghiijk y x z Explanation of a single option, i.e. a+(?(?!b)(*ACCEPT)): a+ Matches a (literally) one or more times. This catches instances where several of the same characters are in sequence such as aa. (?(?!b)(*ACCEPT)) If clause evaluating the condition. (?!b) Condition for the if clause. Negative lookahead ensuring what follows is not b. This is because if it's not b, we want the following control verb to take effect. (*ACCEPT) If the condition (above) is met, we accept the current solution. This control verb causes the regex to end successfully, skipping the rest of the pattern. Since this token is inside a capturing group, only that capturing group is ended suc…
has comment: http://stackoverflow.com/comment/84178867

http://stackoverflow.com/q/48608858
answer count: 0
downvote count: 0
score: 1
upvote count: 1
tagged with: spyder
favorite count: 0
has title: Buildozer failed while compiling into APK
has comment: http://stackoverflow.com/comment/84291766
type: Question
type: UnansweredQuestion
has body: Here is the app: #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Feb 3 23:11:38 2018 @author: djaber """ from kivy.app import App from kivy.uix.scatter import Scatter #from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout class TutorialApp(App): def build(self): f = FloatLayout() s= Scatter() l= Label(text= "Hello!", font_size= 150) f.add_widget(s) s.add_widget(l) return f # This is necessary to run the app if __name__ == "__main__": TutorialApp().run() I saved the script as "main.py" in order to be recognized by Buildozer. I ran Buildozer with the command "buildozer android debug" I took several minutes downloading some relevant packages. However, in the end, failed. I got the following error message (Log is set to 2 in order to display a detailed error message). djaber@djaber-ThinkPad-T440s ~/APK buider $ buildozer android debug # Check configuration tokens # Ensure build layout # Check configuration tokens # Preparing build # Check requirements for android # Run 'dpkg --version' # Cwd None Debian `dpkg' package management program version 1.17.5 (amd64). This is free software; see the GNU General Public License version 2 or later for copying conditions. There is NO warranty. # Search for Git (git) # -&gt; found at /usr/bin/git # Search for Cython (cython) # -&gt; found at /home/djaber/anaconda2/bin/cython # Search for Java compiler (javac) # -&gt; found at /usr/lib/jvm/java-7-openjdk-amd64/bin/javac # Search for Java keytool (keytool) # -&gt; found at /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/keytool # Install platform # Run 'pip install -q --user "appdirs" "colorama&gt;=0.3.3" "sh&gt;=1.10,&lt;1.12.5" "jinja2" "six"' # Cwd None # Apache ANT found at /home/djaber/.buildozer/android/platform/apache-ant-1.9.4 # Android SDK found at /home/djaber/.buildozer/android/platform/android-sdk-20 # Android NDK found at /home/djaber/.buildozer/android/platform/android-ndk-r9c # Check application requi…
tagged with: apk
tagged with: python
tagged with: kivy
tagged with: buildozer

http://stackoverflow.com/a/54149666
score: 37
downvote count: 0
answers question: http://stackoverflow.com/q/48620526
upvote count: 37
type: Answer
has body: Now it's added to selenium (SeleniumHQ/selenium#5919) so you can simply use the original approach from your question: from selenium import webdriver with webdriver.Chrome() as wd: res = wd.get('https://stackoverflow.com/questions/') print(res.page_source)

http://stackoverflow.com/comment/84239137
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48621143
type: QuestionComment
has text: By the way I am using zeep==2.4.0

http://stackoverflow.com/comment/84230705
type: AnswerComment
has text: Thank you! Yeah it works :D Just a question, does [2] represent its second root [@class='login-btn']?
comment on: http://stackoverflow.com/a/48616705
type: Comment
score: 0

http://stackoverflow.com/a/48627523
accepted answer of: http://stackoverflow.com/q/48627387
score: 2
has comment: http://stackoverflow.com/comment/84255324
upvote count: 2
has comment: http://stackoverflow.com/comment/84261249
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48627387
has body: import datetime d1 = datetime.datetime.strptime('2018/01/13', '%Y/%m/%d') d2 = datetime.datetime.strptime('2018/01/15 18:34:02', '%Y/%m/%d %H:%M:%S') delta = d2 - d1 print delta.total_seconds() print delta.days
has comment: http://stackoverflow.com/comment/84252154
type: Answer
has comment: http://stackoverflow.com/comment/84252014
has comment: http://stackoverflow.com/comment/84295966

http://stackoverflow.com/q/48575490
has title: Trying to get a label to update and print an integer after a button press in Tkinter in Python 3.6
has answer: http://stackoverflow.com/a/48576845
score: 0
tagged with: tkinter
has body: So I'm making a simple BMI calculator (really simple) and I'm trying to get the text boxes that have an input to change a label at the bottom that says the final answer. Problem is I can't get the label to display an actual answer. I can get the program to print the answer in the command line but I can't update the value of the text in the label itself. Below is my code. Thanks a bunch to whoever helps :^) from tkinter import * import tkinter root = Tk() root.title("BMI Calculator") root.geometry("300x200") name = StringVar() height = DoubleVar() weight = DoubleVar() bmi2= DoubleVar() name.set("Default") weight.set(20) height.set(2) bmi2.set(0) def calculate(): global name global height global weight global bmi2 bmi1= (weight.get() /height.get()) bmi2= (bmi1/height.get()) fnlname = print(name.get()) fnlbmi = print(bmi2) e= Entry(root, textvariable=height) e.pack() e2= Entry(root, textvariable=weight) e2.pack() e3= Entry(root, textvariable=name) e3.pack() b=Button(root, text="Calculate", command=calculate).pack() l=Label(root, text=bmi2).pack() root.mainloop()
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/9073995
tagged with: label

http://stackoverflow.com/comment/84066116
has text: `txs = tx.split(','); [','.join([a, b]) for a, b in zip(txs[::2], txs[1::2])]` gives: `['{{253, 146}', ' {3, 845}', ' {-841, 337}',...` after the link by Astrom
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48533153
type: Comment

http://stackoverflow.com/a/48542245
type: Answer
has body: An array is type-defined (dtype), so if you have a numpy array with only one complex value, the type will be complex and thus ALL the values are stored as complex number. If it's just to print out values, you should use lists instead of numpy array or simply a loop. The X2 list gives the home made solution. If you really want to use real_if_close, then you should use numpy.asscalar to convert the type numpy.array to a scalar value that format ":g" understand. X = [1+1e-14j,1+1e-13j] eps = np.finfo(float).eps tol = 100 # tolerance (used in real_if_close) X2 = [np.real(x) if np.imag(x)&lt;tol*eps else x for x in X] X3 = [np.asscalar(np.real_if_close(x)) for x in X] for x in X3: print("{:.5g}".format(x))
has comment: http://stackoverflow.com/comment/84082035
answers question: http://stackoverflow.com/q/48541604
score: 0
accepted answer of: http://stackoverflow.com/q/48541604
has comment: http://stackoverflow.com/comment/84113840
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84114090

http://stackoverflow.com/q/48542644
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84138290
score: 52
has comment: http://stackoverflow.com/comment/84103890
has comment: http://stackoverflow.com/comment/84110259
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50403960
has answer: http://stackoverflow.com/a/51239081
has comment: http://stackoverflow.com/comment/84149892
downvote count: 0
tagged with: python
answer count: 4
tagged with: named-pipes
has comment: http://stackoverflow.com/comment/84153428
has answer: http://stackoverflow.com/a/77665544
has title: Python and Windows Named Pipes
upvote count: 52
tagged with: windows
has body: What is the proper way of communicating with named pipes on Windows from Python? I've googled it, and can't find any packages that wrap this communication. There are: some descriptions of how to do it with pywin32 (I could not find how to connect to an existing pipe with it, though). This package: https://pypi.python.org/pypi/PyWPipe/ (had no luck with it either) A piece of code here, that I haven't yet tested: https://jonathonreinhart.com/posts/blog/2012/12/13/named-pipes-between-c-and-python/ I need just to connect to an existing named pipe and read/write to it. I previously had only tried communication with serial port (using pySerial), and I'm surprised how little info I could find on named pipes in comparison to it. There's usually tons of guides for any purpose for Python. I'll appreciate any help.
has answer: http://stackoverflow.com/a/78238957
favorite count: 0

http://stackoverflow.com/a/48515860
has comment: http://stackoverflow.com/comment/84037697
score: 0
accepted answer of: http://stackoverflow.com/q/48504308
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84031398
answers question: http://stackoverflow.com/q/48504308
has comment: http://stackoverflow.com/comment/84035797
has comment: http://stackoverflow.com/comment/84030392
has comment: http://stackoverflow.com/comment/84033980
type: Answer
has body: Before starting, If you are using Django REST your response from the view will be of the form application/json in normal case. This will help you in passing `permission_required = 'can_view_user' in this case. However, will try to provide a general idea how permission-based functionality can be implemented using Django. Let the three functionality available in dashboard be menu_1, menu_2, and menu_3. Your template can be of the form {% if can_view_menu1 %} Menu option 1 {% endif %} {% if can_view_menu2 %} Menu option 2 {% endif %} {% if can_view_menu3 %} Menu option 3 {% endif %} In your view class you can check for the role of the logged-in user and provide the permissions. An example can be as follows. class YourViewClass(ListView): # By default noone is permitted to access the view. can_view_menu_1 = False can_view_menu_2 = False can_view_menu_3 = False def dispatch(self, reuest, *args, **kwargs): if check_permission_RM(request): # returns True if user is RM self.can_view_menu_1 = True if check_permission_AM_or_PM(request): # returns True if logged in user is AM or PM. self.can_view_menu_1 = True self.can_view_menu_2 = True self.can_view_menu_3 = True return super(UsersListView, self).dispatch(request, *args, **kwargs) Remember to pass these variables as context or use DRF templatehtmlrenderer.
has comment: http://stackoverflow.com/comment/84034451

http://stackoverflow.com/comment/84140177
type: Comment
score: 0
has text: my results: https://imgur.com/a/V87HT
type: QuestionComment
comment on: http://stackoverflow.com/q/48571049

http://stackoverflow.com/a/48608309
accepted answer of: http://stackoverflow.com/q/48606314
type: AcceptedAnswer
downvote count: 0
score: 16
upvote count: 16
answers question: http://stackoverflow.com/q/48606314
type: Answer
has body: You have used side_effects instead of side_effect. Its something like this @patch.object(Class, "attribute") def foo(attribute): attribute.side_effect = Exception() # Other things can go here BTW, its not good approach to catch all the Exception and handle according to it.

http://stackoverflow.com/comment/84047064
type: Comment
score: 0
type: AnswerComment
has text: I solved with another url, xml instaed of html... the only question I need now is if I want to extract `nombre`and `url`, `for item in soup.find_all('nombre', 'url'):` did't work... how I need to do it?
comment on: http://stackoverflow.com/a/48525665

http://stackoverflow.com/q/48542904
type: UnansweredQuestion
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84087105
has body: I have automation scripts where the implicitly_wait is parametrized so that the user will be able to set it. I have a default value of 20 seconds which I am aware of but there is a chance that the user has set it with a different value. In one of my methods I would like to change the implicitly_wait (to lower it as much as possible) and return it to the value before the method was called. In order to do so I would like to save the implicitly_wait value before I change it. This is why I am looking for a way to reach to it.
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/84108410
has title: How can I view the implicitly_wait that the webdriver was set with?
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48543491

http://stackoverflow.com/q/48539900
tagged with: jupyter-notebook
answer count: 2
downvote count: 0
has body: I never used bash with jupyter notebook. For some project, I need to use bash with python but it's giving me errors. I have installed bash kernel also. PATH="/Downloads/dogscats/" !ls {PATH} 'ls' is not recognized as an internal or external command, operable program or batch file.
has comment: http://stackoverflow.com/comment/84075020
has title: using bash commands in jupyter notebook
score: 6
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/56597071
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84075230
upvote count: 6
has comment: http://stackoverflow.com/comment/84075414
tagged with: python
has answer: http://stackoverflow.com/a/54034655

http://stackoverflow.com/comment/84163536
score: 0
comment on: http://stackoverflow.com/q/48583184
type: QuestionComment
type: Comment
has text: Dictionaries are not deemed to be sorted, although they may be in the future. Therefore, your desired output should be a list of tuples.

http://stackoverflow.com/comment/84240788
has text: A generic comment. I hope these prove to be useful to help you advance, but it only addresses your immediate problem. I am not too wild about the `sys.argv` manipulation for it is a global attribute of the running environment and doing so violates interface/object encapsulation (it is not neat and possibly causes trouble down the road). Unfortunately I am not familiar enough with `distutils` to give you the correct answer off the bet, but I would encourage you to look around and see how to pass you own set of arguments replacing use of `sys.argv` (`argparse` for instance allows the same).
type: AnswerComment
comment on: http://stackoverflow.com/a/48619734
score: 0
type: Comment

http://stackoverflow.com/q/48634071
type: AnsweredQuestion
has title: seaborn's lmplot: KeyError [ ...] not in index; excel and csv import
answer count: 2
has answer: http://stackoverflow.com/a/67956555
score: 2
tagged with: http://stackoverflow.com/tag/csv
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/67956555
has body: I'm very new to python, so please bear with me. I'm having trouble to visualize an excel/csv file with seaborn's lmplot. This code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df=pd.read_csv("C:/Users/me/Documents/Jupyter Notebooks/Seaborn/Test.csv") sns.set_style('whitegrid') sns.lmplot(x=df["TestX"],y=df["TestY"], data=df) gives me this error: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-41-00ad8b882663&gt; in &lt;module&gt;() ----&gt; 1 sns.lmplot(x=df["TestX"],y=df["TestY"], data=df) ~\Anaconda3\lib\site-packages\seaborn\regression.py in lmplot(x, y, data, hue, col, row, palette, col_wrap, size, aspect, markers, sharex, sharey, hue_order, col_order, row_order, legend, legend_out, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, x_jitter, y_jitter, scatter_kws, line_kws) 550 need_cols = [x, y, hue, col, row, units, x_partial, y_partial] 551 cols = np.unique([a for a in need_cols if a is not None]).tolist() --&gt; 552 data = data[cols] 553 554 # Initialize the grid ~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key) 2131 if isinstance(key, (Series, np.ndarray, Index, list)): 2132 # either boolean or fancy integer index -&gt; 2133 return self._getitem_array(key) 2134 elif isinstance(key, DataFrame): 2135 return self._getitem_frame(key) ~\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_array(self, key) 2175 return self._take(indexer, axis=0, convert=False) 2176 else: -&gt; 2177 indexer = self.loc._convert_to_indexer(key, axis=1) 2178 return self._take(indexer, axis=1, convert=True) 2179 ~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _convert_to_indexer(self, obj, axis, is_setter) 1267 if mask.any(): 1268 raise KeyError('{mask} not in index' -&gt; 1269 .format(mask=objarr[mask])) 1270 1271 return …
upvote count: 2
tagged with: seaborn
accepted answer: http://stackoverflow.com/a/48634895
has answer: http://stackoverflow.com/a/48634895
tagged with: python
tagged with: excel

http://stackoverflow.com/comment/84464207
type: AnswerComment
has text: I get the following error : `/rest_framework/pagination.py:208: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'api.models.Message'> QuerySet. `
comment on: http://stackoverflow.com/a/48732384
type: Comment
score: 0

http://stackoverflow.com/q/48493279
has body: I have a bunch of methods for creating CSV files that are starting to make me feel like I am really repeating myself. Here are a couple: def genSmsOutputFile(self, smsDict): with open(settings.MEDIA_ROOT + 'smsOutput.csv', 'w+') as csvfile: writer = csv.writer(csvfile, delimiter=',') writer.writerow( ['電話番号','会員ID','TEL1','TEL2','TEL3','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)','(ラベル無し)',] ) for key, value in smsDict.items(): phoneNumber = value[2] + value[3] + value[4] writer.writerow( [ phoneNumber, value[0], value[2], value[3], value[4],'','','','','','','','','','','',''] ) return 'smsOutput.csv' def genMailOutputFile(self, okMailMaga): with open(settings.MEDIA_ROOT + 'mailMagaOutput.csv', 'w+') as csvfile: writer = csv.writer(csvfile, delimiter=',') writer.writerow( [ '会員id','e-mail','お名前(姓)','お名前(名)','購入回数' ] ) for key, value in okMailMaga.items(): writer.writerow( [ value[0], value[1], value[2], value[3], value[4] ] ) return settings.MEDIA_ROOT + 'mailMagaOutput.csv' I am working to create the function _writeOutputToFile(self, dictionary, columnNames): But I am finding myself stuck on how I would write the line: writer.writerow([value[0], value[1], value[2], value[3], value[4]]) Is there some way to grab an entire row of the CSV from a dictionary in one loop iteration dynamically?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48493310
has answer: http://stackoverflow.com/a/48493310
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
score: 1
favorite count: 0
type: Question
has title: Iterate through Python dictionary N items at a time for CSV writing
downvote count: 0
upvote count: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/48560927
has body: My advice: Assign another route for the html page @app.route('/cric') def getrender(): return render_template('/cric.html') Update method check from GET to POST in function getinfo and use request.form to get the parameter @app.route('/',methods=['GET','POST']) def getinfo(): print request.method # print the request.method for debug purpose if request.method == 'POST': a=request.form.get('team1') b=request.form.get('team2') c=request.form.get('matchid') print(a,b,c) return render_template('/cric.html') And update the form header and assign three input with name in html: &lt;form action="http://localhost:5000/" method="post"&gt; ... &lt;input class="form-control" id="team1" name="team1" type="text" placeholder="Enter team 1"&gt; ... Then you can visit the '/cric' to view the html page, then submit the form, which will invoke a post request to '/' and print the parameters.
has comment: http://stackoverflow.com/comment/84118547
answers question: http://stackoverflow.com/q/48560425
type: Answer
has comment: http://stackoverflow.com/comment/84118039
score: 0

http://stackoverflow.com/a/59097445
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48587595
has body: The Pandas to_datetime function has an origin parameter for julian to datetime conversion: amna['Date'] = pd.to_datetime(amna['DATA_BLOCK_CODE_1'], unit='D', origin='julian') print(df) ORG CHAIN_NBR SEQ_NBR INT_STATUS BLOCK_CODE_1 DATA_BLOCK_CODE_1 Date 0 523 1 0 A C 2012183 2012-07-02 1 523 2 1 I A 2013025 2013-01-26 2 521 3 1 A H 2007067 2007-03-09 3 513 4 1 D H 2001046 2001-02-16 4 513 5 1 8 I 2006075 2006-03-17 Note that you must include the unit parameter, and it must be set to days ('D'). Edit 2020-06-27 In response to Sami Navesi's comment, if the DATA_BLOCK_CODE_1 column is integer or string, you can split the year out (convert to string) and convert the julian days separately as shown in this answer. This example assumes the DATA_BLOCK_CODE_1 is string. The results are the same as above. amna['Date'] = [pd.to_datetime(e[:4]) + pd.to_timedelta(int(e[4:]) - 1, unit='D') for e in amna['DATA_BLOCK_CODE_1']]
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/110694667

http://stackoverflow.com/comment/84111225
has text: @guidot It's because I am really new to python and I could barely help myself with it. You can see my previous questions, I have always posted codes that I tried and didn't work. Here i could not even proceed so thought to take help from stackoverflow
comment on: http://stackoverflow.com/q/48557624
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48572715
has comment: http://stackoverflow.com/comment/84142586
score: 2
answers question: http://stackoverflow.com/q/48572629
has comment: http://stackoverflow.com/comment/84142310
has comment: http://stackoverflow.com/comment/84142526
type: Answer
accepted answer of: http://stackoverflow.com/q/48572629
has comment: http://stackoverflow.com/comment/84143194
upvote count: 2
has body: Python is a scripting language this means that there is no compiling/recompiling is necessary and errors are reported when you run the script. This removes one of the greatest assets of using make. Although you can use makefiles for replacing long commands in the command line or controlling dictionaries/files, it is unlikely you will really need this. If you are using C/C++ in with your Python project then it is highly recommendable. You mention intergrating. makefiles are unlikely to be the tools you want. You need to build a module at the very least. Modules allow you to use functions from other python files as if they were in that file. You need to import them and that's pretty much it. If you want to install on other PCs use setup.py script to create a package. This allows you to make your project installable and then the project can be used just like an extension to Python. Python is not like C or C++. Just knowing where to find the files together is fine for Python and when they are turned into modules you will just have to import them once and you will be able to use the functions they provide
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48596821
answers question: http://stackoverflow.com/q/48596726
type: Answer
score: 0
has body: Your original idea doesn't work because you can't have lists in sets, as they aren't hashable. An easy way is to turn your lists into tuples : ListA = [[4, 4], [4, 5], [4, 6], [5, 4], [5, 5], [5, 6], [6, 4], [6, 5], [6, 6]] ListB =[[0, 4], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [3, 6], [3, 7], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [5, 2], [5, 3], [5, 4], [5, 5], [5, 6], [6, 4]] set_a = set([tuple(l) for l in ListA]) set_b = set([tuple(l) for l in ListB]) intersection = set_a.intersection(set_b) print(intersection) # {(6, 4), (5, 4), (4, 6), (5, 5), (4, 5), (5, 6), (4, 4)} # or, if you prefer a list of lists print([list(t) for t in intersection]) # [[6, 4], [5, 4], [4, 6], [5, 5], [4, 5], [5, 6], [4, 4]]

http://stackoverflow.com/comment/83990980
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48498587
has text: Ah your google-fu exceeded mine in that case, I obviously couldn't concoct the right mix of 'string', 'list', 'split', 'delimiter'...!

bit
tag name: bit
type: Tag
tags question: http://stackoverflow.com/q/48568717

http://stackoverflow.com/comment/84126084
score: 2
type: Comment
has text: @JamesSchinner that's my guess. dict() is implemented in C but the class has to go through the Python Object shenigans
type: QuestionComment
comment on: http://stackoverflow.com/q/48564965

http://stackoverflow.com/a/48573677
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/126234361
answers question: http://stackoverflow.com/q/48573445
has body: From the documentation, it seems really straight forward pbar = ProgressBar().start() def job(): total_steps = 7 # script 1 pbar.update((1/7)*100) # current step/total steps * 100 # script 2 pbar.update((2/7)*100) # current step/total steps * 100 # .... pbar.finish() Also, don't be afraid to check out the source code https://github.com/niltonvolpato/python-progressbar/blob/master/progressbar/progressbar.py
type: Answer
score: 2

http://stackoverflow.com/comment/84211331
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48607515
type: Comment
has text: Cool. But it will not work with abbreviations, right? Do you know something additional for recognizing abbreviations and passing them to country names?

http://stackoverflow.com/comment/84049833
type: QuestionComment
has text: DO you have space to load `my_var[tmin:tmax,:,:]` and then do the `upts` indexing on the array? Is `upts` typically small compared to the time range? If you must iterate, do so on the smallest range.
comment on: http://stackoverflow.com/q/48525724
score: 0
type: Comment

asynchronous
tags question: http://stackoverflow.com/q/48584712
tags question: http://stackoverflow.com/q/48640549
tags question: http://stackoverflow.com/q/48617655
tags question: http://stackoverflow.com/q/48618709
tags question: http://stackoverflow.com/q/48510000
type: Tag
tags question: http://stackoverflow.com/q/48638355
tags question: http://stackoverflow.com/q/48563969
tags question: http://stackoverflow.com/q/48555439
tag name: asynchronous
tags question: http://stackoverflow.com/q/48498510
tags question: http://stackoverflow.com/q/48636568
tags question: http://stackoverflow.com/q/48590138

http://stackoverflow.com/comment/84103750
has text: Thanks. I did see this. However, where and how do I store this so that it works with "from class_vis import prettyPicture, output_image"? Or, is there another way to implement this besides placing the code in my program (with a couple changes of course)? Thanks!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48533455
type: Comment

http://stackoverflow.com/a/48545187
has comment: http://stackoverflow.com/comment/84085857
score: 0
type: Answer
has body: You can try without any external library : a = [1,1,1,1,0,0,0,1,1,0,0,0,1,1,1] track=[] full_track=[] for i,j in enumerate(a): try: if a[i+1]==a[i]: track.append(j) else: track.append(a[i]) full_track.append(track) track=[] except IndexError: if a[i-1]==a[i]: track.append(j) full_track.append(track) print(list(map(lambda x:(x[0],x[-1]),full_track))) output: [(1, 1), (0, 0), (1, 1), (0, 0), (1, 1)]
answers question: http://stackoverflow.com/q/48542890

http://stackoverflow.com/q/48566534
favorite count: 0
has answer: http://stackoverflow.com/a/48566946
type: Question
tagged with: python-3.x
tagged with: nltk
tagged with: python
possible better answer: http://stackoverflow.com/a/48566946
tagged with: data-structures
has comment: http://stackoverflow.com/comment/84228419
type: AnsweredQuestion
answer count: 2
tagged with: tokenize
downvote count: 0
has body: I have 3 counters with total count for word frequency on different strings. Counter({u'childhood': 3, u'waiting': 2}) #counter1 Counter({u'childhood': 5}) #counter2 Counter({u'waiting': 2}) #counter 3 Atm I am able to perform counter addition to get the total word count for all words in all counters. Counter({u'childhood': 8, u'waiting': 4}) I however need to take each counter and insert them on a hash table with the word as key and a linked list as value where each linked entry has the count per string per Counter. Example [childhood] : [1,3] -&gt; [2,5] #counter 1 - 3 times | counter 2 - 5 times [waiting] : [1,3] -&gt; [3,2] How do I achieve this in Python? I was thinking of a dictionary with a deque inside? Or extend the counter addition function? I'n trying to use existent python data structures without extending or creating custom data structure implementations.
score: 1
upvote count: 1
has title: Convert Counters to Hash Table with Linked List values
has answer: http://stackoverflow.com/a/48566878
accepted answer: http://stackoverflow.com/a/48566878

http://stackoverflow.com/comment/84023119
type: Comment
has text: Hi giosans, thanks for your respond. I tried with your code as below import zipfile import os def show_jar_classes(jar_file): zf = zipfile.ZipFile(jar_file, 'w') try: #Code to write inside org folder in inside z.jar filename = 'org\India.txt' # name of the file fcontent = b'India is a great country' # content zf.writestr(filename,fcontent,zipfile.ZIP_DEFLATED) finally: zf.close() jar_file='D:/python/try' show_jar_classes(jar_file) Instead of writing it into try,jar it has created another file with the same name try
type: AnswerComment
comment on: http://stackoverflow.com/a/48506102
score: 0

http://stackoverflow.com/q/48507651
has comment: http://stackoverflow.com/comment/84010390
has comment: http://stackoverflow.com/comment/84010189
has comment: http://stackoverflow.com/comment/84010268
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84020715
has comment: http://stackoverflow.com/comment/84010105
type: UnansweredQuestion
has body: I am solving a binary classification problem over some text documents using Python and implementing the scikit-learn library, and I wish to try different models to compare and contrast results - mainly using a Naive Bayes Classifier, SVM with K-Fold CV, and CV=5. I am finding a difficulty in combining all of the methods into one pipeline, given that the latter two models use gridSearchCV(). I cannot have multiple Pipelines running during a single implementation due to concurrency issues, hence I need to implement all the different models using one pipeline. This is what I have till now, # pipeline for naive bayes naive_bayes_pipeline = Pipeline([ ('bow_transformer', CountVectorizer(analyzer=split_into_lemmas, stop_words='english')), ('tf_idf', TfidfTransformer()), ('classifier', MultinomialNB()) ]) # accessing and using the pipelines naive_bayes = naive_bayes_pipeline.fit(train_data['data'], train_data['gender']) # pipeline for SVM svm_pipeline = Pipeline([ ('bow_transformer', CountVectorizer(analyzer=split_into_lemmas, stop_words='english')), ('tf_idf', TfidfTransformer()), ('classifier', SVC()) ]) param_svm = [ {'classifier__C': [1, 10], 'classifier__kernel': ['linear']}, {'classifier__C': [1, 10], 'classifier__gamma': [0.001, 0.0001], 'classifier__kernel': ['rbf']}, ] grid_svm_skf = GridSearchCV( svm_pipeline, # pipeline from above param_grid=param_svm, # parameters to tune via cross validation refit=True, # fit using all data, on the best detected classifier n_jobs=-1, # number of cores to use for parallelization; -1 uses "all cores" scoring='accuracy', cv=StratifiedKFold(train_data['gender'], n_folds=5), # using StratifiedKFold CV with 5 folds ) svm_skf = grid_svm_skf.fit(train_data['data'], train_data['gender']) predictions_svm_skf = svm_skf.predict(test_data['data']) EDIT 1: The second pipeline is the only pipeline using gridSearchCV(), and never seems to be executed. EDIT 2: Added more code to show gridSearchCV() use.
has comment: http://stackoverflow.com/comment/84010194
has comment: http://stackoverflow.com/comment/84010659
score: 10
upvote count: 10
tagged with: python
linked to: http://stackoverflow.com/q/50285973
has comment: http://stackoverflow.com/comment/84010814
tagged with: pipeline
has comment: http://stackoverflow.com/comment/84010456
has title: Multiple classification models in a scikit pipeline python
downvote count: 0
has comment: http://stackoverflow.com/comment/84011008
linked to: http://stackoverflow.com/q/51695322
tagged with: classification
has answer: http://stackoverflow.com/a/53926120
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/84010352

http://stackoverflow.com/comment/84264401
type: QuestionComment
has text: Why do not you want to draw the rectangles several times?
comment on: http://stackoverflow.com/q/48622395
score: 0
type: Comment

http://stackoverflow.com/comment/83978725
type: Comment
has text: You need to add `self` prefix to `label1.image = photo` and `label1.grid()`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48492780

http://stackoverflow.com/q/48571689
downvote count: 1
tagged with: yahoo-finance
score: -1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: pandas-datareader
has answer: http://stackoverflow.com/a/48572266
tagged with: python
linked to: http://stackoverflow.com/q/37794095
has body: I am using the below code to parse a large tickers list to yahoo datareader, I am trying to get back a dataframe as per below. If the list is large, I often get a RemoteError back but on different tickers each time. I am not sure how to handle the RemoteError and I am happy to drop the ticker and continue with the next ticker in the list. I would, however, like to try again to get adj close ticker data. I thought using a for loop and adding a time delay would help with yahoo requests but I am still getting a Remote error. Any ideas? IBM MSFT ORCL TSLA YELP Date 2014-01-02 184.52 36.88 37.61 150.10 67.92 2014-01-03 185.62 36.64 37.51 149.56 67.66 2014-01-06 184.99 35.86 37.36 147.00 71.72 2014-01-07 188.68 36.14 37.74 149.36 72.66 2014-01-08 186.95 35.49 37.61 151.28 78.42 import pandas_datareader.data as web import datetime as dt import pandas as pd import time from pandas_datareader._utils import RemoteDataError Which_group = ['Accident &amp; Health Insurance'] ##&lt;&lt;&lt;&lt;put in group here df = pd.read_csv('/home/ross/Downloads/UdemyPairs/stocks1.csv') df.set_index('categoryName', inplace = True) df1 = df.loc[Which_group] tickers = df1.Ticker.tolist() print(tickers) #tickers = ['SPY', 'AAPL', 'MSFT'] # add as many tickers start = dt.datetime(2013, 1,1) end = dt.datetime.today() # Function starts here def get_previous_close(strt, end, tick_list, this_price): """ arg: `this_price` can take str Open, High, Low, Close, Volume""" #make an empty dataframe in which we will append columns adj_close = pd.DataFrame([]) # loop here. for idx, i in enumerate(tick_list): try: # time.sleep(0.01) total = web.DataReader(i, 'yahoo', strt, end) adj_close[i] = total[this_price] except RemoteDataError: pass return adj_close #call the function print(get_previous_close(start, end, tickers, 'Adj Close'))
has title: Pandas DataReader handle RemoteError yahoo finance
tagged with: pandas

http://stackoverflow.com/comment/84232818
type: QuestionComment
comment on: http://stackoverflow.com/q/48612170
has text: @MatiasValdenegro I mean that fit_generator shows loss 8.9 while evaluate_generator shows 0.1
score: 0
type: Comment

http://stackoverflow.com/comment/84005984
score: 0
type: Comment
type: QuestionComment
has text: I cannot see any change to `read_from_db`. `read_lock` is only mentioned once. If you have a `read_lock.acquire()` in a method, then there should be a `read_lock.release()` as well.
comment on: http://stackoverflow.com/q/48505658

http://stackoverflow.com/comment/84189332
comment on: http://stackoverflow.com/q/48592239
score: 0
type: Comment
type: QuestionComment
has text: add it in the main urls .. urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('myproject_api.urls')), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT,}) ]

http://stackoverflow.com/comment/84209471
has text: Go through this blog: https://www.analyticsvidhya.com/blog/2017/01/sentiment-analysis-of-twitter-posts-on-chennai-floods-using-python/
comment on: http://stackoverflow.com/q/48606331
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48547617
downvote count: 0
answer count: 1
has title: Sum for a large dataframe?
score: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I have a large SparseDataFrame, approximately 12000 rows x 16000 columns. I want to calculate sum of rows grouped by a column: Input: +-------+------+------+------+ | | Col1 | Col2 | Col3 | +-------+------+------+------+ | row 1 | Foo | 1 | 0 | | row 2 | Foo | 3 | 1 | | row 3 | Bar | 5 | 3 | +-------+------+------+------+ Output: +-----+------+------+ | | Col2 | Col3 | +-----+------+------+ | Foo | 4 | 1 | | Bar | 5 | 3 | +-----+------+------+ Any ideas how to make this code more performant? Currently it works very slow. sparse_df = pd.SparseDataFrame(vector, columns=data).transpose() sparse_df.groupby('col1').sum()
upvote count: 1
tagged with: python
tagged with: pandas
has answer: http://stackoverflow.com/a/48547847

http://stackoverflow.com/q/48497073
has title: Why doesn't tkinter free the thread once the window has closed?
favorite count: 0
has comment: http://stackoverflow.com/comment/84001329
has comment: http://stackoverflow.com/comment/83995807
score: 1
tagged with: python
type: Question
upvote count: 4
has body: I have a class, ClientGUI (make in tkinter), which represents the client's class for my application. In this class, upon pressing a button, a new tkinter window is opened (using a module I imported), which represents a UI for a drawing tool. When I close this drawing tool window, I want it to return a message to the client class that the drawing tool has been closed. The problem is that I receive this message only when I close the main client window as well. The code for all this is below: This is the code that declares and starts the main client window: root = Tk() root.resizable(False, False) root.title("Client") root.protocol("WM_DELETE_WINDOW", onX) clientGui = clientGUI(root) //clientGUI is the client class. It contains all the UI and functionality elements root.mainloop() This is the function I use to close it: def onX(): answer = tkinter.messagebox.askquestion("Quit", "Are you sure you want to quit the application ?") if answer == "yes": root.destroy() In the clientGUI, upon pressing a button, a new window is opened from a module I created, this is the code that starts the new window: def startDrawingTool(self, username, password): drawingToolStatus = drawingTool.startTool() // the new window is opened here print(drawingToolStatus) // This only gets printed when I close the main client window(clientGui) This is the startTool() function, declared in the drawingTool module I imported: def startTool(): def onX(): answer = tkinter.messagebox.askquestion("Quit", "Quiting without saving may result in data loss, make sure to always save first. Are you sure you want to quit?") if answer == "yes": root.destroy() root = Tk() root.resizable(False, False) root.title("Drawing program") root.protocol("WM_DELETE_WINDOW", onX) app = Application(root) // Application is the drawing tool class, contains all the UI elements and functionality root.mainloop() return "window closed" // This is how I want to let the main client class know that the drawing tool has been closed Hopefu…
tagged with: python-3.x
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
downvote count: 3

http://stackoverflow.com/a/48525387
has body: Since you tag pandas pd.DataFrame(mylist).\ apply(lambda x: sorted(x, key=pd.notnull), 1).\ fillna(0).astype(int).values.tolist() Out[89]: [[0, 0, 1], [0, 1, 2], [1, 2, 3]]
has comment: http://stackoverflow.com/comment/84045913
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48525210
has comment: http://stackoverflow.com/comment/84045983
has comment: http://stackoverflow.com/comment/84046012
score: 2
downvote count: 0

http://stackoverflow.com/comment/84157877
comment on: http://stackoverflow.com/a/48580406
has text: I get this: `File "C:\Users\User\Desktop\test.py", line 14, in main res = pool.map(jobWrapper, the_args) File "C:\Python27\lib\multiprocessing\pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "C:\Python27\lib\multiprocessing\pool.py", line 558, in get raise self._value cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48573742
tagged with: python
has comment: http://stackoverflow.com/comment/84145515
has comment: http://stackoverflow.com/comment/84144394
upvote count: 2
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84144343
has answer: http://stackoverflow.com/a/48573855
accepted answer: http://stackoverflow.com/a/48573855
has comment: http://stackoverflow.com/comment/84144374
downvote count: 2
has comment: http://stackoverflow.com/comment/84144315
answer count: 1
has comment: http://stackoverflow.com/comment/84144426
has comment: http://stackoverflow.com/comment/84144317
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am trying to separate digits of a number and then store them in a list. can someone please explain how the 'digits' line works? Code: n = [153,423,1,22] for i in range(0, len(n)): digits = [int(d) for d in str(n[i])]
has title: I am trying to separate digits of a number and then store them in a list

http://stackoverflow.com/comment/84159860
comment on: http://stackoverflow.com/q/48581767
has text: you can directly give like this : `dict[some_variables_name1] = value1` right ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84203149
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48602761
has text: With regards to static typing, consider this Java example: https://repl.it/repls/LimpingNoxiousShorebird

http://stackoverflow.com/q/48497529
tagged with: python
tagged with: cmd
has title: Python can't access cmd when using CX_FREEZE
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: cx-freeze
has body: After I build my script using CX_FREEZE I can't get anything to print. Tried using shell : cmd ="echo %s"% a call(cmd, shell=True) But that didn't worked either. Is there another way to open CMD and print something after building. I'm using 3.6 python and using 32 bit.
score: 1

http://stackoverflow.com/comment/84172111
comment on: http://stackoverflow.com/q/48587416
score: 0
has text: ty man. god bless you
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84023854
score: 0
has text: It's certainly possible, but... why do you want to do this? How do you imagine you'll use these variables?
comment on: http://stackoverflow.com/q/48514653
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84093910
comment on: http://stackoverflow.com/q/48527321
score: 0
type: Comment
type: QuestionComment
has text: Ohh, my bad. It was meant to be like this `seed=0`. Then `np.random.seed(seed)` and `random_state=seed`

http://stackoverflow.com/comment/84129073
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48566333
score: 0
has text: You're subtracting Time_Start from time, actually. I'm assuming you're looping through these? Please post your code for context.

http://stackoverflow.com/a/74256950
has body: I wrapped up @Akash's answer in a method to be added to a custom Manager or QuerySet: def gfks(self, **kwargs): filters = {} for field, obj in kwargs.items(): gfk = self.model._meta.get_field(field) filters[gfk.ct_field] = ContentType.objects.get_for_model( obj ) filters[gfk.fk_field] = obj.pk return self.filter(**filters) For example, if you had a model called Comparison with two GFKs called product1 and product2, and added this method, usage would look like: comp = Comparison.objects.gfks(product1=foo, product2=bar) Would be nice if Django's contenttypes app provided some similar sugar automatically, but I'll settle for adding this to my BaseQuerySet class in the meantime.
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48605567

http://stackoverflow.com/q/48636547
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/48636617
has answer: http://stackoverflow.com/a/48636617
type: AnsweredQuestion
has body: suppose, If I have dictionary game = [{'points': '534', 'Team': 'Ireland', 'Rating': '36', 'Matches': '15'}, {'points': '5146', 'Team': 'England Women', 'Rating': '129', 'Matches': '40'}, {'points': '5898', 'Team': 'Australia Women', 'Rating': '128', 'Matches': '46'},{'date-updated': '05 February 2018', 'match-type': "ICC Women's Championship"}] If I wan't to use key's 'points','Team','Rating','Matches', I can use for loop like {% for team in game %} {{ team["Team"]}} {{ team['Matches'] }} {{ team['points'] }} {{ team['Rating'] }} {% endif%} and I can print these key's value. How can I render the key value of date-updated and match-type without using for loop since there is only one set of dictionary present. I tried to call it as bellow but it didn't print anything {{game['date-updated']}} {{game['match-type']}}
accepted answer: http://stackoverflow.com/a/48636610
answer count: 2
has title: How to render the value of variable from a HTML page?
has answer: http://stackoverflow.com/a/48636610
upvote count: 0
tagged with: jinja2
downvote count: 1

http://stackoverflow.com/a/48573683
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
has body: You can use the bar object this way: import time import progressbar def job(): bar = progressbar.ProgressBar() for i in bar(range(100)): ... # Code that you want to run #time.sleep(0.02) job() If the code you want to execute has fast execution time, you can put a time.sleep() inside in order not to have progressbar set to 100% in the beginning.
type: Answer
answers question: http://stackoverflow.com/q/48573445
accepted answer of: http://stackoverflow.com/q/48573445

http://stackoverflow.com/q/48551440
has comment: http://stackoverflow.com/comment/84099528
downvote count: 0
tagged with: python
has title: How to use multiprocessing to loop through a big list of URL?
has answer: http://stackoverflow.com/a/48552764
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84099077
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84099585
has comment: http://stackoverflow.com/comment/84099486
has answer: http://stackoverflow.com/a/48552109
possible better answer: http://stackoverflow.com/a/48552109
accepted answer: http://stackoverflow.com/a/48552764
has comment: http://stackoverflow.com/comment/84132782
favorite count: 0
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has body: Problem: Check a listing of over 1000 urls and get the url return code (status_code). The script I have works but very slow. I am thinking there has to be a better, pythonic (more beutifull) way of doing this, where I can spawn 10 or 20 threads to check the urls and collect resonses. (i.e: 200 -> www.yahoo.com 404 -> www.badurl.com ... Input file:Url10.txt www.example.com www.yahoo.com www.testsite.com .... import requests with open("url10.txt") as f: urls = f.read().splitlines() print(urls) for url in urls: url = 'http://'+url #Add http:// to each url (there has to be a better way to do this) try: resp = requests.get(url, timeout=1) print(len(resp.content), '->', resp.status_code, '->', resp.url) except Exception as e: print("Error", url) Challenges: Improve speed with multiprocessing. With multiprocessing But is it not working. I get the following error: (note: I am not sure if I have even implemented this correctly) AttributeError: Can't get attribute 'checkurl' on <module '__main__' (built-in)> -- import requests from multiprocessing import Pool with open("url10.txt") as f: urls = f.read().splitlines() def checkurlconnection(url): for url in urls: url = 'http://'+url try: resp = requests.get(url, timeout=1) print(len(resp.content), '->', resp.status_code, '->', resp.url) except Exception as e: print("Error", url) if __name__ == "__main__": p = Pool(processes=4) result = p.map(checkurlconnection, urls)
has comment: http://stackoverflow.com/comment/84131867
answer count: 2
tagged with: multithreading
has comment: http://stackoverflow.com/comment/84099500

http://stackoverflow.com/comment/84002477
has text: To your `bind`-comment: That's wrong, but probably `self` is not bound to the right object in your code. [The tkinter example](https://docs.python.org/3.6/library/tkinter.html#coupling-widget-variables) binds a method (`self.print_something`) to a key.
type: QuestionComment
comment on: http://stackoverflow.com/q/48503893
score: 0
type: Comment

http://stackoverflow.com/a/48553175
upvote count: 1
has body: Your regex is anchored to the end of the line: ^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})(.*?)$ Since you've enabled multi-line mode, $ matches at a line break. That's why the match ends after global_pg_audit. You want to match until the next line that starts with a date. You can use a lookahead to do this: ^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})(.*?)(?=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|\Z) The alternation |\Z allows the regex to match the last line even though it's not followed by a date. See also the regex demo.
has comment: http://stackoverflow.com/comment/84132749
type: Answer
answers question: http://stackoverflow.com/q/48553106
score: 1
downvote count: 0

http://stackoverflow.com/comment/83993185
score: 0
comment on: http://stackoverflow.com/q/48498184
has text: do i change any code in API.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84059473
has text: I am actually creating this dataframe from a SQL query to a snowflake database. Do you have an example of this using a query to a database.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48531566

http://stackoverflow.com/comment/84192433
comment on: http://stackoverflow.com/q/48597453
type: Comment
type: QuestionComment
score: 0
has text: Oh ok. ..... I searched in Panda but i didn't find something, do you know how i can translate it ? :)

wavelet
tag name: wavelet
tags question: http://stackoverflow.com/q/48555287
type: Tag

http://stackoverflow.com/q/48507197
downvote count: 0
tagged with: pandas
has title: Custom sorting of the level 1 index of a multiindex Pandas DataFrame according to the level 0 index
tagged with: multi-index
has answer: http://stackoverflow.com/a/48507433
possible better answer: http://stackoverflow.com/a/48507433
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/122672250
accepted answer: http://stackoverflow.com/a/48507565
has body: I have a multindex DataFrame, df: arrays = [['bar', 'bar', 'baz', 'baz', 'baz', 'baz', 'foo', 'foo'], ['one', 'two', 'one', 'two', 'three', 'four', 'one', 'two']] df = pd.DataFrame(np.ones([8, 4]), index=arrays) which looks like: 0 1 2 3 bar one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 baz one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 three 1.0 1.0 1.0 1.0 four 1.0 1.0 1.0 1.0 foo one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 I now need to sort the 'baz' sub-level into a new order, to create something that looks like df_end: arrays_end = [['bar', 'bar', 'baz', 'baz', 'baz', 'baz', 'foo', 'foo'], ['one', 'two', 'two', 'four', 'three', 'one', 'one', 'two']] df_end = pd.DataFrame(np.ones([8, 4]), index=arrays_end) which looks like: 0 1 2 3 bar one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 baz two 1.0 1.0 1.0 1.0 four 1.0 1.0 1.0 1.0 three 1.0 1.0 1.0 1.0 one 1.0 1.0 1.0 1.0 foo one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 I thought that I might be able to reindex the baz row: new_index = ['two','four','three','one'] df.loc['baz'].reindex(new_index) Which gives: 0 1 2 3 two 1.0 1.0 1.0 1.0 four 1.0 1.0 1.0 1.0 three 1.0 1.0 1.0 1.0 one 1.0 1.0 1.0 1.0 ...and insert these values back into the original DataFrame: df.loc['baz'] = df.loc['baz'].reindex(new_index) But the result is: 0 1 2 3 bar one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 baz one NaN NaN NaN NaN two NaN NaN NaN NaN three NaN NaN NaN NaN four NaN NaN NaN NaN foo one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 Which is not what I'm looking for! So my question is how I can use new_index to reorder the rows in the baz index. Any advice would be greatly appreciated.
linked to: http://stackoverflow.com/q/43073254
tagged with: dataframe
tagged with: python
tagged with: sorting
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/48507565
type: AnsweredQuestion
answer count: 2

java
tags question: http://stackoverflow.com/q/48504301
tags question: http://stackoverflow.com/q/48522880
tag name: java
tags question: http://stackoverflow.com/q/48584703
tags question: http://stackoverflow.com/q/48599891
tags question: http://stackoverflow.com/q/48634514
tags question: http://stackoverflow.com/q/48636600
tags question: http://stackoverflow.com/q/48582862
tags question: http://stackoverflow.com/q/48604128
tags question: http://stackoverflow.com/q/48522126
type: Tag
tags question: http://stackoverflow.com/q/48638105
tags question: http://stackoverflow.com/q/48566577
tags question: http://stackoverflow.com/q/48617746
tags question: http://stackoverflow.com/q/48618191

http://stackoverflow.com/q/48546446
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84089105
has comment: http://stackoverflow.com/comment/84088878
tagged with: pandas
upvote count: 0
has body: Hi I have 2 dataframe df1 and df2. df1=pd.DataFrame(data=[['a1','a2'],['b1','b2'],['c1','c2']],columns=['HR','RR'],index=[0,0,1]) df1 Out[146]: HR RR 0 a1 a2 0 b1 b2 1 c1 c2 df2=pd.DataFrame(data=[['1','2'],['1','2'],['1','2'],['1','2'],['1','2']],columns=['ST','SR'],index=[0,0,0,0,1]) df2 Out[147]: ST SR 0 1 2 0 1 2 0 1 2 0 1 2 1 1 2 How can I concatenate them in order to get result and result2? result = pd.DataFrame(data=[['a1','a2',1,2],['b1','b2',1,2],[np.nan,np.nan,1,2],[np.nan,np.nan,1,2],['c1','c2',1,2]],columns=['HR','RR','ST','SR'],index=[0,0,0,0,1]) result Out[148]: HR RR ST SR 0 a1 a2 1 2 0 b1 b2 1 2 0 NaN NaN 1 2 0 NaN NaN 1 2 1 c1 c2 1 2 result2 = pd.DataFrame(data=[[np.nan,np.nan,1,2],[np.nan,np.nan,1,2],['a1','a2',1,2],['b1','b2',1,2],['c1','c2',1,2]],columns=['HR','RR','ST','SR'],index=[0,0,0,0,1]) result2 Out[148]: HR RR ST SR 0 NaN NaN 1 2 0 NaN NaN 1 2 0 a1 a2 1 2 0 b1 b2 1 2 1 c1 c2 1 2
type: UnansweredQuestion
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84088984
type: Question
has title: concatenate 2 dataframes with different number of rows for the same index
has answer: http://stackoverflow.com/a/48546549

http://stackoverflow.com/comment/84104231
type: Comment
has text: The post [here](https://stackoverflow.com/questions/45178447/multiprocessing-queue-as-arg-to-pool-worker-aborts-execution-of-worker?rq=1) show a much simpler illustration of the above problem . The second code in that post also doesn't work for me (just hangs). Hm....
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48553786

http://stackoverflow.com/a/48592949
has body: In case tuple is sure to have minimum two items in it then, this seems to be simple. for f,s,*r in [(1,2), (3,4), (5,6,7), (8,9)]: print(f,s)
answers question: http://stackoverflow.com/q/48592831
type: Answer
has comment: http://stackoverflow.com/comment/84183231
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/q/48568649
has comment: http://stackoverflow.com/comment/84133633
tagged with: python
has answer: http://stackoverflow.com/a/48569129
has comment: http://stackoverflow.com/comment/84133986
tagged with: export-to-csv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48596155
answer count: 2
linked to: http://stackoverflow.com/q/9807634
has title: Convert Json to CSV using Python
score: 1
upvote count: 1
downvote count: 0
has body: Below, is the json structure I am pulling from my online weather station. I am also including a json_to_csv python script that is supposed to convert json data to csv output, but only returns a "Key" error. I want to pull data from "current_observation": only. { "response": { "features": { "conditions": 1 } } , "current_observation": { "display_location": { "latitude":"40.466442", "longitude":"-85.362709", "elevation":"280.4" }, "observation_time_rfc822":"Fri, 26 Jan 2018 09:40:16 -0500", "local_time_rfc822":"Sun, 28 Jan 2018 11:22:47 -0500", "local_epoch":"1517156567", "local_tz_short":"EST", "weather":"Clear", "temperature_string":"44.6 F (7.0 C)", } } import csv, json, sys inputFile = open("pywu.cache.json", 'r') #open json file outputFile = open("CurrentObs.csv", 'w') #load csv file data = json.load(inputFile) #load json content inputFile.close() #close the input file output = csv.writer(outputFile) #create a csv.write output.writerow(data[0].keys()) for row in data: output = csv.writer(outputFile) #create a csv.write output.writerow(data[0].keys()) for row in data: output.writerow(row.values()) #values row What's the best method to retrieve the temperature string and convert to .csv format? Thank you!
favorite count: 0
possible better answer: http://stackoverflow.com/a/48569129
type: Question
has comment: http://stackoverflow.com/comment/84133544
accepted answer: http://stackoverflow.com/a/48596155

http://stackoverflow.com/a/49230109
downvote count: 0
upvote count: 8
answers question: http://stackoverflow.com/q/48552182
type: Answer
score: 8
has body: It should be like this !! if your class defined as: class mi_module(models.Model): _name = "mi.module" #"Body" you have to do it as : mi module window mi.module tree,form

http://stackoverflow.com/comment/84033907
comment on: http://stackoverflow.com/a/48519378
has text: So I have added the return inventory under the inventory.setdefault statement, however then it only added the first value of the list that the dictionary does not contain (dagger).
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48575657
has comment: http://stackoverflow.com/comment/84152370
tagged with: python
has comment: http://stackoverflow.com/comment/84152270
has answer: http://stackoverflow.com/a/48578271
has comment: http://stackoverflow.com/comment/84152494
has comment: http://stackoverflow.com/comment/84152610
linked to: http://stackoverflow.com/q/24234823
has title: can't open files using numpy in mac os
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/84152459
answer count: 1
has comment: http://stackoverflow.com/comment/84147833
has comment: http://stackoverflow.com/comment/84148165
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84151041
has comment: http://stackoverflow.com/comment/84152365
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84147874
has comment: http://stackoverflow.com/comment/84152295
type: UnansweredQuestion
has body: import matplotlib.pyplot as plt import numpy as np x, y = np.loadtxt('num.txt', delimiter=',', unpack=True) plt.plot(x,y, label='Loaded from file!') plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show() whenever I run this code, it shows me this error UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 11: ordinal not in range(128)". how to open files in python on mac os ?
has comment: http://stackoverflow.com/comment/84152424
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84147853
linked to: http://stackoverflow.com/q/48259515
has comment: http://stackoverflow.com/comment/84151395

http://stackoverflow.com/comment/84077855
score: 0
comment on: http://stackoverflow.com/a/48541289
type: Comment
type: AnswerComment
has text: What could be the rationale for accepting this answer considering that it involves more logic than using `split(',')`?

http://stackoverflow.com/q/48618653
has comment: http://stackoverflow.com/comment/84233795
answer count: 3
has comment: http://stackoverflow.com/comment/84234199
has answer: http://stackoverflow.com/a/48618694
has comment: http://stackoverflow.com/comment/84233821
score: -4
linked to: http://stackoverflow.com/q/25201438
has answer: http://stackoverflow.com/a/48618746
has body: I have the following list: beerlist = [['', 'beer', 'uerige-doppel-sticke', '46158', ''], ['', 'beer', 'schumacher-1838er', '211568', ''], ['', 'beer', 'schlussel-stike', '53106', '']] and I would like to iterate through the list and print the 3rd value from each entry. I can access this individually, for example: beerList[2][3] But when I try to iterate through the list: for beer in beerList: print(beer[2]) I get the following error: IndexError: list index out of range I think I am misunderstanding something about accessing objects in a loop, what am I not getting here?
favorite count: 0
type: Question
has title: appending from a list of listts
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84233824
tagged with: python
has comment: http://stackoverflow.com/comment/84233828
downvote count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/48618714
tagged with: list

http://stackoverflow.com/q/48492274
has title: Python qrcode package - use of ECI
has comment: http://stackoverflow.com/comment/85067255
has comment: http://stackoverflow.com/comment/85020327
has comment: http://stackoverflow.com/comment/85000768
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84748155
has body: I'm programming an automated system which will automatically fill the input fields in universal payment order. This UPO has a QR code field and the QR code has very specific requirements: version: 15 data type: mode byte error connection level: M use of ECI size of module: 0,42333 mm x 0,42333 mm size: 32,59676 mm x 32,59667 mm minimum resolution: 600 x 600 DPI is there a python library that provides all of the functionalities? I looked at https://pypi.python.org/pypi/qrcode but I'm not sure if ECI is included.
favorite count: 0
type: Question
score: 1
tagged with: qr-code
tagged with: python

http://stackoverflow.com/comment/83984548
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48494750
score: 0
has text: Use withColumn() function, check the doc,http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html

http://stackoverflow.com/a/48555076
accepted answer of: http://stackoverflow.com/q/48554943
answers question: http://stackoverflow.com/q/48554943
type: Answer
has comment: http://stackoverflow.com/comment/84106772
upvote count: 2
score: 2
downvote count: 0
has body: def main(): answers = [ ['A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'], ['D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'], ['E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'], ['C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'], ['A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'], ['B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'], ['B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'], ['E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D']] keys = ['D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'] grades = [] # Grade all answers for i in range(len(answers)): # Grade one student correct_count = 0 for j in range(len(answers[i])): if answers[i][j] == keys[j]: correct_count += 1 grades.append([i, correct_count]) grades.sort(key=lambda x: x[1]) for student, correct in grades: print("Student", student,"'s correct count is", correct) if __name__ == '__main__': main() What you were doing was printing grades while you were still in the loop. If you would've printed grades after both loops, you would've only seen the last line: [[3, 4], [2, 5], [1, 6], [0, 7], [5, 7], [6, 7], [7, 7], [4, 8]], then just loop through grades and python will "unpack" the list into the student, and grade, respectively ash shown above. Here is the output: Student 3 's correct count is 4 Student 2 's correct count is 5 Student 1 's correct count is 6 Student 0 's correct count is 7 Student 5 's correct count is 7 Student 6 's correct count is 7 Student 7 's correct count is 7 Student 4 's correct count is 8 Don't forget to click the check mark if you like this answer.
has comment: http://stackoverflow.com/comment/84106665
type: AcceptedAnswer

http://stackoverflow.com/q/48644272
has body: I have an array which has intensity values from -3000 to 1000,I have thresholded all values which are less then -100 to -100 and all values greater than 400 to 400,After which i convert it to datatype np.uint8,Which makes all the values in the array to have intensity values from 0 to 255, What i am confused about is,is there an operation i can run which will give the array from 0-255 intensity range to the earlier one -100 to 400? Any suggestions will be useful,Thanks in advance
tagged with: python
has comment: http://stackoverflow.com/comment/84285427
upvote count: 1
has answer: http://stackoverflow.com/a/48644352
type: Question
score: 0
answer count: 2
has title: Encode array to uint8 and then back
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84285761
downvote count: 1
has comment: http://stackoverflow.com/comment/84285553
has comment: http://stackoverflow.com/comment/84286454
has answer: http://stackoverflow.com/a/48645838
favorite count: 0
has comment: http://stackoverflow.com/comment/84287108
has comment: http://stackoverflow.com/comment/84286077

http://stackoverflow.com/comment/84137208
has text: `Set WshShell = CreateObject("WScript.Shell")` Ops I was using WSH's `CreateObject` rather than VB's `CreateObject`.
score: 0
comment on: http://stackoverflow.com/a/48551489
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48546018
tagged with: import
type: Question
has comment: http://stackoverflow.com/comment/84088202
has comment: http://stackoverflow.com/comment/84100603
has comment: http://stackoverflow.com/comment/84088128
answer count: 0
type: UnansweredQuestion
tagged with: sys
has body: I'm trying to find a way to import a module automatically in my script if the directory of the module is in the same directory of the script. Here is the code: import sys import os cwd = os.getcwd() dirs= os.listdir(cwd) for dirName in dirs: if dirName == "arrayUtilities": modulePath = str(cwd) +"/" + str(dirName) sys.path.append(modulePath) import arrayUtilities as arr The script is in a directory where there is also the module's directory and it should work. Any help?
has comment: http://stackoverflow.com/comment/84101487
score: 0
has comment: http://stackoverflow.com/comment/84087792
tagged with: python
tagged with: directory
tagged with: module
has title: python: "sys.path.append" not taking parameter

http://stackoverflow.com/comment/84204876
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48597116
type: Comment
has text: Beautiful and simple !

http://stackoverflow.com/q/48640599
tagged with: tensorflow-estimator
score: 3
has comment: http://stackoverflow.com/comment/84496416
upvote count: 3
has comment: http://stackoverflow.com/comment/84476125
has title: Predict batch of images with a SageMaker model
downvote count: 0
tagged with: tensorflow-serving
answer count: 1
favorite count: 0
type: Question
has body: Thanks by advance for your help to solve this issue. I trained a model on Sagemaker. This is a TensorFlow estimator taking images as input, computing high-level features (ie bottlenecks) with InceptionV3, then using a dense layer to predict new classes. It kinda works: I can train it, serve it, and predict new images ONE AFTER ANOTHER. Now I'd like to predict a whole batch of images at once, in one unique HTTP call / predict() call. How? Here is how I do: from IPython.display import Image import numpy as np from keras.preprocessing import image estimator = TensorFlow(entry_point=..., ...) estimator.fit(train_data_location) predictor = estimator.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge') image_list = [ 'e9bfa679-31bb-464e-9d9f-3bdb0ef9c121.jpeg', # 131 'b27880e1-6de8-43cf-a684-bb02aef1e44b.jpeg', # 170 ] directory = '/path/to/dir/' images = np.empty((len(image_list), 299, 299, 3), dtype=np.float32) # for filename in image_list: for i,filename in enumerate(image_list): path = os.path.join(directory, filename) Image(path) img = image.load_img(path, target_size=(299, 299)) x = image.img_to_array(img) images[i] = x print(images.shape) # to_send = images[-1] # works for a unique image to_send = images # doesn't work for a batch of images # some other attempts that did not work # to_send = images.tolist() # to_send = [images[0].tolist(), images[1].tolist()] print(np.shape(to_send)) predict_response = predictor.predict(to_send) print('The model predicted the following classes: \n{}'.format( predict_response['outputs']['classes']['int64Val'])) This fires the following results: (2, 299, 299, 3) (2, 299, 299, 3) # Notice here the shape of what I send. So why does it complain about the shape [1,2,299,299,3] in the logs below ?? ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (500) from model with message "". See https://eu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logEventViewer…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51487621
tagged with: amazon-sagemaker

http://stackoverflow.com/comment/84229758
score: 0
has text: Hey I managed to execute the solution above after some slight modification. But when I tried to print out the sorted list by using print(month_groups), it prints out a lot values. Is there any way to print out only the total for each of the month?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48615462

multiprocessing
tags question: http://stackoverflow.com/q/48643343
tags question: http://stackoverflow.com/q/48595660
tags question: http://stackoverflow.com/q/48593694
tags question: http://stackoverflow.com/q/48543654
tags question: http://stackoverflow.com/q/48616071
tags question: http://stackoverflow.com/q/48516078
tags question: http://stackoverflow.com/q/48511247
tags question: http://stackoverflow.com/q/48504348
tags question: http://stackoverflow.com/q/48532648
tags question: http://stackoverflow.com/q/48623544
tags question: http://stackoverflow.com/q/48500567
tags question: http://stackoverflow.com/q/48504023
tags question: http://stackoverflow.com/q/48587804
tags question: http://stackoverflow.com/q/48581455
tags question: http://stackoverflow.com/q/48553651
tags question: http://stackoverflow.com/q/48579982
tags question: http://stackoverflow.com/q/48622638
tags question: http://stackoverflow.com/q/48491143
tags question: http://stackoverflow.com/q/48569867
tags question: http://stackoverflow.com/q/48633272
tags question: http://stackoverflow.com/q/48539989
tags question: http://stackoverflow.com/q/48509560
tags question: http://stackoverflow.com/q/48617627
tags question: http://stackoverflow.com/q/48489753
tags question: http://stackoverflow.com/q/48579685
type: Tag
tags question: http://stackoverflow.com/q/48551440
tags question: http://stackoverflow.com/q/48601103
tags question: http://stackoverflow.com/q/48634517
tags question: http://stackoverflow.com/q/48503994
tag name: multiprocessing
tags question: http://stackoverflow.com/q/48555439

http://stackoverflow.com/q/48521293
tagged with: python
has comment: http://stackoverflow.com/comment/84037238
has comment: http://stackoverflow.com/comment/84037107
has comment: http://stackoverflow.com/comment/84037186
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84037163
tagged with: matrix
answer count: 1
has title: Randomly remove and save elements from matrix
type: Question
tagged with: numpy
has body: I wrote this code snippet in Python: def remove_randomly(data, percentage): test_list = [] np.random.shuffle(data) for i in range(data.shape[0]): for j in range(data.shape[1]): roll = np.random.randint(low=1, high=100) if roll &gt; percentage: test_list.append((i, j, data[i, j])) data[i, j] = 0 It gets matrix data and a number percentage, iterates over the entire matrix, and zeros (100 - percentage) of the elements and saving them to another object called test_list. Is there a better, more efficient way to achieve this result? I've heard nested loops are bad for your health. Plus, my data matrix happens to be huge, so iterating with for loops is very slow. Example Suppose data is the matrix [1, 2; 3, 4] and percentage is 25%. Then I would like the output to be (for example) data = [1, 2; 0, 4] and test_list = [(1, 0, 3)]
has answer: http://stackoverflow.com/a/48521442
accepted answer: http://stackoverflow.com/a/48521442

http://stackoverflow.com/q/48508000
tagged with: python
type: AnsweredQuestion
score: 0
has body: I'm using drum template to build a reddit style website and I want to populate my database with some entries. My problem is that I'm not able to add a Link and the corresponding keywords. I was trying this (I add a few more attributes to the model): keywords_list = ['key1_test','key1_test'] u = User.objects.get(username = username) obj = Link( link = 'www.example.com', user = u, pub_date = datetime.datetime.now(), title = 'Title', description = 'blabla', fb_shares_ts = '', fb_reactions_ts = '', fb_comments_ts = '', fb_engagement_ts = '' ) for key in keywords_list: keyword, _ = Keyword.objects.get_or_create(title=key) obj.keywords.add(AssignedKeyword(keyword=keyword),bulk=False) obj.save() It gives me this error: django.db.utils.IntegrityError: NOT NULL constraint failed: generic_assignedkeyword.object_pk
answer count: 1
has answer: http://stackoverflow.com/a/48508071
accepted answer: http://stackoverflow.com/a/48508071
type: Question
has title: Save object model with keywords in Django
tagged with: django
tagged with: django-models

http://stackoverflow.com/q/48514315
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/48514651
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/48514382
has comment: http://stackoverflow.com/comment/84023256
score: 1
possible better answer: http://stackoverflow.com/a/48514406
has answer: http://stackoverflow.com/a/48514382
has answer: http://stackoverflow.com/a/48514463
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48514406
favorite count: 0
has body: I have a list of dictionaries: dictionaries = [ {'id': 1, 'name': 'test1', 'description': 'foo'}, {'id': 2, 'name': 'test2', 'description': 'bar'} ] I would like to separate the values from the keys in each dictionary, making a list of lists like this: [(1 ,'test1', 'foo'), (2, 'test2', 'bar')] I have the following code to perform this... values_list = [] for dict in dictionaries: values_list.append(list(dict.values())) When I run this code in my app, I get: TypeError: list() takes 0 positional arguments but 1 was given What's the right way to do this type of list comprehension?
type: Question
has comment: http://stackoverflow.com/comment/84087271
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48516183
has comment: http://stackoverflow.com/comment/84023192
answer count: 5
has title: How to Extract Values from Dictionaries and Create Lists From Them
tagged with: python
has comment: http://stackoverflow.com/comment/84023159
tagged with: dictionary

http://stackoverflow.com/comment/84184034
type: AnswerComment
has text: it would help if you deleted your line breaks in the string....
type: Comment
comment on: http://stackoverflow.com/a/48593428
score: 0

http://stackoverflow.com/a/48725336
downvote count: 0
has body: It is simple enough to write your own implementation of EM algorithm. It would also give you a good intuition of the process. I assume that covariance is known and that prior probabilities of components are equal, and fit only means. The class would look like this (in Python 3): import numpy as np import matplotlib.pyplot as plt from scipy.stats import multivariate_normal class FixedCovMixture: """ The model to estimate gaussian mixture with fixed covariance matrix. """ def __init__(self, n_components, cov, max_iter=100, random_state=None, tol=1e-10): self.n_components = n_components self.cov = cov self.random_state = random_state self.max_iter = max_iter self.tol=tol def fit(self, X): # initialize the process: np.random.seed(self.random_state) n_obs, n_features = X.shape self.mean_ = X[np.random.choice(n_obs, size=self.n_components)] # make EM loop until convergence i = 0 for i in range(self.max_iter): new_centers = self.updated_centers(X) if np.sum(np.abs(new_centers-self.mean_)) &lt; self.tol: break else: self.mean_ = new_centers self.n_iter_ = i def updated_centers(self, X): """ A single iteration """ # E-step: estimate probability of each cluster given cluster centers cluster_posterior = self.predict_proba(X) # M-step: update cluster centers as weighted average of observations weights = (cluster_posterior.T / cluster_posterior.sum(axis=1)).T new_centers = np.dot(weights, X) return new_centers def predict_proba(self, X): likelihood = np.stack([multivariate_normal.pdf(X, mean=center, cov=self.cov) for center in self.mean_]) cluster_posterior = (likelihood / likelihood.sum(axis=0)) return cluster_posterior def predict(self, X): return np.argmax(self.predict_proba(X), axis=0) On the data like yours, the model would converge quickly: np.random.seed(1) X = np.random.normal(size=(100,2), scale=3) X[50:] += (10, 5) model = FixedCovMixture(2, cov=[[3,0],[0,3]], random_state=1) model.fit(X) print(model.n_iter_, 'iterations') print(model.mean_) plt.scatter(X[:,0], X[:,1],…
accepted answer of: http://stackoverflow.com/q/48502153
type: AcceptedAnswer
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/48502153
has comment: http://stackoverflow.com/comment/128926606
has comment: http://stackoverflow.com/comment/84449965
score: 9

http://stackoverflow.com/q/48613356
tagged with: python
score: -1
tagged with: modem
has body: When I change some parameter and turn it to correct value on DSL Configuration of Modem Settings, IP that I am using changes so I wanted to write a python code to login modem interface(192.168.1.1) and change some parameter on DSL Configuration. I am able to login but I can not post the port data but indeed the parameter does not change. The code that I am using is somewhat like below; payload = {'Password': '1111', 'Username': 'admin','action':'login','LoginId':'Login'} page = requests.post('http://192.168.1.1',data=payload) payload ='?TypeUplink=1&amp;pageType=0&amp;IF_ACTION=Apply&amp;_InstID=IGD.WD1.WCD2.WCPPP1&amp;InstHasGot=1&amp;ControlType=0&amp;WANCName=ttt&amp;xdslMode=2' page = requests.post('http://192.168.1.1/common_page/Internet_Internet_lua.lua'+payload) My Modem is ZTE ZXHN H267N.
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/48613907
upvote count: 1
has comment: http://stackoverflow.com/comment/84223817
tagged with: python-requests
has title: How to change modem settings with Python Code
favorite count: 0
tagged with: ip
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84223473

http://stackoverflow.com/comment/84255614
score: 1
type: Comment
has text: pandas should be able to handle a million rows easily, though it may choke on the merge, since that could give an _O(N²)_ expansion in memory or time if it's implemented poorly in pandas. What I wanted to point out, indirectly, is that your solution is still operating in _O(N²)_ time, just more efficiently than OP's. This means that it will scale poorly regardless of memory limitations.
comment on: http://stackoverflow.com/a/48629104
type: AnswerComment

http://stackoverflow.com/comment/84052403
type: Comment
has text: @Aaron no errors, the contours just dont appear after using the cv2.drawContours
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48528417

http://stackoverflow.com/a/48517739
upvote count: 1
answers question: http://stackoverflow.com/q/48517652
has body: Use itertools.groupby() with a key function: from itertools import groupby l = ['t', 'p', 'k', 'F', 'p', 'l', 'v', 'F'] result = [list(g) for k, g in groupby(l, key=lambda x: x != 'F') if k] &gt;&gt;&gt; result [['t', 'p', 'k'], ['p', 'l', 'v']] Another way is with string operations: result = [list(x) for x in ''.join(l).split('F') if x] &gt;&gt;&gt; result [['t', 'p', 'k'], ['p', 'l', 'v']] Note that both solutions above will include any trailing items that follow the final 'F'. Not sure if that is what you want?
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/84312909
score: 0
comment on: http://stackoverflow.com/a/48643261
type: Comment
has text: This statement should be parsed like "Ram and Sita likes mangos and apples respectively". But here x and y are not categorized as nouns, so that is the challenge in this task.
type: AnswerComment

http://stackoverflow.com/q/48581973
tagged with: anaconda
has title: Spyder 3 (Anaconda) on Ubuntu- How to change working directory to that of terminal
tagged with: spyder
accepted answer: http://stackoverflow.com/a/48583070
type: Question
has answer: http://stackoverflow.com/a/48583070
answer count: 2
has answer: http://stackoverflow.com/a/48586985
tagged with: python
tagged with: python-idle
tagged with: ubuntu
possible better answer: http://stackoverflow.com/a/48586985
type: AnsweredQuestion
score: 0
has body: I'm using Spyder 3 bundled with Anaconda Python on Ubuntu. Usually with other Python IDEs (like IDLE,...) when i want to work inside a specific folder, I just go to that folder then open a terminal, type "idle" and the IDE pops up, then I can work inside that folder. But with Spyder when i open a terminal, type "spyder" , the Spyder IDE still works at the default directory! How can I change this? Please help me, thank you very much

gtk
tags question: http://stackoverflow.com/q/48490196
type: Tag
tag name: gtk
tags question: http://stackoverflow.com/q/48523365
tags question: http://stackoverflow.com/q/48638872
tags question: http://stackoverflow.com/q/48585493
tags question: http://stackoverflow.com/q/48559407
tags question: http://stackoverflow.com/q/48523344

http://stackoverflow.com/q/48516612
has comment: http://stackoverflow.com/comment/84027680
has answer: http://stackoverflow.com/a/48516936
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/84027519
has comment: http://stackoverflow.com/comment/84027785
type: Question
has comment: http://stackoverflow.com/comment/84027602
tagged with: django-templates
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84028263
has answer: http://stackoverflow.com/a/48516945
has comment: http://stackoverflow.com/comment/84027583
type: UnansweredQuestion
has title: django invalid field name(s) for model content type
has comment: http://stackoverflow.com/comment/84027585
tagged with: django
has comment: http://stackoverflow.com/comment/84027692
has body: i looked all around internet i can't find a solution for this error in django this script is worked on by one of the developers before me i'm trying to run ./manage.py migrate but it keeps getting this output django.core.exceptions.FieldError: Invalid field name(s) for model ContentType: 'name'. and this is the whole traceback this is the content of manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smsg.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)

http://stackoverflow.com/q/48625239
upvote count: 9
has answer: http://stackoverflow.com/a/48636722
has title: ValueError: Invalid endpoint: s3-api.xxxx.objectstorage.service.networklayer.com
answer count: 2
favorite count: 0
score: 9
type: Question
has comment: http://stackoverflow.com/comment/84270683
has answer: http://stackoverflow.com/a/48625240
has body: I'm trying to access a csv file in my Watson Data Platform catalog. I used the code generation functionality from my DSX notebook: Insert to code > Insert StreamingBody object. The generated code was: import os import types import pandas as pd import boto3 def __iter__(self): return 0 # @hidden_cell # The following code accesses a file in your IBM Cloud Object Storage. It includes your credentials. # You might want to remove those credentials before you share your notebook. os.environ['AWS_ACCESS_KEY_ID'] = '******' os.environ['AWS_SECRET_ACCESS_KEY'] = '******' endpoint = 's3-api.us-geo.objectstorage.softlayer.net' bucket = 'catalog-test' cos_12345 = boto3.resource('s3', endpoint_url=endpoint) body = cos_12345.Object(bucket,'my.csv').get()['Body'] # add missing __iter__ method so pandas accepts body as file-like object if not hasattr(body, "__iter__"): body.__iter__ = types.MethodType(__iter__, body) df_data_2 = pd.read_csv(body) df_data_2.head() When I try to run this code, I get: /usr/local/src/conda3_runtime.v27/4.1.1/lib/python3.5/site-packages/botocore/endpoint.py in create_endpoint(self, service_model, region_name, endpoint_url, verify, response_parser_factory, timeout, max_pool_connections) 270 if not is_valid_endpoint_url(endpoint_url): 271 --&gt; 272 raise ValueError("Invalid endpoint: %s" % endpoint_url) 273 return Endpoint( 274 endpoint_url, ValueError: Invalid endpoint: s3-api.us-geo.objectstorage.service.networklayer.com What is strange is that if I generate the code for SparkSession setup instead, the same endpoint is used but the spark code runs ok. How can I fix this issue? I'm presuming the same issue will be encountered for the other Softlayer endpoints so I'm listing them here as well to ensure this question is also applicable for the other softlayer locations: s3-api.us-geo.objectstorage.softlayer.net s3-api.dal-us-geo.objectstorage.softlayer.net s3-api.sjc-us-geo.objectstorage.softlayer.net s3-api.wdc-us-geo.objectstorage.softlayer.net s3.us-so…
tagged with: ibm-cloud
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84269860
accepted answer: http://stackoverflow.com/a/48625240
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48636722
tagged with: data-science-experience

http://stackoverflow.com/q/48559775
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84115338
tagged with: string
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question
linked to: http://stackoverflow.com/q/24076297
has comment: http://stackoverflow.com/comment/84115417
tagged with: python
has title: How to truncate and pad in python3 using just str.format?
accepted answer: http://stackoverflow.com/a/48560618
has body: I would like to do this: '{pathname:&gt;90}'.format(pathname='abcde')[-2:] using string formatting instead of array indexing. So the result would be 'de' or in the case of pathname='e' the result would be ' e' with a space before e. If the index would be [2:] this question would be answered by How to truncate a string using str.format in Python? I need this in the following example: import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO,style='{',format='{pathname:&gt;90}{lineno:4d}{msg}') logging.info('k')
has answer: http://stackoverflow.com/a/48560618
has comment: http://stackoverflow.com/comment/84115255
has comment: http://stackoverflow.com/comment/84115290
score: 2

http://stackoverflow.com/comment/84156599
score: 0
type: QuestionComment
type: Comment
has text: I have seen this problem before. May be you do not have permission to run that command, or that command is not executable.
comment on: http://stackoverflow.com/q/48579428

http://stackoverflow.com/q/48630060
accepted answer: http://stackoverflow.com/a/48630346
has answer: http://stackoverflow.com/a/48630346
has title: Select N rows above and below a specific row in pandas
type: AnsweredQuestion
upvote count: 14
tagged with: pandas
has body: I have this data frame and I want to select 10 rows before and after on a specific column. I have reached up to this point but I was wondering how to make it more elegant in a lambda python expression as I need to run this on a loop 10 thousand times. import pandas as pd df = pd.DataFrame(data=np.random.rand(90), index=pd.date_range('2015-01-01','2015-03-31'),columns=['A']) I have reached to this as an solution in progress: 10 observations before and after: df.loc['2015-01-17':].head(11)[1:11].transpose() ! before df.loc[:'2015-01-17'].tail(11)[0:10].transpose() ! after So, how can I make this is in a loop with a lambda expression and having not only one index but two indexes?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
score: 14
tagged with: indexing
tagged with: dataframe
tagged with: python

pre-trained-model
tag name: pre-trained-model
tags question: http://stackoverflow.com/q/48637407
type: Tag

arrays
tags question: http://stackoverflow.com/q/48501432
tags question: http://stackoverflow.com/q/48542940
tags question: http://stackoverflow.com/q/48588932
tag name: arrays
tags question: http://stackoverflow.com/q/48532003
tags question: http://stackoverflow.com/q/48551298
tags question: http://stackoverflow.com/q/48562295
tags question: http://stackoverflow.com/q/48609781
tags question: http://stackoverflow.com/q/48625812
tags question: http://stackoverflow.com/q/48592264
tags question: http://stackoverflow.com/q/48555747
tags question: http://stackoverflow.com/q/48573004
tags question: http://stackoverflow.com/q/48593563
tags question: http://stackoverflow.com/q/48564368
tags question: http://stackoverflow.com/q/48546075
tags question: http://stackoverflow.com/q/48547499
tags question: http://stackoverflow.com/q/48604403
tags question: http://stackoverflow.com/q/48539344
tags question: http://stackoverflow.com/q/48597434
type: Tag
tags question: http://stackoverflow.com/q/48633293
tags question: http://stackoverflow.com/q/48605430
tags question: http://stackoverflow.com/q/48574252
tags question: http://stackoverflow.com/q/48596724
tags question: http://stackoverflow.com/q/48525210
tags question: http://stackoverflow.com/q/48537563
tags question: http://stackoverflow.com/q/48633660
tags question: http://stackoverflow.com/q/48608710
tags question: http://stackoverflow.com/q/48569341
tags question: http://stackoverflow.com/q/48627182
tags question: http://stackoverflow.com/q/48561794
tags question: http://stackoverflow.com/q/48569965
tags question: http://stackoverflow.com/q/48535471
tags question: http://stackoverflow.com/q/48534819
tags question: http://stackoverflow.com/q/48552101
tags question: http://stackoverflow.com/q/48591523
tags question: http://stackoverflow.com/q/48502253
tags question: http://stackoverflow.com/q/48631638
tags question: http://stackoverflow.com/q/48584422
tags question: http://stackoverflow.com/q/48640535
tags question: http://stackoverflow.com/q/48627163
tags question: http://stackoverflow.com/q/48543200
tags question: http://stackoverflow.com/q/48531876
tags question: http://stackoverflow.com/q/48621111
tags question: http://stackoverflow.com/q/48603533
tags question: http://stackoverflow.com/q/48631106
tags question: http://stackoverflow.com/q/48632881
tags question: http://stackoverflow.com/q/48488998
tags question: http://stackoverflow.com/q/48500590
tags question: http://stackoverflow.com/q/48599009
tags question: http://stackoverflow.com/q/48584855
tags question: http://stackoverflow.com/q/48572322
tags question: http://stackoverflow.com/q/48536540
tags question: http://stackoverflow.com/q/48638838
tags question: http://stackoverflow.com/q/48608540
tags question: http://stackoverflow.com/q/48631113
tags question: http://stackoverflow.com/q/48613828
tags question: http://stackoverflow.com/q/48637042
tags question: http://stackoverflow.com/q/48629230
tags question: http://stackoverflow.com/q/48582102
tags question: http://stackoverflow.com/q/48530915
tags question: http://stackoverflow.com/q/48543002
tags question: http://stackoverflow.com/q/48549018
tags question: http://stackoverflow.com/q/48566704
tags question: http://stackoverflow.com/q/48515415
tags question: http://stackoverflow.com/q/48606909
tags question: http://stackoverflow.com/q/48550999
tags question: http://stackoverflow.com/q/48593683
tags question: http://stackoverflow.com/q/48493343
tags question: http://stackoverflow.com/q/48546571
tags question: http://stackoverflow.com/q/48582908
tags question: http://stackoverflow.com/q/48569301
tags question: http://stackoverflow.com/q/48613158
tags question: http://stackoverflow.com/q/48581080
tags question: http://stackoverflow.com/q/48522316
tags question: http://stackoverflow.com/q/48553531
tags question: http://stackoverflow.com/q/48584403
tags question: http://stackoverflow.com/q/48508923
tags question: http://stackoverflow.com/q/48632817
tags question: http://stackoverflow.com/q/48567497

http://stackoverflow.com/a/48561836
answers question: http://stackoverflow.com/q/48556353
has body: Assuming you are not working with spatially structured data (e.g. images, sounds, time series, etc.), then the order and shape of the features doesn't matter to the model. If that is the case, then a simple reshape should do the trick: model.fit(trainFeatures.reshape(127, -1), trainLabels) In any case, I'd suggest you to drop the fourth dimension with trainFeatures.squeeze(). If you feel that the 9 by 6 structure of the features is important, then you could try using convolutional neural networks (if each sample is, semantically, a grid), or recurrent neural networks (if each sample is a sequence of 9 steps of a 6-dimensional signal). Cheers
score: 1
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84254815
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48610824
has text: Preferably it working from Python 2.6-3.6.x as of the time of this writing, for instance, CentOS/RHEL 6 comes with Python 2.6, and despite even Python 2.7 approaching EOL, RHEL/CentOS 6 is valid until 2020 for primary update, and 2024 for maintenance, since the project I am starting is targeting a corporate env, ideally it will work across.
score: 0

http://stackoverflow.com/a/49512785
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48601123
type: Answer
upvote count: 1
has body: This error happens when you try to add an object to a session but it is already loaded. The only line that I see you use .add function is at the end where you run: connection.connect.add(article) So my guess is that this Model is already loaded in the session and you don't need to add it again. You can add a try, except and rollback the operation if it throws an exception.

http://stackoverflow.com/q/48598429
has comment: http://stackoverflow.com/comment/84193835
tagged with: django
tagged with: django-models
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48681403
has comment: http://stackoverflow.com/comment/84193320
answer count: 1
has body: I'm working on a 'workflow management website' where different workflows with different steps can be tracked. A workflow is defined by a number of steps with a given order. A 'Job' realizes the workflow and 'Tasks' realize the steps. class Workflow(models.Model): name = models.CharField(_('Name'),max_length = 100, unique = True) class Step(models.Model): workflow = models.ForeignKey( Workflow, on_delete=models.CASCADE, ) name = models.CharField(_('Name'), max_length = 100) order = models.SmallIntegerField(_('Reihenfolge')) class Job(models.Model): workflow = models.ForeignKey( Workflow, on_delete=models.CASCADE, ) def current_task(self): # first task without finished date my_tasks = self.task_set\ .filter(finished__isnull=True)\ .order_by('step__order') if my_tasks.exists(): return my_tasks.first() return False class Task(models.Model): job = models.ForeignKey( Job, on_delete=models.CASCADE, ) step = models.ForeignKey( 'Step', on_delete=models.CASCADE, ) assigned_to = models.ForeignKey( User, on_delete=models.CASCADE, ) The current task of a workflow is the 'first' task without a 'finished' date (ordering is given by task.step.order). If there is no such task, the job is finished. My question is how to filter current tasks for a number of jobs. For example, I want to filter Jobs where the current task is assigned_to some user. So far I used a for-loop and checked job.current_task().assigned_to for each job, but this obviously is a pretty slow/dumb way of doing that. Is there a more efficient way? I could, of course, add an additional relationship (not DRY) which points from Job to the current task, but that shouldn't be necessary? EDIT: Here is my current approach for filtering jobs (given by 'queryset') where the current task is assigned to 'myuser': for job in queryset: if not job.current_task() or not job.current_task().assigned_to == myuser: exclude.append(job.id) queryset_filtered = queryset.exclude(id__in=exclude)
has title: Django: How to filter related objects based on different criteria?
type: Question
type: UnansweredQuestion

graphlab
tags question: http://stackoverflow.com/q/48631680
tag name: graphlab
type: Tag

http://stackoverflow.com/q/48639106
tagged with: python
accepted answer: http://stackoverflow.com/a/48639634
has answer: http://stackoverflow.com/a/48639634
has body: I am trying to use Gaussian Processes for fitting smooth functions to some datapoints. I am using scikit-learn library for python and in my case my input are two dimensional spatial coordinates and the output are some transformed version and also 2-D spatial coordinates. I generated some dummy test data and tried to fit a GP model to it. The code that I used was as follows: from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C import numpy as np # Some dummy data X = np.random.rand(10, 2) Y = np.sin(X) # Use the squared exponential kernel kernel = C(1.0, (1e-3, 1e3)) * RBF(10, (1e-2, 1e2)) gp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9) # Fit to data using Maximum Likelihood Estimation of the parameters gp.fit(X, Y) print(X) # Evaluate on a test point test = np.random.rand(1, 2) test[:, 0] = 1.56 test[:, 1] = 0.92 y_pred, sigma = gp.predict(test, return_std=True) print(test, np.sin(test)) # The true value print(y_pred, sigma) # The predicted value and the STD I was wondering if there is a good way to visualize the model fit. As my input and output dimensions are both 2-D, I am not sure how I can visualize it quickly so that I get an idea of the model fit (particularly want to know the smoothness and variance of the model prediction between the points). Most examples online are, of course, for 1-D case.
has title: visualizing high dimension data in matplotlib/python
type: AnsweredQuestion
score: 0
tagged with: scikit-learn
answer count: 1
type: Question
tagged with: data-visualization
tagged with: matplotlib

http://stackoverflow.com/comment/84119403
type: Comment
score: 0
has text: @SIM Of course. Headless mode works the same as GUI mode.
type: AnswerComment
comment on: http://stackoverflow.com/a/48557308

http://stackoverflow.com/a/48591571
upvote count: 2
has comment: http://stackoverflow.com/comment/84180669
downvote count: 0
type: Answer
has body: You can try something like this. It sounds much simpler, but I'm not sure it will fit your needs. # setting the time as index df = df.set_index('Time') # grouping by hour grouped = df.groupby(df.index.hour) # computing various stats grouped = grouped.agg(['std', 'mean', 'skew']).transpose().unstack() # cosmetics dropping a useless column level grouped.columns = grouped.columns.droplevel() grouped # std mean skew # A1 NaN 1.0 NaN # A2 0.707107 1.5 NaN # A3 NaN 3.0 NaN # AB40 NaN NaN NaN Alternative Starting from pandas 0.20 you can use agg directly on the DataFrame to compute various stats. See detail here. It should be worth considering it for what you are trying to do. df.agg(['std', 'mean', 'skew']).transpose() # std mean skew # A1 NaN 1.0 NaN # A2 0.707107 1.5 NaN # A3 NaN 3.0 NaN # AB40 NaN NaN NaN
has comment: http://stackoverflow.com/comment/84201167
answers question: http://stackoverflow.com/q/48590694
score: 2
has comment: http://stackoverflow.com/comment/84188778

http://stackoverflow.com/comment/84176555
comment on: http://stackoverflow.com/a/48589494
type: Comment
type: AnswerComment
has text: Thanks Dan for your response. I understand what you're saying: list will parse the entire file and return all values matching keys. I made the changes you suggested. However, when running the code, I now get a "TypeError: 'NoneType' object is not iterable" on the lat variable.
score: 0

http://stackoverflow.com/a/48640116
has body: It appears you're looking for enchantdict.store_replacement('Nr', 'Nummer'). It's explained in the documentation, not that hard to find.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48640004
type: Answer
accepted answer of: http://stackoverflow.com/q/48640004
has comment: http://stackoverflow.com/comment/84277016
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48563138
has answer: http://stackoverflow.com/a/48564706
tagged with: class
tagged with: object
has comment: http://stackoverflow.com/comment/84121962
has comment: http://stackoverflow.com/comment/84121963
has title: Variable defined in do_local generates error: The variable ... is referenced before it is declared
tagged with: python
has body: I am trying to understand namespaces in Python. I tried this scenario as given in Python documentation. def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" do_local() print("before local assignment:", spam) do_nonlocal() print("before nonlocal assignment:", spam) do_global() print("before global assignment:", spam) spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) This fails saying: The variable spam is referenced before its declared. I have clearly defined the variable in the do_local().
score: -1
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: namespaces
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/48550681
answers question: http://stackoverflow.com/q/48550643
type: Answer
has body: import matplotlib.pyplot as plt This should work. You need to import plot as well. Just importing matplotlib is not enough.
score: 0

http://stackoverflow.com/comment/84073242
has text: Ok thanks but i know that, so only i asked about overriding internal function.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48538043
type: Comment

http://stackoverflow.com/a/48536402
score: 0
has body: If X=[-1,0,1,2,3], for onehot you can try: from sklearn.preprocessing import OneHotEncoder one_hot_enc=OneHotEncoder() X_onehot=one_hot_enc.fit_transform(X.reshape(-1,1)) #reshape to convert 1-d array to 2-d array print(X_onehot.toarray()) Since you have negative values like -1 in your class, trying one_hot will throw ValueError: X needs to contain only non-negative integers. for this you can first try Label-encoding first: from sklearn.preprocessing import LabelEncoder enc=LabelEncoder() x_new=enc.fit_transform(X) print(x_new.classes_) feed x_new in place of X to OneHotEncoder
answers question: http://stackoverflow.com/q/48535962
type: Answer
has comment: http://stackoverflow.com/comment/84080864

http://stackoverflow.com/q/48525626
downvote count: 0
answer count: 1
tagged with: python
has body: I have this database model... class Distributor(Base): __tablename__ = 'distributor' id = Column(Integer, primary_key=True) commercial_address_id = Column(Integer, ForeignKey('addresses.id'), nullable=False, unique=True) invoice_address_id = Column(Integer, ForeignKey('addresses.id'), nullable=False, unique=True) commercial_address = relationship(Address, lazy="noload", foreign_keys=[commercial_address_id]) invoice_address = relationship(Address, lazy="noload", foreign_keys=[invoice_address_id]) class Address(Base): __tablename__ = 'address' id = Column(Integer, primary_key=True) address_name = Column(String(64)) country_id = Column(Integer, ForeignKey('countries.id'), nullable=False) country = relationship(Country, lazy="noload") class Country(Base): __tablename__ = 'country' id = Column(Integer, primary_key=True) code = Column(Integer) ...then I do the query to the database... alias_commercial_address = aliased(Distributor.invoice_address) alias_commercial_address_country = aliased(Address.country) alias_invoice_address = aliased(Distributor.commercial_address) alias_invoice_address_country = aliased(Address.country) return Distributor.query\ .outerjoin(alias_commercial_address, Distributor.commercial_address)\ .outerjoin(alias_commercial_address_country, Address.country)\ .outerjoin(alias_invoice_address, Distributor.invoice_address)\ .outerjoin(alias_invoice_address_country, Address.country)\ .options(contains_eager(Distributor.commercial_address, alias=alias_commercial_address) .contains_eager(Address.country, alias=alias_commercial_address_country), contains_eager(Distributor.invoice_address, alias=alias_invoice_address) .contains_eager(Address.country, alias=alias_invoice_address_country))\ .all() ...but the framework generates the query incorrectly... SELECT ... FROM distributors LEFT OUTER JOIN addresses AS addresses_1 ON addresses_1.id = distributors.commercial_address_id LEFT OUTER JOIN countries AS countries_1 ON countries_1.id = addresses_1.country_id L…
has answer: http://stackoverflow.com/a/48528135
score: 2
accepted answer: http://stackoverflow.com/a/48528135
type: AnsweredQuestion
tagged with: mysql
tagged with: sqlalchemy
favorite count: 0
type: Question
upvote count: 2
has title: Multiple joins with SQLAlchemy

http://stackoverflow.com/a/48554230
has comment: http://stackoverflow.com/comment/84107824
has body: As discussed below, you need 2 lists. One with x coordinates of all players and one with y. Here is the code: import pandas data = pandas.read_csv('Wide_Single_timestamp2.csv') x_list = [] y_list = [] for row in data.index: for player in ['Player 1', 'Player 2', 'Player 3']: x = data.loc[row, player + '_X'] y = data.loc[row, player + '_Y'] if x &lt; 5: x = None y = None if x: x_list.append(x) if y: y_list.append(y)
has comment: http://stackoverflow.com/comment/84111026
has comment: http://stackoverflow.com/comment/84108213
has comment: http://stackoverflow.com/comment/84107575
type: Answer
has comment: http://stackoverflow.com/comment/84107143
has comment: http://stackoverflow.com/comment/84110729
has comment: http://stackoverflow.com/comment/84107936
has comment: http://stackoverflow.com/comment/84109720
has comment: http://stackoverflow.com/comment/84109680
has comment: http://stackoverflow.com/comment/84108651
has comment: http://stackoverflow.com/comment/84105866
score: 0
answers question: http://stackoverflow.com/q/48553991
has comment: http://stackoverflow.com/comment/84106698
has comment: http://stackoverflow.com/comment/84107776
has comment: http://stackoverflow.com/comment/84113525

http://stackoverflow.com/q/48562457
has comment: http://stackoverflow.com/comment/84120457
possible better answer: http://stackoverflow.com/a/48562571
has answer: http://stackoverflow.com/a/48562571
type: AnsweredQuestion
has body: I'm creating a program where it collects data from the user, I have finished the basic inputs of collecting their first name, surname, age etc; however I wanted the user to have no numbers in their first name or surname. If the user types a number in their first name such as "Aaron1" or their surname as "Cox2"; it would repeat the question asking for their name again. Attempt 1 firstname=input("Please enter your first name: ") if firstname==("1"): firstname=input("Your first name included a number, please re-enter your first name") else: pass Attempt 2 firstname=input("Please enter your first name: ") try: str(firstname) except ValueError: try: float(firstname) except: firstname=input("Re-enter your first name: ") Any suggestions?
score: 0
has comment: http://stackoverflow.com/comment/84120541
linked to: http://stackoverflow.com/q/19859282
tagged with: python
has title: If user types numbers instead of letters, show this error
duplicate of: http://stackoverflow.com/q/19859282
has comment: http://stackoverflow.com/comment/84120487
type: Question
has answer: http://stackoverflow.com/a/48562513
accepted answer: http://stackoverflow.com/a/48562513
answer count: 2
tagged with: validation

http://stackoverflow.com/q/48537026
has answer: http://stackoverflow.com/a/48537279
has answer: http://stackoverflow.com/a/48537261
tagged with: python
possible better answer: http://stackoverflow.com/a/48566093
has answer: http://stackoverflow.com/a/48537240
has body: I try to read a csv file which I need to convert into a list of floats for evaluation. The list looks like this: [['Time [s];17063_X;17063_Y;17063_Z;17064_X;17064_Y;17064_Z;17065_X;17065_Y;17065_Z;17067_X;17067_Y;17067_Z;17068_X;17068_Y;17068_Z'], ['0;0.01952;0.04337;0.0242;0.01151;0.04152;0.03236;0.00015;-0.01679;0.05328;0.02872;0.01717;0.09341;0.01452;0.01489;0.07444'], ['0.00042;0.02188;0.04351;0.02803;0.0062;0.04108;0.03312;-0.00529;-0.01412;0.05167;0.02173;0.01377;0.04098;0.00807;0.00246;0.04354'],...] but actually it has more than 17000 additional entries. The list I need should look like this: [['Time [s]', '17063_X', '17063_Y', '17063_Z', '17064_X', '17064_Y', '17064_Z', '17065_X', '17065_Y', '17065_Z', '17067_X', '17067_Y', '17067_Z', '17068_X', '17068_Y', '17068_Z'], [0, 0.01952, 0.04337, 0.0242, 0.01151, 0.04152, 0.03236, 0.00015, -0.01679, 0.05328, 0.02872, 0.01717, 0.09341, 0.01452, 0.01489, 0.07444], ...] So far I managed to get a single line (last element in list) into this format but not all the list. Here is what I've got so far: import csv with open(filepath, 'r') as f: reader = csv.reader(f) data = list(reader) for j in range(1, len(data)): # this loop does nothing?! for i in data[j]: dt = i.split(';') da = [float(i) for i in dt] print(da) Out: [0.005, 0.0207, 0.02925, 0.02095, 0.02332, 0.04211, 0.02223, 0.0075, -0.01961, 0.05093, 0.02604, 0.00711, 0.06644, 0.00689, -0.00092, 0.04737] I would appreciate any help and also some tips when it comes to list comprehension. Thanks!
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48537108
tagged with: split
downvote count: 0
accepted answer: http://stackoverflow.com/a/48537240
tagged with: string
has answer: http://stackoverflow.com/a/48566093
favorite count: 0
type: Question
type: AnsweredQuestion
answer count: 5
has title: Converting sublist of string (csv) to float (list comprehension)
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/84184608
type: Comment
type: QuestionComment
has text: Also, you'll get better answers if you include code that can be run, not just console output. Right now, `data` and `tf.data` could be any size.
comment on: http://stackoverflow.com/q/48593683
score: 0

http://stackoverflow.com/q/48496741
downvote count: 1
accepted answer: http://stackoverflow.com/a/48496803
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48496803
tagged with: python
type: AnsweredQuestion
score: 0
has title: Pandas adding sub columns
tagged with: pandas
has body: I have a df: Id Day Name Value1 Value2 Value3 ... Value10 factor 11 1 x 1 2 3 ... 10 2 11 1 y 10 9 8 ... 1 2 11 1 z 2 2 2 ... 2 2 22 2 i 3 3 4 ... 4 3 22 2 j 0 0 1 ... 1 3 My goal is to sum the values in the "Value" columns and multiply it by its factor. The output would be: Id Day Value1 Value2 Value3 ... Value10 11 1 2*(1+10+2) 2*(2+0+2) 2*(3+8+2) 2*(10+1+2) 22 2 3*(3+0) 3*(3+0) 3*(4+1) 3*(4+1) My approach is to group them by ID but then I don't want to add the "Day", and I'm not sure what would be the right way to handle this. Many thanks!
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/84210001
has text: for f in glob.glob(os.path.join(faces_folder_path, "*.JPG")): fh = open(f + ".txt","w") print("Processing file: {}".format(f)) img = io.imread(f)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48606898
score: 0

http://stackoverflow.com/q/48528536
tagged with: python
possible better answer: http://stackoverflow.com/a/48528853
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48528853
accepted answer: http://stackoverflow.com/a/48528995
tagged with: pandas
has answer: http://stackoverflow.com/a/48528995
has body: My goal is to add a column where it would display the field name(s) of the empty cell. Name x y z abc 1 3 0 ijk m lmn 1 2 3 The new column would be: Name x y z Empty abc 1 3 y 0 x,Name,z ijk m y,z lmn 1 a c I've tried: pd.isnull(df).any(1).nonzero() but this only show the row that contains empty cell. Many thanks! :)
favorite count: 0
type: Question
has title: Pandas output null column
answer count: 2
score: 2
upvote count: 2
tagged with: null
downvote count: 0

http://stackoverflow.com/comment/84255174
has text: Dear @apogalaction , i did the pyinstaller --debug, but after that dist folder became empty. Also, enum34 is not installed, I checked. This above said error is not shown up.
type: Comment
comment on: http://stackoverflow.com/a/48628671
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84261245
score: 0
comment on: http://stackoverflow.com/a/48631964
type: AnswerComment
has text: Do you know how stackoverflow chat works? I can't find it
type: Comment

http://stackoverflow.com/q/48532034
has title: Numpy: tile a matrix into a higher dimension, but with scale
favorite count: 0
has comment: http://stackoverflow.com/comment/84059741
tagged with: numpy
score: 2
upvote count: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48532309
has body: I need to implement the following behavior in NumPy: a = [1, 2, 3] b = [[1, 0], [0, 1]] c = f(a, b) &gt; c = [[[1, 0], [0, 1]], [[2, 0], [0, 2]], [[3, 0], [0, 3]]] I can implement this with np.outer(a, b.flatten()).reshape(a.shape + b.shape), but that is non-obvious and requires a comment to make the intention of the code clear. Is there any built-in function that gives this behavior?
downvote count: 0
has answer: http://stackoverflow.com/a/48532183
tagged with: python
has answer: http://stackoverflow.com/a/48532309
has answer: http://stackoverflow.com/a/48532164
type: Question
answer count: 3
accepted answer: http://stackoverflow.com/a/48532164

http://stackoverflow.com/a/48552303
accepted answer of: http://stackoverflow.com/q/48551332
answers question: http://stackoverflow.com/q/48551332
type: Answer
score: 0
has body: You may need to extract the data by 3 columns group. Then rename the columns and add the "A,B,C" flag column and concatenate them together. See the test as below: abc_list = [["2017-10-01",0,"2017-10-02",1,"2017-10-03",8],["2017-11-01",3,"2017-11-01",5,"2017-11-05",10],["2017-12-01",0,"2017-12-07",7,"2017-12-07",12]] df = pd.DataFrame(abc_list,columns=["Time1","A","Time2","B","Time3","C"]) The output: Time1 A Time2 B Time3 C 0 2017-10-01 0 2017-10-02 1 2017-10-03 8 1 2017-11-01 3 2017-11-01 5 2017-11-05 10 2 2017-12-01 0 2017-12-07 7 2017-12-07 12 Then: df_a=df.iloc[:,0:2].rename(columns={'Time1':'time','A':'value'}) df_a['flag']="A" df_b=df.iloc[:,2:4].rename(columns={'Time2':'time','B':'value'}) df_b['flag']="B" df_c=df.iloc[:,4:].rename(columns={'Time3':'time','C':'value'}) df_c['flag']="C" df_final=pd.concat([df_a,df_b,df_c]) df_final.reset_index(drop=True) output: time value flag 0 2017-10-01 0 A 1 2017-11-01 3 A 2 2017-12-01 0 A 3 2017-10-02 1 B 4 2017-11-01 5 B 5 2017-12-07 7 B 6 2017-10-03 8 C 7 2017-11-05 10 C 8 2017-12-07 12 C This is a quit bit not a pythonic way to do it. Here is another way: columns = pd.MultiIndex.from_tuples([('A','Time'),('A','Value'),('B','Time'),('B','Value'),('C','Time'),('C','Value')],names=['Group','Sub_value']) df.columns=columns Output: Group A B C Sub_value Time Value Time Value Time Value 0 2017-10-01 0 2017-10-02 1 2017-10-03 8 1 2017-11-01 3 2017-11-01 5 2017-11-05 10 2 2017-12-01 0 2017-12-07 7 2017-12-07 12 Run: df.stack(level='Group') Output: Sub_value Time Value Group 0 A 2017-10-01 0 B 2017-10-02 1 C 2017-10-03 8 1 A 2017-11-01 3 B 2017-11-01 5 C 2017-11-05 10 2 A 2017-12-01 0 B 2017-12-07 7 C 2017-12-07 12
type: AcceptedAnswer

http://stackoverflow.com/comment/110281079
type: AnswerComment
has text: I used boto to save the file into an Amazon AWS S3 bucket in the cloud instead of trying to actually send the file to the browser. Then, I could simply download it from the link.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48725792

http://stackoverflow.com/a/48530002
score: 1
answers question: http://stackoverflow.com/q/48527614
type: Answer
has body: A one-line hack which works in this case is to add the line serie2.columns= ["_" + col for col in serie2.columns] before you plot the second dataframe. This will replace all column names with an underscore, followed by the original name. Since names starting with underscore ("_") are not shown in the legend, this leaves you only with the legend entries of the first dataframe. This solution requires to have the same order of columns in both dataframes.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84212636
score: 0
has text: To be honest @Piinthesky, the more I think about it, the less it seems plausible that it's an efficiency problem. Something must overflow between 3.10^6 and 4.10^6 . I see no reason for the script to suddenly get stuck while it finishes in a few minutes at 3.10^6. I will give it a go at Code Review. As anyone try to run it here ?
type: QuestionComment
comment on: http://stackoverflow.com/q/48607185
type: Comment

http://stackoverflow.com/a/51146361
answers question: http://stackoverflow.com/q/48575336
has body: Turns out that this was a syncing issue with my network. We use a cloud based network that syncs with our offices, so somehow not all of the files were being synced and getting left in a queue.
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48575336

http://stackoverflow.com/a/48609899
upvote count: 7
answers question: http://stackoverflow.com/q/48609700
score: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/48609700
type: AcceptedAnswer
has body: Summary of three pythonic solutions to instantiating dictionaries. Having a "one-line" solution should never be the most important consideration. 1. Keys and default value defined in advance. Instead of setting a default value for every key, use dict.fromkeys. Also, do not name variables the same as classes, e.g. use lst instead. dic2 = dict.fromkeys(lst, 0) 2. Default value defined in advance, but not keys. Alternatively, if you will be adding more keys in the future, consider using collections.defaultdict, which is a subclass of dict: from collections import defaultdict dic2 = defaultdict(int) dic2['newkey'] # returns 0 even not explicitly set 3. Keys and values related by a function. For building a dictionary where keys and values are linked via a function, use a dictionary comprehension, as described in detail by @OmerB, e.g. {k: f(k) for k in lst} # value function of given keys {f(v): v for v in lst} # key function of given values
downvote count: 0

http://stackoverflow.com/comment/84217863
comment on: http://stackoverflow.com/a/48608143
score: 0
has text: Nah. Return statement just returns the value to where ever you want to store it. Why would it print it on the screen if you didn't tell it to? You can just make a variable `tree_size = bst.size()` and then `print(tree_size)`.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48519054
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48518434
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48518434
type: Answer
has body: Here is the output shapes of each layer in your model (?, 376, 1344, 3) - Input (?, 126, 1344, 3) - Cropping2D (?, 126, 1344, 3) - Lambda (?, 60, 669, 16) - Conv2D 1 (?, 27, 332, 32) - Conv2D 2 (?, 12, 164, 32) - Conv2D 3 (?, 4, 80, 64) - Conv2D 4 By the time the inputs have passed through the 4th Conv2D layer the output shape is already (4,80). You cannot apply another Conv2D layer with filter size (5, 5) since the first dimension of your output is less than the filter size.
score: 4
has comment: http://stackoverflow.com/comment/84037335

http://stackoverflow.com/comment/84264662
type: QuestionComment
type: Comment
has text: If you want matrix-multiplication, you either need to do ```A.dot(B)``` or use the [new operator](https://stackoverflow.com/questions/34142485/difference-between-numpy-dot-and-python-3-5-matrix-multiplication) introduced. This behaves differently if A would be of type np.matrix or a scipy sparse matrix (where A*B is actually matrix-multiplication) [numpy-docs: basic operations](https://docs.scipy.org/doc/numpy-1.12.0/user/quickstart.html#basic-operations).
score: 0
comment on: http://stackoverflow.com/q/48633812

http://stackoverflow.com/comment/84050277
comment on: http://stackoverflow.com/a/48527617
score: 0
type: AnswerComment
has text: I have my output printed, not returned -.- Seems like I will have to run it again overnight.
type: Comment

http://stackoverflow.com/a/53042311
answers question: http://stackoverflow.com/q/48637005
type: Answer
score: 0
has body: If you are using external or Bluetooth microphone, you may need to install extra python package: !pip install pyaudio Then import the package in your code without changing anything, but you can check for the list of supported mics in your pc import pyaudio # check the list of microphones sr.Microphone.list_microphone_names() for a complete tutorial on speech recognition, it worth checking this website: https://realpython.com/python-speech-recognition/

http://stackoverflow.com/a/48598297
has comment: http://stackoverflow.com/comment/84193764
has comment: http://stackoverflow.com/comment/84193366
answers question: http://stackoverflow.com/q/48598276
type: AcceptedAnswer
downvote count: 2
has comment: http://stackoverflow.com/comment/84193958
has comment: http://stackoverflow.com/comment/84193492
has comment: http://stackoverflow.com/comment/84193207
upvote count: 7
has comment: http://stackoverflow.com/comment/84193674
has comment: http://stackoverflow.com/comment/84193180
has comment: http://stackoverflow.com/comment/84193442
score: 5
has comment: http://stackoverflow.com/comment/84193834
has comment: http://stackoverflow.com/comment/84193542
has comment: http://stackoverflow.com/comment/84194143
has comment: http://stackoverflow.com/comment/84194024
has comment: http://stackoverflow.com/comment/84204126
has comment: http://stackoverflow.com/comment/84193987
has comment: http://stackoverflow.com/comment/84193932
type: Answer
accepted answer of: http://stackoverflow.com/q/48598276
has comment: http://stackoverflow.com/comment/84193448
has body: Use zip() and map() functions to apply the sum() on each column: x, y = map(sum, zip(*delta))
has comment: http://stackoverflow.com/comment/84198005
has comment: http://stackoverflow.com/comment/84193326

http://stackoverflow.com/comment/84148285
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48575307
type: Comment
has text: Thank you so much for the feedback, ill try them out!

http://stackoverflow.com/comment/84254731
type: QuestionComment
has text: A bunch of concatenated zlib streams is itself usable as a zlib stream, so you don't need to do anything differently based on whether the stream in question was created this way or not.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48628523

http://stackoverflow.com/comment/84166011
type: Comment
type: AnswerComment
score: 0
has text: As a hack I currently have order always as ascending and I have additional parameter to determine whether the order should be flipped or not. So similar to your first suggestion. I don't like this approach though, because it introduces additional parameter parameter and I can't operate on the order as nice as I would like. As far as I understand GQL would need different model and wouldn't mix with query from NDB, right?
comment on: http://stackoverflow.com/a/48574891

http://stackoverflow.com/comment/83976643
has text: python3.6/site-packages? Is this a venv?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48491537
score: 0

http://stackoverflow.com/a/48532948
accepted answer of: http://stackoverflow.com/q/48532723
has body: I guess the problem lies in reticulate not being able to read customized Python objects, which is common, so you have to pass Python objects as close as native Python types between R and Python interfaces. There's a way to change the output format of ne_chunks to string (bracketed parse format), using Tree.pformat(): &gt;&gt;&gt; from nltk import word_tokenize, pos_tag, ne_chunk &gt;&gt;&gt; sent = "Christopher is having a difficult time parsing NLTK Trees in R." &gt;&gt;&gt; ne_chunk(pos_tag(word_tokenize(sent))) Tree('S', [Tree('GPE', [('Christopher', 'NNP')]), ('is', 'VBZ'), ('having', 'VBG'), ('a', 'DT'), ('difficult', 'JJ'), ('time', 'NN'), ('parsing', 'VBG'), Tree('ORGANIZATION', [('NLTK', 'NNP'), ('Trees', 'NNP')]), ('in', 'IN'), Tree('GPE', [('R', 'NNP')]), ('.', '.')]) &gt;&gt;&gt; ne_chunk(pos_tag(word_tokenize(sent))).pformat() '(S\n (GPE Christopher/NNP)\n is/VBZ\n having/VBG\n a/DT\n difficult/JJ\n time/NN\n parsing/VBG\n (ORGANIZATION NLTK/NNP Trees/NNP)\n in/IN\n (GPE R/NNP)\n ./.)' And to read it back in, use Tree.fromstring(): &gt;&gt;&gt; tree_str = ne_chunk(pos_tag(word_tokenize(sent))).pformat() &gt;&gt;&gt; from nltk import Tree &gt;&gt;&gt; Tree.fromstring(tree_str) Tree('S', [Tree('GPE', ['Christopher/NNP']), 'is/VBZ', 'having/VBG', 'a/DT', 'difficult/JJ', 'time/NN', 'parsing/VBG', Tree('ORGANIZATION', ['NLTK/NNP', 'Trees/NNP']), 'in/IN', Tree('GPE', ['R/NNP']), './.']) So I would guess doing this in R might work: text &lt;- "Christopher is having a difficult time parsing NLTK Trees in R." ne_tagged_tokens &lt;- ne_chunk(pos_tag(word_tokenize(tagged_tokens)))$pformat() print(ne_tagged_tokens) But reading the strings back into R objects shouldn't be possible since it couldn't handle non-native Python Tree objects so the some_func &lt;- function(...{nltk$some_func(...)}) won't work with Tree since it's not a function. If you want to manipulate the output of ne_chunk Tree objects into a list of named entities, then you would have to do something …
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48532723
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84062442
type: Answer
upvote count: 2

http://stackoverflow.com/a/48642267
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48641437
has body: I think what you can look into is this django project which has scrapy embedded in it. You will have to figure out the part of deploying this to heroku. https://github.com/bipul21/scrapy_django http://bipuljain.com/blog/using-scrapy-with-django-14
accepted answer of: http://stackoverflow.com/q/48641437
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48626328
answer count: 1
downvote count: 0
upvote count: 1
has title: Adding an image to the ylabel in pyplot
tagged with: plot
favorite count: 0
type: Question
has body: I would like to set an image as the ylabel for a plot I've made. The following code import numpy as np import matplotlib.pyplot as plt from matplotlib.cbook import get_sample_data from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage, AnnotationBbox) fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3,4,5,6,7],[1,4,2,8,5,7,1]) arr = np.arange(100).reshape((10, 10)) im = OffsetImage(arr, zoom=2) im.image.axes = ax xy = (1, 5) ab = AnnotationBbox(im, xy) ax.add_artist(ab) plt.show() generates the following figure: I would like that picture to be to the left of the yaxis ticks, rather than on the plot. I've tried changing the line xy = (1, 5), but that just makes the image disappear. I've also tried writing ax.set_ylabel(ab) and ax.set_ylabel(im), though (predictably) these just put the name of the object as the y-axis label.
tagged with: matplotlib
tagged with: python
tagged with: label
tagged with: image
accepted answer: http://stackoverflow.com/a/48626560
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48626560
score: 1

http://stackoverflow.com/q/48630570
has answer: http://stackoverflow.com/a/48630748
has comment: http://stackoverflow.com/comment/84258175
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/48630658
has answer: http://stackoverflow.com/a/48638889
has answer: http://stackoverflow.com/a/48630713
downvote count: 2
has answer: http://stackoverflow.com/a/48630658
favorite count: 0
possible better answer: http://stackoverflow.com/a/48630748
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84258296
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84258305
has title: How to remove duplicated keys in reverse order from dictionary (python)
answer count: 4
has body: I am struggling to remove same keys from a dictionary in the case below: {('cat', 'tiger'): 18, ('tiger', 'cat'): 18, ('chines', 'gentleman'): 7, ('gentleman', 'chines'): 7} In this case, I consider reverse order ('cat', 'tiger'): 18 and ('tiger', 'cat'): 18 as same keys and try to make a new dictionary like below {('cat', 'tiger'): 18, ('gentleman', 'chines'): 7} What I am trying is adapt any reverse order case, when I have a similar dictionary like {(('cage', 'cat'), 5),(('cat', 'cage'), 5)} to be merged or removed, either one.
score: 0

http://stackoverflow.com/q/48596724
upvote count: 2
accepted answer: http://stackoverflow.com/a/48597015
has answer: http://stackoverflow.com/a/48601737
tagged with: arrays
score: -3
has title: Python - Count consecutive values without sort
has answer: http://stackoverflow.com/a/48597015
downvote count: 5
tagged with: python
answer count: 6
has body: I am trying to build 2 different functions in Python. strip consecutive values: desired outcome: exampleArrray = [0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0] strippedArray = [0,1,2,1,2,1,2,1,2,1,0] What I have tried so far: def stripArray(array): lengthArray = len(array) for i in range (1,lengthArray): print(i) print(lengthArray) if (i&lt;lengthArray): if(array[i-1] == array[i]): print("has been delted " + str(array[i])) del(array[i]) i = i -1 lengthArray = lengthArray -1 print(array) stripArray([0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0]) Outputs: [0, 0, 1, 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 2, 1, 1, 0], I could loop again but I think there is a better approach somewhere? count consecutive values and join Pseudo: 4x0, 6x1, 3x2, 2x1, 1x2, 1x1, 1x2, 2x1, 6x2, 4x1, 2x0 exampleArrray = [0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0] countArray = [40,61,32,21,12,11,12,21,62,41,20] I think I'll need the stripArray for this? Edit: countArray[0] = OccurencesAfterAnother*10 + stripArray[0] SOLVED: We have 3 perfect funtioning answers! Thank you all! Your Answers couldnt be more different and i really like them all! Edit: Thank you all for contributing to the accepted answer! Also future viewers, there are different solutions to this, not all of them need imports and others are using numpy approach. Thanks to all contributors!
has answer: http://stackoverflow.com/a/48596946
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48596953
possible better answer: http://stackoverflow.com/a/48596822
has answer: http://stackoverflow.com/a/48596949
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48596822

http://stackoverflow.com/comment/84282272
type: QuestionComment
has text: Please update the question with your full code.
score: 0
comment on: http://stackoverflow.com/q/48642747
type: Comment

http://stackoverflow.com/a/48504790
has comment: http://stackoverflow.com/comment/93663018
has comment: http://stackoverflow.com/comment/93662771
has comment: http://stackoverflow.com/comment/93662666
score: 2
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/93647838
has comment: http://stackoverflow.com/comment/93663363
downvote count: 0
has comment: http://stackoverflow.com/comment/93662257
answers question: http://stackoverflow.com/q/48503130
has comment: http://stackoverflow.com/comment/93663273
has body: It's possible with data_files but not recommended. Think about a package installed into a separate environment created with virtualenv — users will be surprised if such a package installs files outside that separate environment. Hence advice: distinguish pip-installable package that must be self-contained and must not install anything beyond python code and files required for the code (could be installed with package_data) from full-blown installable package created with installer builders like RPM or DEB.
has comment: http://stackoverflow.com/comment/93663062
accepted answer of: http://stackoverflow.com/q/48503130
type: Answer

http://stackoverflow.com/comment/84213424
score: 0
type: Comment
has text: Yeah I'm using WHM Cpanel, and I also read this original answer, but it wasn't clear enough, thanks anyway
type: AnswerComment
comment on: http://stackoverflow.com/a/48607496

http://stackoverflow.com/a/48750857
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48564598
upvote count: 4
has body: I am posting this fix to my problem, in case somebody needs it. I replaces the read_csv line with the following and the problem was solved: dataset = pd.read_csv(io.BytesIO(response['Body'].read()), encoding='utf8')
answers question: http://stackoverflow.com/q/48564598
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83973619
comment on: http://stackoverflow.com/a/48490200
score: 0
type: AnswerComment
has text: I'm just curious about this :)
type: Comment

http://stackoverflow.com/q/48581116
type: Question
accepted answer: http://stackoverflow.com/a/48581213
has answer: http://stackoverflow.com/a/48581213
tagged with: python
has title: Removing specific rows in an input .txt file (python)
type: AnsweredQuestion
score: 0
has body: I want to do some manipulations on an input .txt file from this: A 0.4 B 0.1 C 0.3 _ 0.2 _ 0.7 D 0.9 into this: A 0.4 B 0.1 C 0.3 D 0.9 In other words, get rid of the rows with the underscore symbol. What first comes to my mind is making a dictionary and then deleting the "_" values. But the problem with the dictionary is that it messes the order of the elements. How can I approach this in a better way?
tagged with: io
answer count: 1

http://stackoverflow.com/comment/84037697
type: AnswerComment
comment on: http://stackoverflow.com/a/48515860
has text: Override get_context_data of your View class [documentation](https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-display/#listview).
score: 0
type: Comment

http://stackoverflow.com/comment/84440458
has text: Yes and no, my full query is a single page, I wanted to query for a specific cursor (which would correspond to a single page), a parameter would need to tell me whether to read it backwards or forwards (cursor can be either the end or the beginning of the page).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48574891

http://stackoverflow.com/a/48507789
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/48507546
has comment: http://stackoverflow.com/comment/84020572
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48507546
has body: I think you need to correct this: model.add(layers.Dense(32, activation='relu', input_shape=(10,))) 10 is your number of features used. Keras will automatically take the number of rows in the batch/dataset. Edit Explanation: from keras import models from keras import layers model = models.Sequential() model.add(layers.Dense(32, input_shape=(10,))) model.add(layers.Dense(1)) Here, The first layers is created that will only accept a 2D tensor with the dimension is 10 (the zero-th dimension, the batch dimension, is unspecified and thus any value would be accepted). Thus this layer can only be connected to an upstream that expects 32-dimensional vectors as its input. When using Keras you don’t have to worry about compatibility, because the layers that you add to your models are dynamically built to match the shape of the incoming layer. The second layer did not receive an input shape argument—instead it automatically inferred its input shape as being the output shape of the layer that came before. Decoding parameter values in the model: Suppose this is my model: from keras import models from keras import layers model = models.Sequential() model.add(layers.Dense(32, input_shape=(2,))) model.add(layers.Dense(1)) model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) print model.summary() And this is the model summary: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_1 (Dense) (None, 32) 96 _________________________________________________________________ dense_2 (Dense) (None, 1) 33 ================================================================= Total params: 129 Trainable params: 129 Non-trainable params: 0 _________________________________________________________________ For Dense Layer, we need to calculate this: output = dot(W, input) + b or output = relu(dot(W, input) + b) #relu here is the activation function I…
has comment: http://stackoverflow.com/comment/84044169
has comment: http://stackoverflow.com/comment/84018709
downvote count: 0

http://stackoverflow.com/comment/84213215
has text: I added a solution without using `regex`. Please find it.
comment on: http://stackoverflow.com/q/48607966
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84195422
type: QuestionComment
comment on: http://stackoverflow.com/q/48599299
has text: @Norrius fair enough, added another dupe target. Martijn's answer modifies the list in place
score: 1
type: Comment

http://stackoverflow.com/comment/84034190
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48519661
has text: For person who voted to close as typo: This is not off topic typo because it is valid python, just not valid json

http://stackoverflow.com/a/48692192
type: Answer
has body: Please make sure all the parameters are set properly and make sure you have all your dependencies uploaded and packaged properly. If everything is done and you still can't run the job, you will need more than just "Internal Error" to pinpoint the issue. Please either contact Google Cloud Platform support or file a bug on the Public Issue Tracker to get further assistance.
answers question: http://stackoverflow.com/q/48511058
score: 0

http://stackoverflow.com/q/48495799
has comment: http://stackoverflow.com/comment/84082109
type: Question
has comment: http://stackoverflow.com/comment/84000598
duplicate of: http://stackoverflow.com/q/2484527
tagged with: matplotlib
tagged with: python
has body: In matplotlib, what is the best way to plot a family of curves which is a solution to a differential equation. How can I plot for example, and to overlay family of orthogonal trajectories over this family of curves Finally I want to be able to produce a figure similar to the following I am aware of contour plots of implicit functions, but how are they related to the constant C in the above equations. I could produce following figure based on the suggestion, But I can't to seem to have the contour labels on the overlaid parabolas. CODE: import matplotlib.pyplot as plt from numpy import arange, meshgrid delta = 0.025 x_range = arange(-20.0, 20.0, delta) y_range = arange(-20.0, 20.0, delta) X, Y = meshgrid(x_range,y_range) fig=plt.figure() ax=fig.add_subplot(111) ax.set_xlim(xmin=-6, xmax=6) ax.set_ylim(ymin=-4, ymax=4) ax.axhline(y=0, color='k',linewidth=1) ax.axvline(x=0, color='k',linewidth=1) # F is one side of the equation, G is the other F = (X**2)/2.0+(Y**2) colrs_tuple=('k','c','c','k') #C = range(6,14,3) C = (2,6,9,12) #print(type(C)) CS = plt.contour(X, Y, F, C, colors=colrs_tuple) labels = plt.clabel(CS) xy = [t.get_position() for t in labels] print(xy) F=Y G=X**2 C = (-5,-3,-1,1,3,5) ##for c1 in C: ## CS=plt.contour(X, Y, F/G- c1,[0], colors='c',linestyles='dashed') ## labels = plt.clabel(CS) ## xy = [t.get_position() for t in labels] ## print(xy) ##plt.show() CS1=plt.contour(X, Y, F/G,levels=(-15,-3,-1,-0.5,0.5,1,3,15), colors='c',linestyles='dashed') labels1 = plt.clabel(CS1) plt.show()
has comment: http://stackoverflow.com/comment/84064802
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84061206
linked to: http://stackoverflow.com/q/2484527
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84022696
has comment: http://stackoverflow.com/comment/84028637
has title: family of curves in matplotlib with constant

http://stackoverflow.com/a/48567553
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84200801
upvote count: 2
has body: The error says it all : selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. Which implies that GeckoDriver binary is not in the Classpath While working with Selenium v3.x you have to download the latest GeckoDriver from this url and store it in your system and mention the absolute path while initiating the webdriver and Web Browser session as follows : from selenium import webdriver driver = webdriver.Firefox(executable_path="C:\\path\\to\\geckodriver.exe") driver.get("https://auth.edgenuity.com/Login/Login/Student") button = driver.find_element_by_id('LoginSubmit') button.click()
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48551161
answers question: http://stackoverflow.com/q/48551161

http://stackoverflow.com/comment/84177664
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48572194
type: Comment
has text: which one it can be? I think the problem is not on the VB code cause even if I run the script outside vb it doesn't show the path. It just takes the picture. can you tell me how to put a picture in the comment so i can show you what i mean?

http://stackoverflow.com/comment/84260260
type: AnswerComment
comment on: http://stackoverflow.com/a/48631541
has text: I have a confused question, however... why would it dump the entire contents of the json file I'm requesting? What is the point of jsonpath at all, if it has no parsing functionality?
type: Comment
score: 0

http://stackoverflow.com/q/48529713
has answer: http://stackoverflow.com/a/48529770
has body: I am having some sort of issue with list aliasing or variable assignment in Python 2.7. I will show you a minimal example. There are two different results with and without the assertion, and I don't know why/how the assertion affects this. Somehow it is overwriting an attribute when I append something to the object_list shown below: class Object1(object): def __init__(self): self.object_list = [] def add_thing(self, thing): # this next line makes all the difference assert thing.name not in [thing.name for thing in self.object_list], 'agent id already exists, use another one' self.object_list.append(thing) class Thing(object): def __init__(self, name): self.name = name def __repr__(self): return self.name Here is a minimal example: With the assertion mfd = Object1() myAgent = Thing('blah') myAgent_2 = Thing('blew') mfd.add_thing(myAgent) mfd.add_thing(myAgent_2) print mfd.object_list &gt;&gt; [blah, blah] Without the assertion mfd = Object1() myAgent = Thing('blah') myAgent_2 = Thing('blew') mfd.add_thing(myAgent) mfd.add_thing(myAgent_2) print mfd.object_list &gt;&gt; [blah, blew] Can someone please explain to me how the assertion above is affecting this? Thank you.
tagged with: python-2.7
score: 0
tagged with: list
tagged with: assert
has comment: http://stackoverflow.com/comment/84055049
upvote count: 1
tagged with: assertions
has comment: http://stackoverflow.com/comment/84054862
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84055009
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84054984
type: UnansweredQuestion
has title: How does assertion affect variable assignment in Python?
has comment: http://stackoverflow.com/comment/84054805
tagged with: python

http://stackoverflow.com/a/48516460
has body: You can use numpy.dtype.names. Here is an example. # inputs In [196]: A Out[196]: array([[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]) In [197]: B Out[197]: array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]) # their dtype In [198]: A.dtype, B.dtype Out[198]: (dtype('int64'), dtype('int64')) # their size In [199]: A.size, B.size Out[199]: (16, 16) # store it as a list of tuples In [200]: dt = np.dtype([('A', A.dtype, A.size), ('B', B.dtype, B.size)]) # get all arrays In [201]: dt.names Out[201]: ('A', 'B') In [202]: dt['A'] Out[202]: dtype(('&lt;i8', (16,))) You can also skip the variable.size since it'll be inferred. In [233]: dt = np.dtype([('A', A.dtype), ('B', B.dtype)]) # size inferred automatically In [234]: dt.itemsize Out[234]: 16 In [235]: dt.names Out[235]: ('A', 'B')
upvote count: 1
has comment: http://stackoverflow.com/comment/84028059
has comment: http://stackoverflow.com/comment/84027717
has comment: http://stackoverflow.com/comment/84027448
score: 1
answers question: http://stackoverflow.com/q/48516016
type: Answer
downvote count: 0

http://stackoverflow.com/q/48503593
has answer: http://stackoverflow.com/a/48503627
has title: What is the -t flag for pip?
downvote count: 5
possible better answer: http://stackoverflow.com/a/53537810
tagged with: python
has body: I was advised to use pip install module-name -t /path/to/project-dir. What does the -t flag mean in this command?
upvote count: 18
accepted answer: http://stackoverflow.com/a/48503627
type: AnsweredQuestion
answer count: 2
tagged with: pip
score: 13
has answer: http://stackoverflow.com/a/53537810
has comment: http://stackoverflow.com/comment/133083210
favorite count: 0
type: Question

http://stackoverflow.com/comment/84276051
score: 0
comment on: http://stackoverflow.com/q/48639783
has text: Do the players and the team have the same fields (keys) though? I suggest you post an [MCVE](https://stackoverflow.com/help/mcve) or at least some code
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48552474
linked to: http://stackoverflow.com/q/815110
tagged with: auth0
tagged with: unit-testing
favorite count: 0
type: Question
has title: Auth0 obtain access_token for unit tests in Python
linked to: http://stackoverflow.com/q/41626602
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/48552579
has body: I'm trying to run unit tests in Python for my flask application for routes that depend on the userID which is obtained from the access_token. Is there a way to call the auth0 authorize API, in Python, to obtain an access_token for a user given their username and password? If not, then what is an automated way of calling the authorize API to give it a username and password and obtain an access_token? A code snippet would be best.
score: 1
has answer: http://stackoverflow.com/a/48554119

http://stackoverflow.com/comment/84237590
type: QuestionComment
has text: it works! thank you @goodvibration t.m.adam
comment on: http://stackoverflow.com/q/48620110
score: 0
type: Comment

http://stackoverflow.com/comment/84276865
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48640167
has text: It would be easier to answer if you would shown a piece of code that demonstrates the problem.
score: 0

http://stackoverflow.com/a/48541011
type: Answer
has body: You can use the zfill function which left-pads with leading zeros and takes as an argument the witdh of the desired output. If s is your series, you can do: s.apply(lambda x : x.zfill(10))
answers question: http://stackoverflow.com/q/48540781
score: 0

http://stackoverflow.com/q/48549513
tagged with: python
tagged with: client
type: AnsweredQuestion
has body: I'm trying to build a chatbot with zmq in Python. I already connected different clients to the server, when a client sends a message, it gets printed on his terminal, and on the terminal of the server, but not on the terminals of the other clients. I only found ways to respond to the current clients, but not to everyone at the same time. All of my chatclients look like this, with different names: import zmq context = zmq.Context() # Socket to talk to server print("Connecting to chatbot...") socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5555") name = "Max" while True: message = input("Message: ") socket.send_pyobj({1:[name, message]}) # Get the reply. message2 = socket.recv_pyobj() print("%s: %s" % (message2.get(1)[0], message2.get(1)[1])) And my server looks like this: import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5555") while True: # Wait for next request from client message = socket.recv_pyobj() print("%s: %s" % (message.get(1)[0], message.get(1)[1])) time.sleep(1) # Send reply back to client socket.send_pyobj({1:[message.get(1)[0], message.get(1)[1]]}) Does someone know a way, that every client sees the messages of every other client as well?
score: 0
tagged with: pyzmq
has title: zmq / How to send response to different clients?
answer count: 1
type: Question
tagged with: server
has answer: http://stackoverflow.com/a/48561873
tagged with: zeromq
accepted answer: http://stackoverflow.com/a/48561873

http://stackoverflow.com/a/48626153
has body: All problem is indentation of quoted string Here is solution, def test_code(): print "test_code" def run(): try: a= ''' def test2(): print "test2" test_code() test2()''' exec(a) except Exception as e: print e run() Output test2 test_code
answers question: http://stackoverflow.com/q/48625747
score: 0
type: Answer

tkinter
tags question: http://stackoverflow.com/q/48493533
tags question: http://stackoverflow.com/q/48600439
tags question: http://stackoverflow.com/q/48510055
tags question: http://stackoverflow.com/q/48496155
tags question: http://stackoverflow.com/q/48542355
tags question: http://stackoverflow.com/q/48599690
tags question: http://stackoverflow.com/q/48494877
tags question: http://stackoverflow.com/q/48566886
tags question: http://stackoverflow.com/q/48488902
tags question: http://stackoverflow.com/q/48611337
tags question: http://stackoverflow.com/q/48602394
tags question: http://stackoverflow.com/q/48563302
tags question: http://stackoverflow.com/q/48530320
tags question: http://stackoverflow.com/q/48551668
tags question: http://stackoverflow.com/q/48594765
tags question: http://stackoverflow.com/q/48568543
tags question: http://stackoverflow.com/q/48538716
tags question: http://stackoverflow.com/q/48505575
tags question: http://stackoverflow.com/q/48519641
tags question: http://stackoverflow.com/q/48532788
tags question: http://stackoverflow.com/q/48588516
tags question: http://stackoverflow.com/q/48494695
tags question: http://stackoverflow.com/q/48586539
tags question: http://stackoverflow.com/q/48610439
tags question: http://stackoverflow.com/q/48551702
tags question: http://stackoverflow.com/q/48603066
tags question: http://stackoverflow.com/q/48492830
tags question: http://stackoverflow.com/q/48504746
tags question: http://stackoverflow.com/q/48501703
tags question: http://stackoverflow.com/q/48600463
tags question: http://stackoverflow.com/q/48630193
tags question: http://stackoverflow.com/q/48489171
tags question: http://stackoverflow.com/q/48537039
tags question: http://stackoverflow.com/q/48536667
tags question: http://stackoverflow.com/q/48501966
tags question: http://stackoverflow.com/q/48593051
tag name: tkinter
tags question: http://stackoverflow.com/q/48535643
tags question: http://stackoverflow.com/q/48532060
tags question: http://stackoverflow.com/q/48531668
tags question: http://stackoverflow.com/q/48554151
tags question: http://stackoverflow.com/q/48492727
tags question: http://stackoverflow.com/q/48503094
tags question: http://stackoverflow.com/q/48568701
tags question: http://stackoverflow.com/q/48508702
tags question: http://stackoverflow.com/q/48596482
tags question: http://stackoverflow.com/q/48547480
tags question: http://stackoverflow.com/q/48576091
tags question: http://stackoverflow.com/q/48497073
tags question: http://stackoverflow.com/q/48505483
tags question: http://stackoverflow.com/q/48561429
tags question: http://stackoverflow.com/q/48586338
tags question: http://stackoverflow.com/q/48510369
tags question: http://stackoverflow.com/q/48517660
tags question: http://stackoverflow.com/q/48637047
tags question: http://stackoverflow.com/q/48619011
tags question: http://stackoverflow.com/q/48530689
tags question: http://stackoverflow.com/q/48618651
tags question: http://stackoverflow.com/q/48550578
tags question: http://stackoverflow.com/q/48516751
tags question: http://stackoverflow.com/q/48618665
tags question: http://stackoverflow.com/q/48554463
tags question: http://stackoverflow.com/q/48493137
tags question: http://stackoverflow.com/q/48607787
tags question: http://stackoverflow.com/q/48537606
tags question: http://stackoverflow.com/q/48544583
tags question: http://stackoverflow.com/q/48526531
tags question: http://stackoverflow.com/q/48492273
tags question: http://stackoverflow.com/q/48633394
tags question: http://stackoverflow.com/q/48590091
tags question: http://stackoverflow.com/q/48488496
tags question: http://stackoverflow.com/q/48598382
tags question: http://stackoverflow.com/q/48548356
tags question: http://stackoverflow.com/q/48597830
tags question: http://stackoverflow.com/q/48534692
type: Tag
tags question: http://stackoverflow.com/q/48625019
tags question: http://stackoverflow.com/q/48614375
tags question: http://stackoverflow.com/q/48503344
tags question: http://stackoverflow.com/q/48526888

http://stackoverflow.com/comment/84221968
has text: @progmatico My template does not have form tags. I'm using `form=LPRForm()` and the browser is submitting the user data back to the server. What's the purpose of `request.POST`?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48600444
type: QuestionComment

unix
tags question: http://stackoverflow.com/q/48604646
tags question: http://stackoverflow.com/q/48572629
tags question: http://stackoverflow.com/q/48566080
tags question: http://stackoverflow.com/q/48501832
tags question: http://stackoverflow.com/q/48530306
type: Tag
tag name: unix
tags question: http://stackoverflow.com/q/48554497

http://stackoverflow.com/a/48609744
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48609632
has body: Before adding i += 1 to i += 2 and not understanding what it means just think what you are trying to do. You want to get values from the array right? i.e. players[0][1] will get you 202 players[1][1] will get you 193 players[2][1] will get you 205 .... So increment i accordingly. Sometimes the easiest way to write code is to first say out loud in your head or write it in simple english. You want to loop over values of the array You want to then check if the value matches something If it does print it If it doesn't don't print it and then move on to the next value Keep doing it till you have checked every value in the array Now writing code makes sense right? The easiest way to understand increment is to write it like this i = i + 1

http://stackoverflow.com/a/48539445
has body: is this what you mean: listOfLists = [2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13] body = ("here are the informations") for a in listOfLists: print(body + str(a)) output looks like: here are the informations[2, 3, 4, 5, 6, 7] here are the informations[8, 9, 10, 11, 12, 13]
has comment: http://stackoverflow.com/comment/84073996
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48539140

http://stackoverflow.com/q/48597662
has comment: http://stackoverflow.com/comment/84191911
answer count: 1
has title: Why won't my Python function execute?
has body: I'm quite new to coding. I've wrote a simple piece of code which will take a URL as an input, load the URL and put the status code for that URL in a variable. I have put this in a function. But when I run the code I get no errors and yet the function won't run. It seems like the interpreter is just flying past my function. I know I have some simple error but no matter how much I search I can't fix it. Please help me understand. Oh, and the code is incomplete. But the function should run. import urllib.request, click, threading url = input("Enter domain name &gt;&gt; \n") def get_stat(): status = urllib.request.urlopen("http://"+url).getcode() if status == 200: return "Site loads normally!\nHost Said: '%s'!" %(str(status)) else: return "Site Needs To Be Checked!\nHost Said: '%s'!" %(str(status)) get_stat() if click.confirm("Would you like to set a uptime watch?"): click.echo("You just confirmed something!!") count = input("Enter the number of times you wish your site to be checked: ") interval = input("Enter the time interval for status requests (Time is in minutes): ")
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84191888
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84192065
linked to: http://stackoverflow.com/q/7129285
favorite count: 0
has answer: http://stackoverflow.com/a/48597736
accepted answer: http://stackoverflow.com/a/48597736
type: Question
upvote count: 2
tagged with: function
tagged with: python

http://stackoverflow.com/comment/131811357
type: Comment
type: QuestionComment
has text: @kyriakosSt It was true when I wrote that comment, and also I think you are confusing things, averating for many distributed algorithms is gradient averaging, not weight averaging (A3C for example), while ensembles or dropout do not average weights, they average activations, there is a huge difference there.
comment on: http://stackoverflow.com/q/48560227
score: 0

http://stackoverflow.com/comment/84055662
has text: I can use numpy, I have it imported but unused presently, if I declare `x[]` via numpy would that solve the issue? I've only got a vague understanding of lists.. i got the same error with `x[0]` the 1 was just a test.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48530092
type: Comment

http://stackoverflow.com/comment/84147799
has text: The real question is: is numpy the right tool and are you aware of the consequences? Do you know the algorithmic complexity of changing numpy-array sizes (resizing is very costly)? In numpy world that's probably a case for concatenate, stack (hstack in this case; i think it will get deprecated someday) and all those. But think about my first sentences as well.
score: 3
type: Comment
comment on: http://stackoverflow.com/q/48575601
type: QuestionComment

http://stackoverflow.com/comment/84208927
has text: I'd vote this up if it didn't digress into Ansible, etc. There are lots of ways to manage deployments. Your preference is unrelated to the question.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48560212

http://stackoverflow.com/a/48502866
upvote count: 13
has body: nonzero will return the indices of an array that is not 0. idx_nonzero = B.nonzero() A[idx_nonzero] = B[idx_nonzero] nonzero is also what numpy.where returns when only a condition is passed in. Thus, equivalently, we can do idx_nonzero = np.where(B != 0) # (B != 0).nonzero() A[idx_nonzero] = B[idx_nonzero] This solution is in-place. If you need to create a new array, see @jp_data_analysis' answer.
answers question: http://stackoverflow.com/q/48501432
downvote count: 0
score: 13
type: Answer

http://stackoverflow.com/q/48519633
type: AnsweredQuestion
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48519776
tagged with: postgresql
accepted answer: http://stackoverflow.com/a/48519756
type: Question
has answer: http://stackoverflow.com/a/48519756
has title: SQLAlchemy cast boolean column to int
tagged with: python
score: 18
upvote count: 18
tagged with: sqlalchemy
has body: I have a table of user records and I wish to see the average when some condition is met. the condition column is a boolean. In Postgresql I could cast it easily: select id, avg(cond::INT) from table group by id; But in SQLAlchemy I couldn't find anything equivalent to ::INT. How do i deal with the type conversion? I have orm_query(Table.id, func.avg(Table.cond)) which, of course, returns an error.
has comment: http://stackoverflow.com/comment/84034075
has answer: http://stackoverflow.com/a/48519776

http://stackoverflow.com/q/48579924
type: Question
has comment: http://stackoverflow.com/comment/84156109
tagged with: python
has title: How to improve performance while iterating through a pandas data frame?
tagged with: pandas
type: AnsweredQuestion
has body: I have two pandas data frames. The first one contains a list of unigrams extracted from the text, count and probability of the unigram occurring in the text. The structure looks like this: unigram_df word count prob 0 we 109 0.003615 1 investigated 20 0.000663 2 the 1125 0.037315 3 potential 36 0.001194 4 of 1122 0.037215 The second one contains a list of skipgrams extracted from the same text, along with the count and probability of the skipgram occurring in the text. It looks like this: skipgram_df word count prob 0 (we, investigated) 5 0.000055 1 (we, the) 31 0.000343 2 (we, potential) 2 0.000022 3 (investigated, the) 11 0.000122 4 (investigated, potential) 3 0.000033 Now, I want to calculate the pointwise mutual information for each skipgram, which is basically a log of skipgram probability divided by the product of its unigrams' probabilities. I wrote a function for that, which iterates through the skipgram df and and it works exactly how I want, but I have huge issues with performance, and I wanted to ask if there is a way to improve my code to make it calculate the pmi faster. Here's my code: def calculate_pmi(row): skipgram_prob = float(row[3]) x_unigram_prob = float(unigram_df.loc[unigram_df['word'] == row[1][0]] ['prob']) y_unigram_prob = float(unigram_df.loc[unigram_df['word'] == row[1][1]] ['prob']) pmi = math.log10(float(skipgram_prob / (x_unigram_prob * y_unigram_prob))) result = str(str(row[1][0]) + ' ' + str(row[1][1]) + ' ' + str(pmi)) return result pmi_list = list(map(calculate_pmi, skipgram_df.itertuples())) Performance of the function for now is around 483.18it/s, which is super slow, as I have hundreds of thousands of skipgrams to iterate through. Any suggestions would be welcome. Thanks.
downvote count: 0
accepted answer: http://stackoverflow.com/a/48580221
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/48580221
favorite count: 0
tagged with: performance

http://stackoverflow.com/a/48584975
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/84166712
downvote count: 1
has comment: http://stackoverflow.com/comment/84166760
has body: while True simply means that the while loop will repeat forever until something breaks it. Because True will always be true it will keep going. I don't understand where this is supposed to break though so that is just your call! EDIT: Something that other people have pointed out is if you actually want to escape the loop without a break call then simply set the condition of the while loop to be while bear_moved == false. That way when the bear moves and sets bear_movedto True then the while loop will stop running.
has comment: http://stackoverflow.com/comment/84166810
type: Answer
answers question: http://stackoverflow.com/q/48584911
has comment: http://stackoverflow.com/comment/84166866

http://stackoverflow.com/comment/84122122
type: Comment
type: QuestionComment
score: 0
has text: You have to the version adapted for `pypy`, if any. Too much of the regular `numpy` is compiled `c` to work with pypy.
comment on: http://stackoverflow.com/q/48562947

http://stackoverflow.com/comment/84026570
has text: Are you suggesting variable reassignment? I really want to achieve "assign the value to the value that the variable holds"
score: 0
comment on: http://stackoverflow.com/a/48515962
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84194914
score: 0
type: QuestionComment
type: Comment
has text: Sorry about that, first time asking a question. Fixed the code, all you need to know about the output is that when i enter quit it just constantly keeps looping with no message and just blank output.
comment on: http://stackoverflow.com/q/48599100

http://stackoverflow.com/a/48547543
has comment: http://stackoverflow.com/comment/84092611
has comment: http://stackoverflow.com/comment/84092345
type: Answer
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48547172
has body: You're rechecking too many times - you were on the way, but I suggest first collecting, then checking: users = set() with open("users.txt") as openfile: for line in openfile: users.update(line.split()) #Another way: #for user in line.split(): #users.add(user) first = True while first or (username in users): if not first: print("Try again, exists!") username=input("Enter a username:") first = False
upvote count: 1

http://stackoverflow.com/a/48641725
upvote count: 4
score: 4
downvote count: 0
has body: You override the init method. So you should return it to your superclass. def __init__(self, *args, **kwargs): self.site_type = kwargs.pop("site_type") # get site type if set and filter against it if self.site_type: subnet_type_data = SiteTypes.objects.filter(site_type=self.site_type) super(AutoSubnetForm, self).__init__(*args, **kwargs) You do not return your _errors. So it does not know about any other data except the ones you provide while overriding. If you want all you should return it to superclass. That should cause it. The code above should fix it.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48641121
accepted answer of: http://stackoverflow.com/q/48641121
type: Answer

http://stackoverflow.com/comment/84020327
type: Comment
has text: "AA" and "BB" are user inputs. I was trying to ask if there is some user input value "BB" that can reduce the code to just browser.find_elements_by_css_selector("AA"). Eg. url = http://store.steampowered.com/search/?filter=topsellers "AA" = span.title, "BB" = someinputvalue . As someinput value is not found, the code will still run as browser.find_elements_by_css_selector("span.title").
type: QuestionComment
comment on: http://stackoverflow.com/q/48512472
score: 0

http://stackoverflow.com/q/48634086
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84265298
has body: I am trying to pass a string though an MySQL query in Python like so - cur.execute("""SELECT * FROM abcDB.zyzTable WHERE ordId IN %s """ %(orderString1)) and orderString1 looks like (534,523,544) the string has the brackets I get the following error. ValueError: unsupported format character 'T' (0x54) at index 2195 How do I fix this?
has title: ValueError: unsupported format character 'T' (0x54)
score: 0
has comment: http://stackoverflow.com/comment/84265422
answer count: 1
tagged with: python
tagged with: mysql
linked to: http://stackoverflow.com/q/7929364
tagged with: valueerror
has answer: http://stackoverflow.com/a/48634599

http://stackoverflow.com/comment/84001066
type: QuestionComment
type: Comment
has text: I just realized, that you are trying to match objects in the first place. This is even more hard to image-similarity-search and your first approach of just using this approach will also fail (on mostly all scenarios; e.g. relative-positioning different; shadows...). But ok... some things are hard and there is a reason there is academics (PCA was academics-only at some time in the past too).
score: 0
comment on: http://stackoverflow.com/q/48502667

http://stackoverflow.com/q/48573717
answer count: 1
has comment: http://stackoverflow.com/comment/84167985
has title: QColorDialog and QItemDelegate
has body: I have a QTableView and I'm Using a QItemDelegate in it as button. I'm trying to change the color of the button, so when i click on it i call a QColorDialog. But then I'm having trouble sending the color it back to the button. Here's how it is going so far: the Button and QColorDialog: class ButtonDelegate(QItemDelegate): def __init__(self, parent): QItemDelegate.__init__(self, parent) def paint(self, painter, option, index): widget = QWidget() layout = QHBoxLayout() widget.setLayout(layout) btn = QPushButton('') btn.setStyleSheet("background-color:rgb(86,12,65)") ix = QPersistentModelIndex(index) btn.clicked.connect(lambda ix = ix : self.onClicked(ix)) layout.addWidget(btn) layout.setContentsMargins(2,2,2,2) if not self.parent().indexWidget(index): self.parent().setIndexWidget(index, widget) def onClicked(self, ix): colorPicker = QColorDialog.getColor() #colorPicker.show() r = str(colorPicker.red()) g = str(colorPicker.red()) b = str(colorPicker.red()) bgcolor = 'background-color:rgb(' + r + ',' + g + ',' + b +')' What's the next step? I tried declaring the button in the delegate init as self.btn = QPushButton() and then reuse it at the onCLick Method, but the button don't even get drawn that way. Some enlightenment? Thank you! edit 1 Model: class Model(QAbstractTableModel): def __init__(self, vtxTable, parent = None): QAbstractTableModel.__init__(self, parent) #data self.groups = [] #header self.header_labels = ['Color', 'Group', 'Done'] self.vtxTable = vtxTable def rowCount(self, parent): return len(self.groups) def columnCount(self, parent): return 3 def flags(self, index): if index.column() == 2: fl = fl = Qt.ItemIsEnabled | Qt.ItemIsSelectable else: fl = Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable return fl def headerData(self, section, orientation, role): if role == Qt.DisplayRole and orientation == Qt.Horizontal: return self.header_labels[section] def removeRow(self, row, parent = QModelIndex()): self.beginRemoveRows(parent, row, row) self.gro…
has comment: http://stackoverflow.com/comment/84144552
type: Question
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/48574300
has answer: http://stackoverflow.com/a/48574300
score: 0
tagged with: pyside2

http://stackoverflow.com/q/48504022
type: Question
score: 2
has body: I have a DataFrame that has two levels of indices. The first level consists of the strings in the list names, and the second levels consists of datetime objects. I am trying to remove the first row at every outer index For example: &gt;&gt;&gt; print(df) val1 val2 name date Tom 2018-01-01 2.3 5.4 2018-01-02 3.6 8.2 Jerry 2018-02-18 5.7 1.3 2018-02-19 7.2 3.8 names = ['Tom', 'Jerry'] for name in names: df.loc[name].drop(&lt;row 0 of this name&gt;, inplace=True) &gt;&gt;&gt; print(df) val1 val2 name date Tom 2018-01-02 3.6 8.2 Jerry 2018-02-19 7.2 3.8
answer count: 3
accepted answer: http://stackoverflow.com/a/48504138
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48504137
upvote count: 2
has answer: http://stackoverflow.com/a/48504138
downvote count: 0
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48504137
tagged with: python
has answer: http://stackoverflow.com/a/48504544
has title: Drop 1st row of every outer index

http://stackoverflow.com/comment/84044828
comment on: http://stackoverflow.com/q/48524927
has text: Your question is unclear. You don't seem to want to split on *any* underscore, only the last one, is that correct?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48541819
has comment: http://stackoverflow.com/comment/90671334
has comment: http://stackoverflow.com/comment/90665690
downvote count: 0
answer count: 1
tagged with: django
tagged with: python
tagged with: django-rest-framework
tagged with: django-hvad
has body: I'm trying to implement django-hvad on a django app but I'm getting an error when I'm trying to launch python manage.py runserver : File "/Users/Philippe/Documents/DjangoApp/env/lib/python3.6/site-packages/hvad/manager.py", line 265, in _clone return super(TranslationQueryset, self)._clone(**kwargs) TypeError: _clone() got an unexpected keyword argument 'shared_model' Did I made any mistakes to translate my models? Thanks for your help! models.py class Opponent(TranslatableModel): name = models.CharField(max_length=255, unique=True, null=True) companyType = models.ForeignKey(CompanyType, on_delete=models.SET_NULL, blank=True, null=True, related_name='opponents') pricing = models.ManyToManyField(Pricing, blank=True) translations = TranslatedFields( description = models.TextField(null=True, blank=True) ) def __str__(self): return "{}" .format(self.name) def save(self, *args, **kwargs): super(Opponent, self).save(*args, **kwargs) # Call the "real" save() method. serializers.py class OpponentSerializer(TranslatableModelSerializer): class Meta: model = Opponent fields = '__all__' views.py class OpponentViewSet(viewsets.ModelViewSet): queryset = Opponent.objects.language().all() serializer_class = OpponentSerializer def get_queryset(self): user_language = self.request.GET.get('language') return Opponent.objects.language(user_language).all()
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51994717
has answer: http://stackoverflow.com/a/51994717
upvote count: 3
favorite count: 0
type: Question
has title: Django-hvad translate model of django-rest-framework

http://stackoverflow.com/q/48604046
type: Question
upvote count: 2
has title: how to pass a pipe() descriptor to Python subprocess.Popen(), in any version of Python
downvote count: 0
has body: I want to spawn a child process in Python, whose standard streams are used for other purposes and I can't touch them, and I want to have a dedicated pipe for my own purposes, independent of standard streams. In Python version 2, the following works: foobar.py: #!/usr/bin/python from os import pipe, environ, read import subprocess output, input = pipe() new_environ = environ.copy() new_environ["PIPE_INPUT"] = str(input) subprocess.Popen(['./a.out'], env=new_environ) print(read(output, 6)) and a.out is compiled from foobar.c: #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; void main() { write(atoi(getenv("PIPE_INPUT")), "foobar", 6); } This works, ./foobar.py prints foobar. But, with the shebang line #!/usr/bin/python3 it does not work. Of course, this is because, according to the docs, in Python 3 the descriptors are not inheritable. Well, then how do I do this in Python 3, and also so that the same code works for Python 2. I cannot have different code for different Pythons, has to be portable code for Python 2 and 3.
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84205465
tagged with: python
has comment: http://stackoverflow.com/comment/84205040
has comment: http://stackoverflow.com/comment/84205321
tagged with: pipe
accepted answer: http://stackoverflow.com/a/48604431
has comment: http://stackoverflow.com/comment/84204872
answer count: 1
has comment: http://stackoverflow.com/comment/84205101
has answer: http://stackoverflow.com/a/48604431
favorite count: 0

http://stackoverflow.com/q/48522389
upvote count: 1
score: -4
answer count: 1
has title: What is the use of pause() function here (regarding raspberry pi) and why it is written in the end?
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 5
tagged with: python
has body: What is the use of pause() function here (regarding raspberry pi) and why it is written in the end? #!/usr/bin/env python3 from gpiozero import Button from signal import pause import os, sys offGPIO = int(sys.argv[1]) if len(sys.argv) &gt;= 2 else 21 holdTime = int(sys.argv[2]) if len(sys.argv) &gt;= 3 else 6 # the function called to shut down the RPI def shutdown():`enter code here` os.system("sudo poweroff") btn = Button(offGPIO, hold_time=holdTime) btn.when_held = shutdown pause() # handle the button presses in the background
has answer: http://stackoverflow.com/a/48522487
tagged with: raspberry-pi

http://stackoverflow.com/q/48609632
has answer: http://stackoverflow.com/a/48609953
has comment: http://stackoverflow.com/comment/84216224
has comment: http://stackoverflow.com/comment/84215976
favorite count: 0
has comment: http://stackoverflow.com/comment/84215890
type: AnsweredQuestion
tagged with: while-loop
answer count: 5
possible better answer: http://stackoverflow.com/a/48609843
has comment: http://stackoverflow.com/comment/84215913
score: 1
has comment: http://stackoverflow.com/comment/84215775
has body: It's my first time to ask a question here. I try to get players whose height is above 200 centimeters but I don't know why it doesn't work until I adjust i += 1 to i += 2, and I still don't know why it works. By the way, I try to use while loops but not for loops to write this code. Thanks in advance! players = [['James', 202], ['Curry', 193], ['Durant', 205], ['Jordan', 199], ['David', 211]] i = 0 while i &lt; len(players): if players[i][1] &lt; 200: continue print(players[i]) i += 1
has answer: http://stackoverflow.com/a/48609724
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/84227079
has comment: http://stackoverflow.com/comment/84216116
accepted answer: http://stackoverflow.com/a/48609721
has answer: http://stackoverflow.com/a/48609744
downvote count: 0
has title: why i += 1 changes to i += 2 works?
has answer: http://stackoverflow.com/a/48609843
upvote count: 1
has comment: http://stackoverflow.com/comment/84215728
has answer: http://stackoverflow.com/a/48609721

http://stackoverflow.com/q/48492727
tagged with: python
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48492788
has comment: http://stackoverflow.com/comment/83978706
answer count: 2
downvote count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/48492788
has comment: http://stackoverflow.com/comment/83978781
has answer: http://stackoverflow.com/a/48492780
linked to: http://stackoverflow.com/q/47357090
has body: I'm currently in the middle of a recorded Python lecture and I think the version of python the teacher is using is outdated and he is writing a tkinter program but after copying it I keep getting this error: Traceback (most recent call last): File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\Lecture Class 11.py", line 35, in &lt;module&gt; photo = PhotoImage(file="Me With My 5th Place.jpg") File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3539, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3495, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't recognize data in image file "Me With My 5th Place.jpg" And here is my code: from tkinter import * class Application(Frame): def __init__(self, master): super(Application, self).__init__(master) self.grid() self.button_clicks = 0 self.create_widgets() def create_widgets(self): self.label1 = Label(self) label1.image = photo label1.grid() self.button1 = Button(self) self.button1["text"] = "Click me!!!" self.button1["command"] = self.update_count self.button1.grid(row=1, column=1) self.button2 = Button(self) self.button2["text"] = "Reset click counter" self.button2["command"] = self.reset_count self.button.grid(row=3, column= 1) def update_count(self): self.button_clicks += 1 self.button1["text"] = "Total clicks: " + str(self.button_clicks) def res_count(self): self.button_clicks = 0 self.button["text"] = "I am reset. Click me!!!" root = Tk() root.title("CP101 click counter") root.geometry("400x400") photo = PhotoImage(file="Me With My 5th Place.jpg") app = Application(root) root.mainloop()
accepted answer: http://stackoverflow.com/a/48492780
has title: tkinter.TclError: couldn't recognize data in image file
type: AnsweredQuestion
upvote count: 3
score: 1
duplicate of: http://stackoverflow.com/q/47357090

http://stackoverflow.com/comment/84118750
type: AnswerComment
has text: Nope. It would still not be able to tell the difference between `grammar` and `agmrrrr`. Read the [documentation on `set`](https://docs.python.org/3.6/library/stdtypes.html#set-types-set-frozenset) for the reason.
comment on: http://stackoverflow.com/a/48547894
type: Comment
score: 0

http://stackoverflow.com/q/48550643
has answer: http://stackoverflow.com/a/48550681
possible better answer: http://stackoverflow.com/a/48550681
has answer: http://stackoverflow.com/a/48550686
accepted answer: http://stackoverflow.com/a/48550686
tagged with: matplotlib
has title: Error: module 'matplotlib' has no attribute 'plot'
tagged with: python
has comment: http://stackoverflow.com/comment/84097270
upvote count: 6
type: AnsweredQuestion
answer count: 2
linked to: http://stackoverflow.com/q/34139163
downvote count: 0
duplicate of: http://stackoverflow.com/q/34139163
score: 6
tagged with: plot
has body: I am using python 3.6 and while running the below code i am getting as error which says Traceback (most recent call last): File "C:/Users/Sagar/AppData/Local/Programs/Python/Python36-32/graphfile.py", line 10, in plt.plot(x,y) AttributeError: module 'matplotlib' has no attribute 'plot' The code is import matplotlib as plt x=[] y=[] readfile=open("graph.txt","r") data=readfile.read().split("\n") for i in data: val=i.split(",") x.append(int(val[0])) y.append(int(val[1])) plt.plot(x,y) plt.show()
favorite count: 0
type: Question
tagged with: attributeerror

http://stackoverflow.com/q/48591693
tagged with: python
has answer: http://stackoverflow.com/a/48593027
type: Question
tagged with: numpy
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: sorting
has title: Numpy - custom sort of rows and columns in array
favorite count: 0
has body: Can I sort the rows or columns of an array according to values stored in a separate list? For example: row_keys = [10, 11, 5, 6] z = np.array([[2.77, 11., 4.1, 7.2], [3.7, 2.2, 1.1, 0.5], [2.5, 3.5, 5.0, 9.0], [4.3, 2.2, 5.1, 6.1]]) Should produce something like array([[ 2.5, 3.5, 5. , 9. ], [ 4.3, 2.2, 5.1, 6.1] [ 2.77, 11. , 4.1, 7.2], [ 3.7, 2.2, 1.1, 0.5], ]) And similar functionality applied to the columns, please.
tagged with: multidimensional-array
tagged with: matrix
score: 1

http://stackoverflow.com/q/48490792
tagged with: opencv
has body: I've been using datasets from sklearn. And I want to show image from 'MNIST original' using openCV.imshow Here is part of my code dataset = datasets.fetch_mldata('MNIST original') features = np.array(dataset.data, 'int16') labels = np.array(dataset.target, 'int') list_hog_fd = [] deskewed_images = [] for img in features: cv2.imshow("digit", img) deskewed_images.append(deskew(img)) "digit" window appears but it is definitely not an digit image. How can I access real image from dataset?
has title: Show image from fetched data using openCV
tagged with: mnist
tagged with: python
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48490883
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48490883
tagged with: scikit-learn
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/84263448
type: QuestionComment
score: 0
has text: PyInstaller should have an option to create a GUI app that doesn't have a console window, which may be all you need. You can also run a task in the background services sessions by enabling it to run whether the user is logged on or not, but non-local UNC paths and mapped network drives may not function in that case for various reasons.
comment on: http://stackoverflow.com/q/48627747
type: Comment

http://stackoverflow.com/comment/84113665
has text: Code cleaned up :)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48558805

http://stackoverflow.com/comment/84195282
has text: You need more efficiency than O(1) for each of the indexing operations? Interesting...
type: Comment
type: QuestionComment
score: 9
comment on: http://stackoverflow.com/q/48599380

http://stackoverflow.com/comment/84302103
comment on: http://stackoverflow.com/a/48640515
has text: That module should come with `mysql.connector`. It's also in their docs (I linked to them in the answer).
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/100432099
type: Comment
has text: Hi, welcome to SO! This question has already been answered, and an answer was accepted. If you believe your answer does add something more to said question, please elaborate why this solution is better then the one accepted. Otherwise it won't be likely to attract much appreciation.
type: AnswerComment
comment on: http://stackoverflow.com/a/56946289
score: 4

http://stackoverflow.com/comment/84175932
type: AnswerComment
score: 0
has text: Thank you! I'll check this out now.
type: Comment
comment on: http://stackoverflow.com/a/48589143

http://stackoverflow.com/a/48619698
has body: For education purpose, a solution with recursion. Do not use in productive code. nestedList = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] newList = [1,2,3] def appendto(L1, L2): if L1 == []: return [] else: return [L1[0] + [L2[0]]] + appendto(L1[1:], L2[1:]) print(appendto(nestedList, newList)) # -&gt; [['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48619260

http://stackoverflow.com/comment/84021290
score: 0
type: Comment
type: AnswerComment
has text: Thank you, I'll read through the docs now and thank you very much for your response.
comment on: http://stackoverflow.com/a/48513167

netcdf4
tags question: http://stackoverflow.com/q/48501843
tags question: http://stackoverflow.com/q/48645682
type: Tag
tag name: netcdf4

http://stackoverflow.com/q/48557887
favorite count: 0
has body: I have created a new firefox profile, that I want to use for the automated tests. When calling firefox manually with this profile then I see the menu bar and the bookmarks toolbar. But when using this profile within my code I still get no menubar and no bookmarks toolbar myprofile = webdriver.FirefoxProfile('C:/Users/xxxxx/Documents/1tm2mblc.WebDriver_Profile') driver = webdriver.Firefox(executable_path="C:\\Program Files (x86)\\eclipse\\geckodriver.exe", firefox_profile=myprofile) So the behaviour is exactly the same as if I don't specify any profile at all. If I put a typo in the profile path then I get an error message, so the profile seems not to be ignored... Geckodriver log: https://www.dropbox.com/s/awg3kv2x1lqetpo/geckodriver.log?dl=0 Logfile with DEBUG Trace Level contains the following lines: 02/02/2018 12:50:44 PM POST http://127.0.0.1:55237/session {"capabilities": {"firstMatch": [{}], "alwaysMatch": {"browserName": "firefox", "acceptInsecureCerts": true, "moz:firefoxOptions": {"profile": "UEsDBBQAAAAIADBGQUygpt2X......" 02/02/2018 12:51:15 PM Finished Request {'value': {'sessionId': 'ebdcc867-62c8-4c8c-900b-ba272fd15345', 'capabilities': {'acceptInsecureCerts': True, 'browserName': 'firefox', 'browserVersion': '58.0.1', 'moz:accessibilityChecks': False, 'moz:headless': False, 'moz:processID': 5316, 'moz:profile': 'C:\\Users\\herololi\\AppData\\Local\\Temp\\rust_mozprofile.8xCt6R02aSkK', 'moz:webdriverClick': True, 'pageLoadStrategy': 'normal', 'platformName': 'windows_nt', 'platformVersion': '6.1', 'rotatable': False, 'timeouts': {'implicit': 0, 'pageLoad': 300000, 'script': 30000}}}} 02/02/2018 12:51:15 PM POST http://127.0.0.1:55237/session/ebdcc867-62c8-4c8c-900b-ba272fd15345/url {"url": "http://only-testing-blog.blogspot.in/2014/05/login.html"} 02/02/2018 12:51:25 PM Finished Request {'value': {}} 02/02/2018 12:51:25 PM POST http://127.0.0.1:55237/session/ebdcc867-62c8-4c8c-900b-ba272fd15345/timeouts {"implicit": 20000} 02/02/2018 12:51:25 PM Finish…
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84154525
has comment: http://stackoverflow.com/comment/84154494
tagged with: firefox-profile
type: UnansweredQuestion
has title: Selenium Webdriver with Python: Firefox Profile Handling
tagged with: python
has comment: http://stackoverflow.com/comment/84128627
tagged with: selenium-webdriver
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/103557153
has comment: http://stackoverflow.com/comment/84160909
upvote count: 2
downvote count: 0
tagged with: selenium
linked to: http://stackoverflow.com/q/58620609

http://stackoverflow.com/a/48594552
score: 2
downvote count: 0
has body: No, it's not essential to use virtualenv for Django but it's recommended because it isolates the multiple versions of python or libraries you are using for your projects on your system. If you are not using virtualenv then that library will be the part of your python home directory. For Example: If you are using version 1 of some library for one project and later on in other projects you have to use or if it's the requirement to use version 2 of that library then using specific virtualenv (if you are working on multiple projects simultaneously) for that project enables you to use multiple libraries without any problem.
answers question: http://stackoverflow.com/q/48594395
type: Answer
upvote count: 2

http://stackoverflow.com/comment/84287861
type: QuestionComment
has text: Yes, I did this. You can define one function and if you want to use in other function capture the return values there.
comment on: http://stackoverflow.com/q/48644689
score: 0
type: Comment

http://stackoverflow.com/comment/84099055
comment on: http://stackoverflow.com/q/48551165
score: 0
has text: @O.rka: You can also just do this within Python: `with open(filename, 'rb') as handle: total = sum(line.startswith('>') for line in handle)`.
type: Comment
type: QuestionComment

pygobject
type: Tag
tags question: http://stackoverflow.com/q/48559407
tag name: pygobject
tags question: http://stackoverflow.com/q/48570058

http://stackoverflow.com/a/48601831
accepted answer of: http://stackoverflow.com/q/48573243
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48573243
has body: Here's a way to arrange this. First up, you make a separate graph for each network to run them in parallel in different sessions: graph1 = tf.Graph() with graph1.as_default(): model1 = build_model() graph2 = tf.Graph() with graph2.as_default(): model2 = build_model() ... where build_model() defines all placeholders, variables and training ops. Both models should use the same naming for variables, which will allow them to swap the state easily. Each network can be trained using a snapshot of the other network for the target (the latest or previous best, it's up to you). Periodically, each network is saved to the disk via tf.Saver() and restored using the weights of one the networks. For example, this code will load the weights from the 2nd network into the 1st graph: with tf.Session(graph=graph1) as sess: saver = tf.train.import_meta_graph('/tmp/model-2/network.meta') saver.restore(sess, '/tmp/model-2/network') ... continue training And this is how the model is saved: with tf.Session(graph=graph1) as sess: ... do some training save_path = saver.save(sess, '/tmp/model-1/network') More on saving and restoring in this question. You can do this in the same session or start a new one. In fact, you can even try to use the same location on disk for both networks, so that both save and restore from the same file. But this will force you to have the latest snapshot, while the previous approach is more flexible. One thing you need to be careful of is the use of sessions: a session created for graph1 can only evaluate tensors and ops from the graph1. Example: def build_model(): x = tf.placeholder(tf.float32, name='x') y = tf.placeholder(tf.float32, name='y') z = x + y return x, y, z graph1 = tf.Graph() with graph1.as_default(): x1, y1 ,z1 = build_model() graph2 = tf.Graph() with graph2.as_default(): x2, y2, z2 = build_model() with tf.Session(graph=graph1) as sess1: with tf.Session(graph=graph2) as sess2: # Good print(sess1.run(z1, feed_dict={x1: 1, y1: 2})) # 3.0 print(sess2.ru…
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/84204190
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48598907
type: Comment
has text: when I call `write_csv('LCTITAN','abcd.csv')`, it returns error `AttributeError: 'file' object has no attribute 'writerows'`

ubuntu
tags question: http://stackoverflow.com/q/48597380
tags question: http://stackoverflow.com/q/48603866
tags question: http://stackoverflow.com/q/48638872
tags question: http://stackoverflow.com/q/48589963
tags question: http://stackoverflow.com/q/48601771
tags question: http://stackoverflow.com/q/48538625
tag name: ubuntu
tags question: http://stackoverflow.com/q/48594354
tags question: http://stackoverflow.com/q/48542005
tags question: http://stackoverflow.com/q/48540483
tags question: http://stackoverflow.com/q/48597930
tags question: http://stackoverflow.com/q/48537039
tags question: http://stackoverflow.com/q/48493028
tags question: http://stackoverflow.com/q/48578304
tags question: http://stackoverflow.com/q/48643455
tags question: http://stackoverflow.com/q/48506436
type: Tag
tags question: http://stackoverflow.com/q/48556297
tags question: http://stackoverflow.com/q/48581973
tags question: http://stackoverflow.com/q/48545467
tags question: http://stackoverflow.com/q/48526788
tags question: http://stackoverflow.com/q/48493695
tags question: http://stackoverflow.com/q/48639424
tags question: http://stackoverflow.com/q/48511008
tags question: http://stackoverflow.com/q/48513473
tags question: http://stackoverflow.com/q/48618827

http://stackoverflow.com/comment/84251217
type: Comment
score: 0
type: AnswerComment
has text: Thanks. It worked. i knew i was missing something small
comment on: http://stackoverflow.com/a/48627095

full-text-search
tags question: http://stackoverflow.com/q/48582862
type: Tag
tag name: full-text-search

http://stackoverflow.com/q/48519546
has answer: http://stackoverflow.com/a/48608133
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: What does the tuples we mention inside openpyxl.reference method mean?
score: 0
has body: What does the tuples we mention inside openpyxl.reference method mean? in following :- from openpyxl.chart import ( Reference, Series, BarChart ) wb = load_workbook('revenue.xlsx') wsheet = wb.get_sheet_by_name('sales') print (wsheet) data = Reference(wsheet, min_col=5, min_row=2, max_col=5, max_row=10) OR data = Reference(wsheet, (5, 2), (5, 10)) I went through some docs but they were not that clear to me
has comment: http://stackoverflow.com/comment/84219866
answer count: 1

http://stackoverflow.com/q/48585073
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84167040
type: Question
has body: Pandas example data frame id age 0 1 2 1 4 NaN 2 NaN NaN 3 5 16 4 6 21 5 7 NaN expected output id age 0 1 2 1 4 7 2 NaN 11 3 5 16 4 6 21 5 7 26 here if i want fill missing age , with previous age + 5 , how to do that ?
has comment: http://stackoverflow.com/comment/84167056
has comment: http://stackoverflow.com/comment/84167027
has answer: http://stackoverflow.com/a/48585787
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/84168134
has title: How to replace NaNs by preceding values plus some constant , in pandas DataFrame?
score: 0
has comment: http://stackoverflow.com/comment/84166974

http://stackoverflow.com/comment/84054419
comment on: http://stackoverflow.com/q/48524013
type: QuestionComment
has text: `pip show Django`. Also problem could be if your Django version < 2.0 because `from django.urls import path` is new feature starting from Django 2.0.
score: 0
type: Comment

http://stackoverflow.com/comment/84191147
has text: Thank you all for contributing to this answer, it fully solves my problems and it's performance is boss. If i could i would accept all your previous answers, since all of them are solving the problem. Still this solution has the shortest length, and is using just one import.
comment on: http://stackoverflow.com/a/48597015
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48610236
has comment: http://stackoverflow.com/comment/84216964
answers question: http://stackoverflow.com/q/48610033
score: 0
has body: Demodata: verts = [(-94, -24, -87), (90, 27, -56), (-22, -59, -44), (50, -70, 52), (-31, 37, -24), (-73, 53, 66), (-47, -28, 99), (-3, -42, -66), (2, 85, 58), (79, -86, 39)] Find min/max: z = [(min(l),max(l)) for l in zip(*verts)] # [(min,max) for each # (x0,..,xn),(y0,..,yn),(z0,..,zn) ] extends_min, extends_max = zip(*z) print(extends_min, extends_max) Output: (-94, -86, -87) (90, 85, 99)
type: Answer

python-2.7
tags question: http://stackoverflow.com/q/48514395
tags question: http://stackoverflow.com/q/48529355
tags question: http://stackoverflow.com/q/48606792
tags question: http://stackoverflow.com/q/48529713
tags question: http://stackoverflow.com/q/48557017
tags question: http://stackoverflow.com/q/48508068
tags question: http://stackoverflow.com/q/48507182
tags question: http://stackoverflow.com/q/48622281
tags question: http://stackoverflow.com/q/48630957
tags question: http://stackoverflow.com/q/48519001
tags question: http://stackoverflow.com/q/48558957
tags question: http://stackoverflow.com/q/48550672
tags question: http://stackoverflow.com/q/48565004
tags question: http://stackoverflow.com/q/48527100
tags question: http://stackoverflow.com/q/48488712
tags question: http://stackoverflow.com/q/48562383
tags question: http://stackoverflow.com/q/48524928
tags question: http://stackoverflow.com/q/48552996
tags question: http://stackoverflow.com/q/48572647
tags question: http://stackoverflow.com/q/48586146
tags question: http://stackoverflow.com/q/48617874
tags question: http://stackoverflow.com/q/48557055
tags question: http://stackoverflow.com/q/48613919
tags question: http://stackoverflow.com/q/48510404
tags question: http://stackoverflow.com/q/48527958
tags question: http://stackoverflow.com/q/48512690
tags question: http://stackoverflow.com/q/48536916
tags question: http://stackoverflow.com/q/48511319
tags question: http://stackoverflow.com/q/48604263
tags question: http://stackoverflow.com/q/48564671
tags question: http://stackoverflow.com/q/48532331
tags question: http://stackoverflow.com/q/48632349
tags question: http://stackoverflow.com/q/48554539
tags question: http://stackoverflow.com/q/48529567
tags question: http://stackoverflow.com/q/48567935
tags question: http://stackoverflow.com/q/48513401
tags question: http://stackoverflow.com/q/48575598
tags question: http://stackoverflow.com/q/48626785
tags question: http://stackoverflow.com/q/48604845
tags question: http://stackoverflow.com/q/48565776
tags question: http://stackoverflow.com/q/48526360
tags question: http://stackoverflow.com/q/48596758
tags question: http://stackoverflow.com/q/48614187
tags question: http://stackoverflow.com/q/48532713
tags question: http://stackoverflow.com/q/48630171
type: Tag
tags question: http://stackoverflow.com/q/48565894
tags question: http://stackoverflow.com/q/48580686
tags question: http://stackoverflow.com/q/48642694
tags question: http://stackoverflow.com/q/48514222
tags question: http://stackoverflow.com/q/48501128
tags question: http://stackoverflow.com/q/48635316
tags question: http://stackoverflow.com/q/48635325
tags question: http://stackoverflow.com/q/48552038
tags question: http://stackoverflow.com/q/48531810
tags question: http://stackoverflow.com/q/48615775
tags question: http://stackoverflow.com/q/48639351
tags question: http://stackoverflow.com/q/48591898
tags question: http://stackoverflow.com/q/48644605
tags question: http://stackoverflow.com/q/48601095
tags question: http://stackoverflow.com/q/48621361
tags question: http://stackoverflow.com/q/48614998
tags question: http://stackoverflow.com/q/48619816
tags question: http://stackoverflow.com/q/48625059
tags question: http://stackoverflow.com/q/48599298
tags question: http://stackoverflow.com/q/48548937
tags question: http://stackoverflow.com/q/48645217
tags question: http://stackoverflow.com/q/48506525
tags question: http://stackoverflow.com/q/48512545
tags question: http://stackoverflow.com/q/48622262
tags question: http://stackoverflow.com/q/48527270
tags question: http://stackoverflow.com/q/48558948
tags question: http://stackoverflow.com/q/48573631
tags question: http://stackoverflow.com/q/48526580
tags question: http://stackoverflow.com/q/48503151
tags question: http://stackoverflow.com/q/48516776
tags question: http://stackoverflow.com/q/48516165
tags question: http://stackoverflow.com/q/48544798
tags question: http://stackoverflow.com/q/48632242
tags question: http://stackoverflow.com/q/48570822

http://stackoverflow.com/comment/91463144
type: Comment
comment on: http://stackoverflow.com/a/48549861
has text: I'd put the `print` statement after the loop. That way it is technically correct.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84183530
comment on: http://stackoverflow.com/q/48593051
type: QuestionComment
has text: Please provide a [mcve].
score: 0
type: Comment

http://stackoverflow.com/a/48634220
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48633982
answers question: http://stackoverflow.com/q/48633982
score: 1
has body: There are parkingFacilityStatus elements inside the identically named parkingFacilityStatus elements, which is rather confusing: … <parkingFacilityReference targetClass="ParkingFacility" id="24278[Karstadt]" version="1.0"/> closed … It's the closed that gives the error, as that element does not have a parkingFacilityReference subelement. Use for pf in parking_facility: facility_ref = pf.find('d:parkingFacilityReference', ns) if facility_ref is not None: ParkingspaceList.append(str((facility_ref.get('id')))) and it works.
type: Answer

pyglet
tags question: http://stackoverflow.com/q/48555284
tags question: http://stackoverflow.com/q/48502930
type: Tag
tag name: pyglet
tags question: http://stackoverflow.com/q/48530498

http://stackoverflow.com/a/48593444
has comment: http://stackoverflow.com/comment/84184117
has comment: http://stackoverflow.com/comment/84184276
has comment: http://stackoverflow.com/comment/84184200
score: 1
answers question: http://stackoverflow.com/q/48593345
type: Answer
has body: Incase you need a one liner [int(sum(i[1:])/len(i[1:])) for i in grades[1:]] Output: [90, 53, 64, 54, 70, 96]
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48506172
has comment: http://stackoverflow.com/comment/84049004
score: 4
has comment: http://stackoverflow.com/comment/84050319
answers question: http://stackoverflow.com/q/48504914
has body: The source code indicates that metrics.log_loss does not support probabilities in y_true. It only supports binary indicators of shape (n_samples, n_classes), for example [[0,0,1],[1,0,0]] or class labels of shape (n_samples,), for example [2, 0]. In the latter case the class labels will be one-hot encoded to look like the indicator matrix before calculating log loss. In this block: lb = LabelBinarizer() if labels is not None: lb.fit(labels) else: lb.fit(y_true) You are reaching lb.fit(y_true), which will fail if y_true is not all 1 and/or 0. For example: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from sklearn import preprocessing &gt;&gt;&gt; lb = preprocessing.LabelBinarizer() &gt;&gt;&gt; lb.fit(np.array([[0,1,0],[1,0,0]])) LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False) &gt;&gt;&gt; lb.fit(np.array([[0.2,0.8,0],[0.9,0.05,0.05]])) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/imran/.pyenv/versions/anaconda3-4.4.0/lib/python3.6/site-packages/sklearn/preprocessing/label.py", line 278, in fit raise ValueError("Multioutput target data is not supported with " ValueError: Multioutput target data is not supported with label binarization I would define your own custom log loss function: def logloss(y_true, y_pred, eps=1e-15): y_pred = np.clip(y_pred, eps, 1 - eps) return -(y_true * np.log(y_pred)).sum(axis=1).mean() Here is the output on your data: &gt;&gt;&gt; logloss(y_true, y_predict) 0.738961717153653
has comment: http://stackoverflow.com/comment/84050169
has comment: http://stackoverflow.com/comment/84049592
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84050017
downvote count: 1
has comment: http://stackoverflow.com/comment/84061553
accepted answer of: http://stackoverflow.com/q/48504914
has comment: http://stackoverflow.com/comment/84060695
upvote count: 5
type: Answer

http://stackoverflow.com/comment/84057136
type: Comment
type: AnswerComment
has text: I agree with your comment, you have the better solution. +1
comment on: http://stackoverflow.com/a/48530832
score: 1

http://stackoverflow.com/comment/84047888
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48522092
score: 0
has text: Ha! thank for this @Nestor Yanchuck... yeap I came across this as I continued searching! Sadly I think I'm not yet too confident with getting by this or I might have found it a little bit complex in my level of programming but thanks again! Btw tried to vote this up but my reputation is still low

http://stackoverflow.com/comment/84111969
type: QuestionComment
score: 0
has text: @cdarke else: print("Boş") break
comment on: http://stackoverflow.com/q/48557947
type: Comment

http://stackoverflow.com/comment/84112469
has text: I rephrase again :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48557893
score: 0

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/48574889
tags question: http://stackoverflow.com/q/48527581
tags question: http://stackoverflow.com/q/48613006
tags question: http://stackoverflow.com/q/48568162
tags question: http://stackoverflow.com/q/48591664
tags question: http://stackoverflow.com/q/48508018
tags question: http://stackoverflow.com/q/48581588
type: Tag
tags question: http://stackoverflow.com/q/48558948
tags question: http://stackoverflow.com/q/48554441

http://stackoverflow.com/comment/84122159
has text: I understand. You don't have the control on the format parameters. But you edited your question afterwards. format can `getattr` but it's very limited. Ex: you cannot slice and you cannot use negative indexes, at least not in python 3.4. For instance, something like this works `{pathname[4]:>90}` but `{pathname[:-10]:>90}` doesn't! bummer. this remains a good question.
comment on: http://stackoverflow.com/a/48560618
type: Comment
type: AnswerComment
score: 2

http://stackoverflow.com/comment/84124283
comment on: http://stackoverflow.com/a/48534062
type: AnswerComment
has text: Ilmari Karonen - you just the best!!! Can you please advice of a thorough Cheat Sheet on SQLite functions? Have in mind that I am very very beginner on this. Thanks a lot!
score: 0
type: Comment

http://stackoverflow.com/a/48817358
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48563303
score: 3
has body: The correct way to iterate through the ResultSet is by using its get_points() method, which can optionally filter by measurement or tags or both. For example: results = client.query("select * from cpu limit 1") for measurement in results.get_points(measurement='cpu'): usage_system = measurement['usage_system'] # do whatever with usage_system See the official InfluxDB-Python documentation.

http://stackoverflow.com/q/48599891
has comment: http://stackoverflow.com/comment/84197539
has answer: http://stackoverflow.com/a/48876177
has comment: http://stackoverflow.com/comment/84214495
has comment: http://stackoverflow.com/comment/84197305
type: UnansweredQuestion
has body: I'm coming from NetBeans and evaluating others and more flexible IDEs supporting more languages (i.e. Python) than just php and related. I kept an eye on Eclipse that seems to be the best choice; at the time I was not able to find an easy solution to keep the original project on my machine and automatically send / syncronize the files on the remove server via sftp. All solutions seems to be outdated or stupid (like mounting a smb partition or manually send the file via an ftp client! I'm not going to believe that an IDE like Eclipse doesn't have a smart solution of what I consider a basic feature of an IDE, so I think I missed something... On Eclipse forums I've seen the same question asked lots of time but without any answer! Some suggestions about is strongly apreciated otherwise I think the only solution is stick on one IDE each language I use that seem to be incredible on 2018. I'm developing on MacOS and the most interesting solution (kDevelop) fails on building with MacPorts. Thank you very much.
tagged with: python
tagged with: php
tagged with: eclipse
has comment: http://stackoverflow.com/comment/84214467
has title: Eclipse Oxygen: How to automatically upload php files on remote server
has comment: http://stackoverflow.com/comment/84207744
score: 1
tagged with: java
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84196882
upvote count: 1
has comment: http://stackoverflow.com/comment/84214119
favorite count: 0
type: Question

http://stackoverflow.com/q/48642476
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48656813
tagged with: sql
has answer: http://stackoverflow.com/a/48656813
has title: Django models design
tagged with: django
accepted answer: http://stackoverflow.com/a/48642729
type: Question
has answer: http://stackoverflow.com/a/48642729
tagged with: python
has body: I am working on a quiz app on Django and have the following models - User, Test, Question and Answer. The Test model acts as a wrapper for the Questions model. This is what my models looks like at present - models.py class Test(models.Model): def id_count(): current_count = Test.objects.count() current_count += 1 return current_count test_id = models.PositiveIntegerField(default=id_count,primary_key=True) test_description = models.CharField(max_length=255) class Question(models.Model): def id_count(): current_count = Question.objects.count() current_count += 1 return current_count test = models.ForeignKey(Test,on_delete=models.CASCADE) question_id = models.PositiveIntegerField(default=id_count,primary_key=True) question_text = models.CharField(max_length=255) option_one = models.CharField(max_length=12,default="Always") option_two = models.CharField(max_length=12,default="Never") class Answer(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) customuser = models.ForeignKey(CustomUser,on_delete=models.CASCADE,blank=True, null=True) original_answer_score = models.IntegerField(default=-1) The current models basically allow every user to answer the same question multiple times. How can I design my models to allow every user to answer one question only once? Thanks. Editing to add the respective view: class AnswerFormView(SingleObjectMixin, generic.FormView): template_name = 'tests/question_detail.html' form_class = forms.AnswerForm model = models.Answer def get_success_url(self,*args,**kwargs): return reverse('tests:question_detail', args=(self.kwargs['pk'],)) def form_valid(self, form): answer = models.Answer.objects.create( question=models.Question.objects.get(question_id=self.kwargs['pk']), customuser=self.request.user, original_answer_score=form.cleaned_data['original_answer_score'] ) return super(AnswerFormView, self).form_valid(form)
type: AnsweredQuestion

http://stackoverflow.com/q/48570417
type: Question
has body: I'm trying to replicate the results of the paper in the link https://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html This link explains how Multinomial Naive Bayes works for text classification. I've tried to reproduce the example using scikit learn. from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import preprocessing, decomposition, model_selection, metrics, pipeline from sklearn.model_selection import GridSearchCV, cross_val_score, KFold from sklearn.metrics import accuracy_score from sklearn.metrics import make_scorer from sklearn.naive_bayes import MultinomialNB #TRAINING SET dftrain = pd.DataFrame(data=np.array([["Chinese Beijing Chinese", "Chinese Chinese Shanghai", "Chinese Macao", "Tokyo Japan Chinese"], ["yes", "yes", "yes", "no"]])) dftrain = dftrain.T dftrain.columns = ['text', 'label'] #TEST SET dftest = pd.DataFrame(data=np.array("Chinese Chinese Chinese Tokyo Japan")) dftest.columns = ['text'] count_vectorizer = CountVectorizer(min_df=0, token_pattern=r"\b\w+\b", stop_words = None) count_train = count_vectorizer.fit_transform(dftrain['text']) count_test = count_vectorizer.transform(dftest['text']) clf = MultinomialNB() clf.fit(count_train, df['label']) clf.predict(count_test) The output is correctly printed as: array(['yes'], dtype='&lt;U3') Just like how its mentioned in the paper! The paper predicts it as YES because P(yes | test set) = 0.0003 &gt; P(no | test set) = 0.0001 I want to be able to see those two probabilities! When I type: clf.predict_proba(count_test) I get array([[ 0.31024139, 0.68975861]]) I think what this means is: P(test belongs to label 'no') = 0.31024139 and P(test belongs to label 'yes') = 0.68975861 Therefore, scikit-learn predicts the text as …
tagged with: naivebayes
tagged with: python
type: AnsweredQuestion
has title: Is there anyway to extract Maximum A Posteriori in scikit-learn Multinomial Naive Bayes based on the Stanford NLP research paper?
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48578286
accepted answer: http://stackoverflow.com/a/48578286
answer count: 1
tagged with: scikit-learn
tagged with: text-classification
favorite count: 0

http://stackoverflow.com/q/48639352
has comment: http://stackoverflow.com/comment/84275231
answer count: 1
tagged with: jquery
duplicate of: http://stackoverflow.com/q/2887209
tagged with: flask
type: Question
tagged with: ajax
type: UnansweredQuestion
has title: Jquery ajax response says "Unexpected token ':'" (using jsonp as datatype)
has body: I have a demo webserver written in Python Flask and I'm making ajax call to this server through jquery using jsonp. The url returns json as response but script is unable to parse it as json. The error says Unexpected token ":". Below is the code for webserver and ajax call and I've also commented the line where I'm getting the error. from flask import Flask, jsonify, render_template app = Flask(__name__) @app.route("/") def index(): html = ( """ Click Me ! """ ) return html @app.route("/url") def get_urls(): response = { "urls": { # for the ajax call, I get an error as Unexpected token ":". "url1": "/api/repos/url1", "url2": "/api/repos/url2", "url3": "/api/repos/url3" } } return jsonify(response) if __name__ == "__main__": app.run(debug=True) I'm quite new to javascript (jquery) and unable to figure out the issue. Any help would be appreciated.
tagged with: python
has answer: http://stackoverflow.com/a/48642407
score: 0
linked to: http://stackoverflow.com/q/2887209

http://stackoverflow.com/comment/84287525
has text: This is pretty broad.. could you refine your question to be a bit more specific? simple library / module requests are off topic for S.O.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48645285
type: QuestionComment

http://stackoverflow.com/a/48631899
downvote count: 0
upvote count: 1
type: Answer
has body: https://docs.python.org/3/howto/curses.html The Windows version of Python doesn’t include the curses module. A ported version called UniCurses is available. You could also try the Console module written by Fredrik Lundh, which doesn’t use the same API as curses but provides cursor-addressable text output and full support for mouse and keyboard input.
score: 1
answers question: http://stackoverflow.com/q/48631759

http://stackoverflow.com/q/48613671
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48613864
downvote count: 0
favorite count: 0
answer count: 4
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48614298
has body: I have a pandas.DataFrame: wordvecs_df, with columns labeled 'word', 'count', 'v1' through 'v50' and 'norm1' through 'norm50' in that order. I want to create a new pandas df with just the columns for 'word', 'count' and norm1-norm50. wordvecs_df.loc[:,"norm1":"norm50"] gets me norm1-norm50, but if I try to put in word and count I get an IndexingError: Too many indexers. I can't figure out how to get just the columns I want out of the dataframe. Any ideas?
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/48613791
accepted answer: http://stackoverflow.com/a/48613732
has title: slice pandas dataframe to get noncontiguous columns
tagged with: slice
has answer: http://stackoverflow.com/a/48613732
possible better answer: http://stackoverflow.com/a/48613864
tagged with: pandas

http://stackoverflow.com/q/48539500
answer count: 1
accepted answer: http://stackoverflow.com/a/62410484
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/62410484
tagged with: ms-access
favorite count: 0
type: Question
has body: Hello again community, I'm looking for a solution to 32 bit .mdb's conflicting with my 64 bit environment: 64 bit Windows 7, with a 64 bit MS Access Database driver running 64 bit python. I want to write data from these .mdb's into a 64 bit PostgreSQL database and possibly also to .csv files. However, I would like this tool to not only work on my machine but also those of colleagues so it would ideally be able to handle other environments as well. Initially I had a script writing to .csv with 32 bit versions of MS Access Database driver and python. However, I would like to create a QGIS plugin which I also had in 64 bit and I don't feel like changing everything to 32 bit just to be able to read the occasional 32 bit .mdb file. I am completely new to coding, but I have read up on the issue and understand it's basically not possible to make a direct connection between a 32 bit database and 64 bit script and driver. Still, I find it difficult to believe that there is no solution to this issue. Do web apps not regularly deal with these kind of situations? Would it be possible to create this kind of functionality using Django for example instead? Or would using a costly driver claiming to support both 32- and 64 bit be a solution? Would it be easier to create a standalone tool? Or does such a tool already exist which I just haven't yet been able to find? So to summarize: I'm looking to write data from a 32 bit .mdb to 64 bit PostgreSQL database preferably coded in a QGIS plugin. The initial code I had working before is: import csv, pyodbc from tkinter import Tk from tkinter.filedialog import askopenfilename Tk().withdraw() filename = askopenfilename()filenameEdit = filename.replace(":/", "://") print(filename) print(filenameEdit) MDB = filename DRV = '{Microsoft Access Driver (*.mdb, *.accdb)}' DBQ = filename PWD = 'pw' con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV,MDB,PWD)) cur = con.cursor() SQL = 'SELECT * FROM strips' # This query would need to be expande…
tagged with: postgresql
has comment: http://stackoverflow.com/comment/84074323
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84097707
tagged with: python
has comment: http://stackoverflow.com/comment/84096999
has comment: http://stackoverflow.com/comment/84097004
has comment: http://stackoverflow.com/comment/84108426
type: AnsweredQuestion
tagged with: 32bit-64bit
score: 1
has title: How to read from a 32 bit .mdb with 64 bit python and odbc driver

http://stackoverflow.com/q/48621825
score: 2
has title: How to use QTest to send a Ctrl-key combination in PyQt5?
answer count: 0
tagged with: pyqt
downvote count: 0
tagged with: pyqt5
tagged with: unit-testing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84262114
linked to: http://stackoverflow.com/q/20731054
has comment: http://stackoverflow.com/comment/84272638
upvote count: 2
type: UnansweredQuestion
tagged with: qtestlib
duplicate of: http://stackoverflow.com/q/20731054
tagged with: python
has comment: http://stackoverflow.com/comment/84260275
has body: I use PyQt5.6, Python 3.5 and Windows for a hobby project where I have an app with some actions (QAction) that have shortcuts set (for key combinations Ctrl-N and Ctrl-B, for example). I have written unit tests to verify that those actions can be triggered and they do what they should. However, I am not able to find any working example of how to trigger an action using a shortcut that has been set when writing a unit test with QTest. To support the question, this is the minimal application code: import sys from PyQt5 import QtGui, QtCore from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, QLabel ######################################################################## class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setGeometry(50, 50, 500, 300) action1 = QAction("&amp;Action1", self) action1.setShortcut("Ctrl+U") action1.triggered.connect(self.update_label) self.label = QLabel('Empty', self) self.setCentralWidget(self.label) main_menu = self.menuBar() file_menu = main_menu.addMenu("&amp;File") file_menu.addAction(action1) self.show() def update_label(self): print("updating label") self.label.setText('Updated label') if __name__ == '__main__': app = QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) The app has one action which can be triggered by Ctrl-U. The app works as expected. Now I have written a unit test suite: import unittest from PyQt5.QtWidgets import QApplication from PyQt5.Qt import QKeySequence from PyQt5.Qt import Qt from myapp import Window from PyQt5.QtTest import QTest ######################################################################## class Test(unittest.TestCase): #---------------------------------------------------------------------- def setUp(self): self.app = QApplication([]) self.ui = Window() self.menu = self.ui.menuBar() #---------------------------------------------------------------------- def test_update_label_from_menu(self): self.assertEqual(self.ui.label.text(), 'Empty') self.…

http://stackoverflow.com/comment/84280925
type: Comment
type: QuestionComment
has text: @LaurentH. Sure, I've added it to the question.
comment on: http://stackoverflow.com/q/48641805
score: 0

http://stackoverflow.com/q/48566647
has answer: http://stackoverflow.com/a/48567449
answer count: 1
tagged with: qlistview
score: 0
tagged with: python
type: Question
has title: QListView horizontal scrollbars not showing
has body: I noticed that after populating a QListView's sourceModel with data, the horizontal scrollbars do not appear? How do i fix this? Even if i set them to always show, they do not correctly expanded when content exceeds the width of the widget. I'm guessing the issues is because I'm setting the size hint to the icon size. The reason i do this is so i can control the size of the icon. import os, sys import tempfile from PySide import QtGui, QtCore class MyModel(QtCore.QAbstractTableModel): def __init__(self, *args, **kwargs): QtCore.QAbstractTableModel.__init__(self, *args, **kwargs) self._items = [] self._iconSize = QtCore.QSize(18, 18) def rowCount(self, index=QtCore.QModelIndex()): return len(self._items) def columnCount(self, index=QtCore.QModelIndex()): return 1 def addItem(self, obj): self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self._items.append(obj) self.endInsertRows() def data(self, index, role=QtCore.Qt.DisplayRole): if not index.isValid(): return None if 0 &lt;= index.row() &lt; self.rowCount(): item = self._items[index.row()] if role == QtCore.Qt.DisplayRole: return item elif role == QtCore.Qt.SizeHintRole: return self._iconSize class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None,): super(MainWindow, self).__init__(parent) self.resize(300, 300) # controls model = QtGui.QSortFilterProxyModel() model.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive) model.setSourceModel(MyModel()) self.ui_list = QtGui.QListView() self.ui_list.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.ui_list.setModel(model) self.ui_list.setWordWrap(False) self._populate_model() # layout self.setCentralWidget(self.ui_list) def _populate_model(self): root = tempfile.gettempdir() for f in os.listdir(root): self.ui_list.model().sourceModel().addItem(os.path.join(root,f)) def main(): app = QtGui.QApplication(sys.argv) ex = MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
type: UnansweredQuestion

http://stackoverflow.com/a/48585781
type: Answer
has body: Here's a useful list comprehension: &gt;&gt;&gt; [item for item in my_list if item.isnumeric()] ['9', '25'] Suggested Readings: String methods
answers question: http://stackoverflow.com/q/48585734
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84168666
downvote count: 0

http://stackoverflow.com/q/48605520
has comment: http://stackoverflow.com/comment/84207547
tagged with: python
has answer: http://stackoverflow.com/a/48605656
tagged with: python-3.6
upvote count: 6
tagged with: text
tagged with: replace
answer count: 2
type: UnansweredQuestion
has title: How to preprocess a text stream on the fly in Python?
has body: What I need is a Python 3 function (or whatever) that would take a text stream (like sys.stdin or like that returned by open(file_name, "rt")) and return a text stream to be consumed by some other function but remove all the spaces, replace all tabs with commas and convert all the letters to lowercase on the fly (the "lazy" way) as the data is read by the consumer code. I assume there is a reasonably easy way to do this in Python 3 like something similar to list comprehensions but don't know what exactly might it be so far.
tagged with: stream
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/48605755
favorite count: 0
type: Question

http://stackoverflow.com/a/73660061
type: Answer
has comment: http://stackoverflow.com/comment/130162798
score: 0
answers question: http://stackoverflow.com/q/48541671
has body: You meant sample weight = None is replaced "uniform_average" and not multiouput param!

http://stackoverflow.com/q/48609168
tagged with: neural-network
answer count: 1
has title: Low Convolutional Neural Network accuracy CIFAR-10
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/48613225
has comment: http://stackoverflow.com/comment/84219074
has answer: http://stackoverflow.com/a/48613225
tagged with: tensorflow
tagged with: python-3.x
linked to: http://stackoverflow.com/q/48594888
has comment: http://stackoverflow.com/comment/84222213
type: AnsweredQuestion
tagged with: classification
score: 0
has body: I started learning about neural networks and decided to follow this Google code lab on convolutional neural networks, but I decided to use the CIFAR-10 dataset for image classification, but I get very low accuracy and high cross-entropy. After training the accuracy is around 0.1 (never more than 0.2) and cross-entropy doesn't go below 230. I didn't use batch-normalization or dropout, but I should still get more accuracy here. My code: import tensorflow as tf import numpy as np import matplotlib as mpt import math # Just disables the warning, doesn't enable AVX/FMA import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def unpickle(file): import pickle with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict def makeMiniBatch(dictionary,start,number): matrix=np.zeros([number,3072],dtype=np.int) labels=np.zeros([number],dtype=np.int) for i in range(0,number): matrix[i]=dictionary[b'data'][i+start] labels[i]=dictionary[b'labels'][i+start] return matrix,labels def formatLabels(labele): lab=np.zeros([100,10]) for i in range(0,100): lab[i][labele[i]]=1 return lab def formatData(values): temp = np.zeros([100,32,32,3]) for i in range(0,100): im_r = values[i][0:1024].reshape(32, 32) im_g = values[i][1024:2048].reshape(32, 32) im_b = values[i][2048:].reshape(32, 32) temp[i] = np.dstack((im_r, im_g, im_b)) return temp batch='D:/cifar-10-python/cifar-10-batches-py/data_batch_1' data=unpickle(batch) tf.set_random_seed(0) K = 8 L = 16 M = 32 N = 200 X_=tf.placeholder(tf.float32,[None,32,32,3]) Y_=tf.placeholder(tf.float32,[None,10]) lr = tf.placeholder(tf.float32) W1 = tf.Variable(tf.truncated_normal([5, 5, 3, K], stddev=0.1)) B1 = tf.Variable(tf.ones([K])/10) W2 = tf.Variable(tf.truncated_normal([5, 5, K, L], stddev=0.1)) B2 = tf.Variable(tf.ones([L])/10) W3 = tf.Variable(tf.truncated_normal([4, 4, L, M], stddev=0.1)) B3 = tf.Variable(tf.ones([M])/10) W4 = tf.Variable(tf.truncated_normal([8 * 8 * M, N], stddev=0.1)) B4 = tf.Variable(tf.ones([N])/10) W5 = tf.…

http://stackoverflow.com/a/48618141
has comment: http://stackoverflow.com/comment/84248602
has comment: http://stackoverflow.com/comment/84247765
type: Answer
accepted answer of: http://stackoverflow.com/q/48615279
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48615279
has body: The code logic is a bit off. It modified the header row, then the line after the header row was printed, then it modified the header row again due to the while, but printed the next unmodified line, etc.; so it only looked like the table wasn't modified. Once count was high enough the while wouldn't be entered anymore, but row would start advancing. The end result was only the header row was modified over and over again. Change print(row[12]) to print(row) and you'll see what I mean. Here's a corrected version with comments: count = 0 for row in resultsTable[1:]: # skip header row via slicing. # while not needed, and prevented row from advancing print(count) row[12] = listPrefInd_a[count] row[13] = listPrefInd_b[count] row[14] = listPerfInd[count] print(row[12]) #debugging print count+=1 #advance to next row print(resultsTable[count]) #this gives the correct offset skipping header. The above is confusing. Here's an advanced version and demo. zip() returns an iterator that returns the first elements from each of its iterable parameters, then the 2nd elements, etc.; then row[12:] (element 12 to the end) is replaced with the three values in replacements: def resultsUpdate(resultsTable, listPrefInd_a, listPrefInd_b, listPerfInd): for row,replacements in zip(resultsTable[1:],zip(listPrefInd_a,listPrefInd_b,listPerfInd)): row[12:] = replacements resultsTable = [['nummer', 'datum', 'larvae', 'zeit', 'gruppe1', 'cs_a', 'med_a', 'neut_a', 'gruppe2', 'cs_b', 'med_b', 'neut_b', 'prefInd_a', 'prefInd_b', 'perfInd'], ['1', '19.01', '0', '0', 'AM', '15', '7', '4', 'BA', '11', '6', '13', '0', '0', '0'], ['2', '19.01', '0', '0', 'AM', '6', '6', '17', 'BA', '4', '11', '15', '0', '0', '0'], ['3', '19.01', '0', '0', 'BA', '9', '13', '10', 'AM', '8', '14', '11', '0', '0', '0'], ['4', '19.01', '0', '0', 'AM', '10', '10', '12', 'BA', '7', '9', '14', '0', '0', '0'], ['5', '19.01', '0', '0', 'BA', '10', '10', '12', 'AM', '10', '7', '13', '0', '0', '0'], ['6', '19.01', '0', '0', 'AM', '1', …

http://stackoverflow.com/comment/84184668
comment on: http://stackoverflow.com/a/48593697
has text: "You can also create a virtual device that has the play store if you want", is that in the docs??
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48488496
type: AnsweredQuestion
answer count: 1
score: -1
has answer: http://stackoverflow.com/a/48489077
tagged with: menu
has comment: http://stackoverflow.com/comment/83981911
has body: Using Tkinter 8.6 in Python 3.6 on Windows 10, at the moment my root form is rather narrow causing the menu bar to wrap. Is there a way to prevent wrapping? In this particular case, increasing the form width to accommodate the menu is acceptable behavior. The problem with wrapping is the geometry manager does not compensate - the grid, for instance, will have controls partially out of view since the window is not automatically resized to account for the extra menu height. Actual: Expected:
favorite count: 0
has comment: http://stackoverflow.com/comment/84002758
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83976565
upvote count: 0
accepted answer: http://stackoverflow.com/a/48489077
has title: How to prevent menu bar from wrapping?
tagged with: python
has comment: http://stackoverflow.com/comment/83999489
downvote count: 1

http://stackoverflow.com/comment/84016714
has text: Although your code is partly written in French the comments should be in English. If you want to communicate in french find a site where that is aloud. choice 1: you're not appending the output to the 'lettre' thus you get only the last one in the list_lettre.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48510652

http://stackoverflow.com/q/48567396
favorite count: 0
accepted answer: http://stackoverflow.com/a/48567705
has comment: http://stackoverflow.com/comment/84131158
type: AnsweredQuestion
has body: This is what I'm trying to do: Time Distance ---------- ---------- 1 100 2 200 I've tried: count = 1 print(' Hour ' + '\t' + ' Distance ') print('----------' + '\t' + '----------') while count &lt;= timeTraveled: print(str.center(10[str(count)]) + '\t' + str.center(10[str((speedOfVehicle * count))])) count = count + 1 No matter how much I try to make my variables a string for formatting purposes I always encounter: TypeError: 'int' object is not subscriptable
tagged with: centering
tagged with: python
type: Question
downvote count: 4
has answer: http://stackoverflow.com/a/48567705
has comment: http://stackoverflow.com/comment/84131084
upvote count: 0
has comment: http://stackoverflow.com/comment/84130997
has comment: http://stackoverflow.com/comment/84131142
has title: How can I center an integer variable in a string?
score: -4
answer count: 1
tagged with: string

web-scraping
tags question: http://stackoverflow.com/q/48532933
tags question: http://stackoverflow.com/q/48606245
tags question: http://stackoverflow.com/q/48573402
tags question: http://stackoverflow.com/q/48499580
tags question: http://stackoverflow.com/q/48586551
tags question: http://stackoverflow.com/q/48542140
tags question: http://stackoverflow.com/q/48492755
tags question: http://stackoverflow.com/q/48594666
tag name: web-scraping
tags question: http://stackoverflow.com/q/48499652
tags question: http://stackoverflow.com/q/48514985
tags question: http://stackoverflow.com/q/48542449
tags question: http://stackoverflow.com/q/48534197
tags question: http://stackoverflow.com/q/48505409
tags question: http://stackoverflow.com/q/48513472
tags question: http://stackoverflow.com/q/48585425
tags question: http://stackoverflow.com/q/48490940
tags question: http://stackoverflow.com/q/48645232
tags question: http://stackoverflow.com/q/48506950
tags question: http://stackoverflow.com/q/48494492
tags question: http://stackoverflow.com/q/48491227
tags question: http://stackoverflow.com/q/48536953
tags question: http://stackoverflow.com/q/48603981
tags question: http://stackoverflow.com/q/48537040
tags question: http://stackoverflow.com/q/48592572
tags question: http://stackoverflow.com/q/48603339
tags question: http://stackoverflow.com/q/48608698
tags question: http://stackoverflow.com/q/48509816
tags question: http://stackoverflow.com/q/48613380
tags question: http://stackoverflow.com/q/48592144
tags question: http://stackoverflow.com/q/48642096
type: Tag
tags question: http://stackoverflow.com/q/48566232
tags question: http://stackoverflow.com/q/48543070
tags question: http://stackoverflow.com/q/48573298
tags question: http://stackoverflow.com/q/48611682
tags question: http://stackoverflow.com/q/48534965
tags question: http://stackoverflow.com/q/48620526
tags question: http://stackoverflow.com/q/48595073
tags question: http://stackoverflow.com/q/48621854
tags question: http://stackoverflow.com/q/48639819
tags question: http://stackoverflow.com/q/48552475
tags question: http://stackoverflow.com/q/48494796
tags question: http://stackoverflow.com/q/48509337
tags question: http://stackoverflow.com/q/48528881
tags question: http://stackoverflow.com/q/48555250
tags question: http://stackoverflow.com/q/48587429
tags question: http://stackoverflow.com/q/48633016
tags question: http://stackoverflow.com/q/48578336
tags question: http://stackoverflow.com/q/48513576
tags question: http://stackoverflow.com/q/48593234
tags question: http://stackoverflow.com/q/48630681
tags question: http://stackoverflow.com/q/48567063
tags question: http://stackoverflow.com/q/48630109
tags question: http://stackoverflow.com/q/48583950
tags question: http://stackoverflow.com/q/48531008
tags question: http://stackoverflow.com/q/48493684
tags question: http://stackoverflow.com/q/48508068
tags question: http://stackoverflow.com/q/48609294
tags question: http://stackoverflow.com/q/48616051
tags question: http://stackoverflow.com/q/48622710
tags question: http://stackoverflow.com/q/48498910
tags question: http://stackoverflow.com/q/48567594
tags question: http://stackoverflow.com/q/48553427
tags question: http://stackoverflow.com/q/48639117
tags question: http://stackoverflow.com/q/48529032
tags question: http://stackoverflow.com/q/48538436
tags question: http://stackoverflow.com/q/48533318
tags question: http://stackoverflow.com/q/48621628
tags question: http://stackoverflow.com/q/48544207
tags question: http://stackoverflow.com/q/48636277
tags question: http://stackoverflow.com/q/48509147
tags question: http://stackoverflow.com/q/48541117

http://stackoverflow.com/comment/84257899
type: AnswerComment
comment on: http://stackoverflow.com/a/48629766
has text: @marmadukeandbob: that does indicate that your version of `twine` is too old. See https://packaging.python.org/guides/migrating-to-pypi-org/#uploading, and try to upgrade.
score: 0
type: Comment

http://stackoverflow.com/comment/84318158
has text: @AsimRaja It's a deceiving command, it may look like it's starting the python interpreter, but yes it's actually activating pip.I recommend you try install like this when you have pip errors in future, it just seems to be more likely to work.
comment on: http://stackoverflow.com/a/48650087
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48642667
score: 0
has body: I use SpaCy. https://spacy.io/ It is designed as an out-of-the-box NLP pipeline, so you shouldn't need to change anything about the model. It gives the "universal" and "Penn treebank" POS tags for the given sentence. It also does dependency tagging.
answers question: http://stackoverflow.com/q/48642141
type: Answer

http://stackoverflow.com/q/48496869
type: Question
has body: I'm working in Arabic text , I want to remove the Arabic Punctuation Example : s="أهلاً بالعالم في هذه التجربة ! علامات ،الترقيم ؟ ,? لا .اتذكرها" I want the output to remove " ؟ ، " also because when I use: import string tr= str.maketrans("","", string.punctuation) the output was 'أهلاً بالعالم في هذه التجربة علامات ،الترقيم ؟ لا اتذكرها'
tagged with: python-3.x
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/48499154
upvote count: 6
tagged with: python
tagged with: unicode
downvote count: 1
has title: Python3 : Remove Arabic Punctuation
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48499154
has answer: http://stackoverflow.com/a/62429861
possible better answer: http://stackoverflow.com/a/62429861

http://stackoverflow.com/a/48534657
score: 0
answers question: http://stackoverflow.com/q/48533849
type: Answer
has body: Here's a two liner: ##add new value, which was formerly the key {k: v.update({'name':k}) for k,v in pet_dictionary.items()} ##reset keys to value of 'age' new_pet = {v.get('age'): v for k,v in pet_dictionary.items()}
has comment: http://stackoverflow.com/comment/84074169

http://stackoverflow.com/a/48585410
has body: Through davidism's comments on my post, I was able to make the necessary change to my web service and get it hosted through IIS. The problem is that I was following the linked tutorial word for word, and not appreciating what the value for WSGI_HANDLER in the config file meant. I needed to make a call to the Flask instance that I created within my Python script: Excerpt from my Python script: from flask import * ... guestreg_api = Flask(__name__) Change made to web.config file: &lt;add key="WSGI_HANDLER" value="guestreg_api_v2.guestreg_api" /&gt;
answers question: http://stackoverflow.com/q/48527904
type: Answer
accepted answer of: http://stackoverflow.com/q/48527904
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/84163395
type: QuestionComment
comment on: http://stackoverflow.com/q/48567861
score: 0
type: Comment
has text: @Umberto, i cant say how long time, but hours, i'm using a MacBook Pro 2015, also i tried with heroku.

http://stackoverflow.com/q/48614790
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48615039
has comment: http://stackoverflow.com/comment/84229960
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84226730
has title: How to connect python and C# winform
has comment: http://stackoverflow.com/comment/84231090
linked to: http://stackoverflow.com/q/181719
downvote count: 1
favorite count: 0
type: Question
has body: Good morning. !!! We want to develop a platform for machine learning using data from sensors. The language used in the project is C# winform. I want to excuter python from c# winform. With winforms as the UI I want to run the analysis with python and see the results. numpy, pandas, etc... Python code for running a machine. I would like to advise you if you know someone who has been worried about me or how. thanks!!
tagged with: winforms
tagged with: c#
type: UnansweredQuestion
upvote count: 0
duplicate of: http://stackoverflow.com/q/181719
tagged with: machine-learning

http://stackoverflow.com/q/48513344
has comment: http://stackoverflow.com/comment/84021531
has title: Assign flag value based on condition
score: 2
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/84021610
answer count: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84034544
has body: I have a dataframe that looks like below groups|score|threshold|cumsum| A |3 |4 |3 | A |2 |4 |5 | A |1 |4 |6 | B |6 |5 |6 | B |1 |5 |7 | C |4 |4 |4 | In the Dataframe I want to create a new column called top_flag. This new column will flag observation in the dataframe as fools; Flag each observation whose cumsum less than threshold as 1. In this case only the first observation in the A group will be flagged. 2.Next, within each group, flag the first row that violates the condition above as 1. In this way, we can see that all the observation in group B violates the condition in (1) so will just flag the first observation in that group as 1 else 0. For C, there is only one observation and it violates our condition but since it is only 1 observation in that group we will flag it as 1 anyway. My desired final dataset should look like below: groups|score|threshold|cumsum|top_flag A |3 |4 |3 |1 A |2 |4 |5 |0 A |1 |4 |6 |0 B |6 |5 |6 |1 B |1 |5 |7 |0 C |4 |4 |4 |1 Can anybody show me how to easily do this pandas? My first try is as follows: #condition 1 df1 =df[df.cumsum &lt; df.threshhold] df['top_flag'] = 1 #condition 2 df2 = df[df.cum &gt;= df.threshhold] #within each group rank cumsum in ascending to flag anywhere rank = 1 as 1 else 0. df2['rank'] =df2.groupby(['groups'])['cumsum'].apply(lambda x: x.rank()) df2['top_flag'] = df1['rank'].apply(lambda x: 1 if x == 1 else 0) df2 = df2.drop(columns = 'rank') df_final = pd.concat([df1,df22]) df_final = df_final.groupby(['groups']) I strongly feel like there is gotta be a slicker way to do this in pandas. Does anyone knows of a better way?
favorite count: 0
accepted answer: http://stackoverflow.com/a/48513600
type: Question
has answer: http://stackoverflow.com/a/48513600
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84021629
tagged with: python

http://stackoverflow.com/comment/84229077
comment on: http://stackoverflow.com/a/48616044
has text: Haha, I'm aware of that. But I don't quite understand it, so I'm gonna avoid it. But thank you!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48531757
type: AcceptedAnswer
has body: The 2d array approach is neater, but here's a way to do it with pandas only: import pandas as pd import glob path = r'.../Model_AMs' allFiles = glob.glob(path + "/*.csv") for file_ in allFiles: # transpose() is here to order values in same way as # numpy's flatten(). astype() shouldn't be necessary, # but useful just in case pandas finds some floating # point values in your data df = pd.read_csv(file_, header=None).astype(int).transpose().melt() # writing in append mode pd.DataFrame(dict(zip(df.index, df.value)), index=[0]).to_csv( 'trainingdata.csv', index=False, header=False, mode='a')
accepted answer of: http://stackoverflow.com/q/48530915
answers question: http://stackoverflow.com/q/48530915
type: Answer
score: 0

http://stackoverflow.com/a/48516561
has body: You may use the variable $BASH_SOURCE to get the name of the current script file. if "$0" == "$BASH_SOURCE" then : "Execute only if started from current script" else : "Execute when included in another script" fi
has comment: http://stackoverflow.com/comment/84086196
downvote count: 0
has comment: http://stackoverflow.com/comment/84092025
score: 7
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48516449
has comment: http://stackoverflow.com/comment/84088556
has comment: http://stackoverflow.com/comment/84092483
answers question: http://stackoverflow.com/q/48516449
type: Answer

http://stackoverflow.com/a/48617760
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48616731
has comment: http://stackoverflow.com/comment/84238639
type: Answer
has body: The key here is Psycopg requires PostgreSQL client library (libpq) >= 9.1 Make sure that the first pg_config on your PATH is from PostgreSQL version 9.1 or higher. From the documentation: Psycopg is a C wrapper around the libpq PostgreSQL client library. To install it from sources you will need: The pg_config program: it is usually installed by the libpq-dev package but sometimes it is not in a PATH directory. Having it in the PATH greatly streamlines the installation, so try running pg_config --version
has comment: http://stackoverflow.com/comment/84241888

http://stackoverflow.com/q/48516016
tagged with: python
has answer: http://stackoverflow.com/a/48516460
linked to: http://stackoverflow.com/q/42622959
answer count: 4
has title: How to use the name of my arrays as filenames?
has comment: http://stackoverflow.com/comment/84026332
tagged with: file-io
upvote count: 3
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/28228324
tagged with: arrays
downvote count: 0
linked to: http://stackoverflow.com/q/28255715
has body: My code is doing some math and saving output in multiple NumPy arrays. At the end, I am writing the output to disk, for which I wish to use the name of the arrays as individual filenames, in which each array will be written. For instance, if I have the following multidimensional arrays time = [...] force = [...] pressure = [...] energy = [...] etc, and I do for array in [time, force, pressure, energy, ....]: with open(**filename**, 'w') as file: pickle.dump(array, file) But how to set the filename, so that it takes on the array names. I have gone through many similar questions (although asked for other motives). The answers have suggested that array(or any variable) names are merely tags and not made to be retrieved like this. But my motive for naming files here seems like a genuine need (to me at least), so asking. If that is possible, I can perhaps go fancier and write in HDF5 format and use the array names as different datasets. All this could be achieved manually though, but then why do we code?
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
score: 3
has comment: http://stackoverflow.com/comment/84026586
has answer: http://stackoverflow.com/a/48516506
has answer: http://stackoverflow.com/a/48516944
has answer: http://stackoverflow.com/a/48516186

http://stackoverflow.com/a/48580719
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84160352
accepted answer of: http://stackoverflow.com/q/48579891
score: 5
answers question: http://stackoverflow.com/q/48579891
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/84158930
has comment: http://stackoverflow.com/comment/84159581
has comment: http://stackoverflow.com/comment/84159249
has comment: http://stackoverflow.com/comment/84159188
has comment: http://stackoverflow.com/comment/84157982
has body: You got the math wrong. When you compute the gradient update for GD you have to divide by the number of samples in your dataset: that's why it is called mean squared error and not just squared error. Also, you might want to use smaller inputs since you're trying to work with an exponential, as it tends to grow... well, exponentially with x. Look at this post for a good intro to LR and GD. I took the liberty of rewriting your code a bit, this should work: import numpy as np import matplotlib.pyplot as plt # Prepare the data input_ = np.linspace(0, 10, 100) # Don't assign user data to Python's input builtin output = np.array([x**2 + 2 for x in input_]) # Define model a = 1 b = 1 # Train model N = input_.shape[0] # Number of samples for e in range(10): loss = 0. for x, y in zip(input_, output): y_hat = a * x + b a = a - 0.1 * (2. / N) * (-x) * (y - y_hat) b = b - 0.1 * (2. / N) * (-1) * (y - y_hat) loss += 0.5 * ((y - y_hat) ** 2) loss /= N print("Epoch {:2d}\tLoss: {:4f}".format(e, loss)) # Predict on test data test_input = np.linspace(0, 15, 150) # Training data [0-10] + test data [10 - 15] test_output = np.array([x**2.0 + 2 for x in test_input]) model_predictions = np.array([a*x + b for x in test_input]) plt.plot(test_input, test_output, 'ro') plt.plot(test_input, model_predictions, '-') plt.show() This should give you as output something along these lines: Epoch 0 Loss: 33.117127 Epoch 1 Loss: 42.949756 Epoch 2 Loss: 40.733332 Epoch 3 Loss: 38.657764 Epoch 4 Loss: 36.774646 Epoch 5 Loss: 35.067299 Epoch 6 Loss: 33.520409 Epoch 7 Loss: 32.119958 Epoch 8 Loss: 30.853112 Epoch 9 Loss: 29.708126 And this is the output plot: Cheers EDIT: OP was asking about SGD. The above answer is still valid code, but it's for standard GD (where you iterate on the whole dataset at the same time). For SGD, the main loop must be slightly changed: for e in range(10): for x, y in zip(input_, output): y_hat = a * x + b loss = 0.5 * ((y - y_hat) ** 2) a = a - 0.01 * (2.) * (-x) * (y - y_hat…

http://stackoverflow.com/a/48551489
has comment: http://stackoverflow.com/comment/84137541
accepted answer of: http://stackoverflow.com/q/48547349
has comment: http://stackoverflow.com/comment/84139923
has comment: http://stackoverflow.com/comment/84137208
has comment: http://stackoverflow.com/comment/84142018
has comment: http://stackoverflow.com/comment/84137421
downvote count: 0
has comment: http://stackoverflow.com/comment/84141543
upvote count: 1
has comment: http://stackoverflow.com/comment/84138661
has comment: http://stackoverflow.com/comment/84191681
answers question: http://stackoverflow.com/q/48547349
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84184581
has comment: http://stackoverflow.com/comment/84141748
has comment: http://stackoverflow.com/comment/84142043
has comment: http://stackoverflow.com/comment/84139317
has comment: http://stackoverflow.com/comment/84136986
has comment: http://stackoverflow.com/comment/84135795
has comment: http://stackoverflow.com/comment/84140068
has comment: http://stackoverflow.com/comment/84139278
has comment: http://stackoverflow.com/comment/84140174
score: 1
has comment: http://stackoverflow.com/comment/84136258
type: Answer
has body: Set WshShell = WScript.CreateObject("WScript.Shell") Set wmic = WshShell.Exec("cmd /c echo hello") Do While wmic.Status = 0 WScript.Sleep 100 Loop Decoded = Replace(wmic.StdOut.ReadAll, vbcrlf, "") Note I use ReadAll rather than looping. This is VBScript which can be pasted into VB6. You can in VB6 use early binding and Dim your objects as Dim x As WshShell after adding a Reference (Project Menu) to Windows Script Host Object Model which is far faster method calls (although you won't notice if doing it once). Python can also use COM objects. Update As you are aware by using app.path you can't guarantee system configuration, and nor should you change the users environment - except to make your program available (ie Start menu). VB6 prorams, except for simple programs, need to be installed on computers. Just because it works on a computer with the VB6 development environment doesn't mean it will work elsewhere without installing. Use the Package and Deployment Wizard on the Addin menu. However the application directory (ie app.path) is only writable by administrators. Programs use AppData directory for files they need to create, write, or read but are not for the user to open. User's data go into Documents, Pictures, Video, Etc. To get these folders you use (there's a lot of functions from different era's of Windows) one of them like https://msdn.microsoft.com/fr-fr/library/0ea7b5xe(v=vs.84).aspx. For the era of software that you are using see Windows 2000 Guide I picked the best three chapters of Application Specification for Microsoft Windows 2000 for Desktop Applications Design Guide for Building Business Applications https://msdn.microsoft.com/en-us/library/ms954115.aspx‎ https://msdn.microsoft.com/en-us/library/ms954375.aspx https://msdn.microsoft.com/en-us/library/bb742580.aspx https://msdn.microsoft.com/en-us/library/ms954371.aspx
has comment: http://stackoverflow.com/comment/84136569
has comment: http://stackoverflow.com/comment/84142254
has comment: http://stackoverflow.com/comment/84138776
has comment: http://stackoverflow.com/comment/84140937

http://stackoverflow.com/q/48542940
has body: This is how text file looks like: 1.0778 0.86111 1.6173 0.94568 3.3376 1.565 1.1927 -0.90241 -1.0183 2.3423 1.0599 1.3005 -2.9829 -1.1132 -0.01103 0.69469 2.9999 1.1401 -0.12478 -0.35958 I want to read to into 10*2 matrix (in this example) (actually my text file is longer)
has answer: http://stackoverflow.com/a/48543145
answer count: 3
has answer: http://stackoverflow.com/a/48544657
downvote count: 1
tagged with: file
has title: How do I read text file of following type in to array/tuple
has comment: http://stackoverflow.com/comment/84081087
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
tagged with: arrays
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48544879
has comment: http://stackoverflow.com/comment/84080902
tagged with: tuples

http://stackoverflow.com/comment/84153570
has text: Part of what makes Python so nice is that there are virtually no special cases. `self.a = ...` works with exactly the same mechanism as `obj.b = ...` does…
comment on: http://stackoverflow.com/q/48578627
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84157333
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48580406
type: Comment
has text: @Basj, itertools creates an iterator so it will not load the memory with the items but compute them as needed

iterable
tags question: http://stackoverflow.com/q/48603998
type: Tag
tags question: http://stackoverflow.com/q/48598276
tag name: iterable

http://stackoverflow.com/comment/84157789
type: Comment
score: 0
has text: The latter two html snippets were copied from the 'view source' page of the resulting page, if that's what you mean? Would there be any other information I can retrieve from the 'view source' page?
type: QuestionComment
comment on: http://stackoverflow.com/q/48572024

http://stackoverflow.com/comment/84243939
type: Comment
has text: Still it's and answer to another problem. Although changing the format of the input from our perspective might be a trivial change, from computer's perspective and algorithmic point of view this is a notable change. After all, this is a clever answer on it's own to a problem like that.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48619647

http://stackoverflow.com/comment/84273255
comment on: http://stackoverflow.com/q/48638398
type: Comment
type: QuestionComment
has text: @mrCarnivore `round(0.5)==0` is by design in most computer languages. https://en.wikipedia.org/wiki/Rounding
score: 3

http://stackoverflow.com/q/48532943
linked to: http://stackoverflow.com/q/22444
tagged with: python
tagged with: regex
duplicate of: http://stackoverflow.com/q/22444
has title: Regex to match string literal enclosed in quotes without matching others
upvote count: 2
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/48533117
downvote count: 1
has body: So I am writing a simple lexer for a subset of the C language in python. I am using re to match and find all my tokens but am having issues with my string literal token matching. To match my string literal I am using: r'(?&lt;=").*(?=") I am doing this non-inclusive because I am wanting to match my double quotes as quote tokens and the content inbetween them as a string literal token. It works fine if a string literal is used only once in a line but if I do "hello" int i "what is up" I end up matching hello correctly but then matching int i because it is inbetween double quotes also. How can I prevent this. Right now all of my input is read in at once into one line. EDIT: I found out my possible issue. I was using a greedy expression with .* I switched it to .*? and it is matching correctly. It started matching as hello" int i "what is up and that is where discovered it was being greedy. My new regex is : r'(?&lt;=").*?(?=") Does anyone see any possible conflicts now?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48533117
tagged with: python-3.x
type: AnsweredQuestion

http://stackoverflow.com/comment/84103538
comment on: http://stackoverflow.com/a/48553496
score: 0
type: Comment
type: AnswerComment
has text: IIUC, you need to use `groupby`. Put it in another question so you have an opportunity to make it very clear what you're asking.

http://stackoverflow.com/comment/84204080
type: AnswerComment
comment on: http://stackoverflow.com/a/48602806
score: 0
type: Comment
has text: I have simulated the case and it works well, maybe can you sharing more information: the answers, crawls, etc

http://stackoverflow.com/q/48602772
accepted answer: http://stackoverflow.com/a/48604893
score: 5
upvote count: 5
tagged with: django
has answer: http://stackoverflow.com/a/48604893
tagged with: python
has title: Django ModelForm with model having ForeignKey field does not display selectBox correctly
possible better answer: http://stackoverflow.com/a/56291420
tagged with: foreign-keys
has body: This is probably easy to solve. I created a form which use forms.ModelForm. My model has ForeignKey field. Form creates a select field for foreignKey, but but does not display value correctly. models.py from django.db import models # Create your models here. class Gender(models.Model): name = models.CharField(max_length=8, null=True) class Meta: db_table='gender' class UserExample(models.Model): name = models.CharField(max_length=16,null=True) age = models.IntegerField(blank=True, null=True) gender = models.ForeignKey('Gender', on_delete=models.SET_NULL, null=True) class Meta: db_table='userExample' def __str__(self): return "" forms.py from django import forms from .models import UserExample, Gender class UserForm(forms.ModelForm): class Meta: model = UserExample fields = ('name', 'age', 'gender') views.py from django.shortcuts import render from .forms import UserForm # Create your views here. def index(request): form = UserForm return render( request, 'index.html', {'form': form} ) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] index.html test {{ form.as_p }} And after I launch my app. In select box I get only selection for gender objects but not for gender names. Optional I used to add values using sqllite3 like this: sqlite> insert into gender values(1,"Male"); sqlite> insert into gender values(2,"Female");
has answer: http://stackoverflow.com/a/61928839
has answer: http://stackoverflow.com/a/56291420
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: forms
favorite count: 0
has comment: http://stackoverflow.com/comment/84202259
type: Question

http://stackoverflow.com/q/48621678
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84243605
has comment: http://stackoverflow.com/comment/84243814
has title: Annotate each result with a value indicating if minimum or maximum of field
has answer: http://stackoverflow.com/a/48727823
has body: I have two models, Author and Book: class Author(models.Model): name = models.CharField(max_length=256) class Book(models.Model): name = models.CharField(max_length=256) price = models.IntegerField() publication_date = models.DateField() author = models.ForeignKey(Author, related_name="books") Now when I get a set of authors and their books, I want to annotate each book with two values indicating if it is the cheapest or most expensive out of the filtered books from the same author. I got the correct results using Exists and annotations filtered_books = Book.objects.filter(publication_date__year=2010) lower_price = filtered_books.only('id').filter(price__lt=OuterRef('price'), author=OuterRef('author')) higher_price = filtered_books.only('id').filter(price__gt=OuterRef('price'), author=OuterRef('author')) filtered_books = filtered_books.annotate( lowest_price=~Exists(lower_price), highest_price=~Exists(higher_price), ) authors = Author.objects.annotate.prefetch_related(Prefetch('books', queryset=filtered_books)) It works but results in three (lower_price, higher_price and the prefetch) very similar subqueries being executed and is not that fast. How can I optimize it?
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84243302
tagged with: query-optimization
tagged with: database
tagged with: django
has comment: http://stackoverflow.com/comment/84246152
tagged with: python
has comment: http://stackoverflow.com/comment/84244105
accepted answer: http://stackoverflow.com/a/48727823
has comment: http://stackoverflow.com/comment/84243134

http://stackoverflow.com/comment/84147606
has text: No part of this calls `iterflattened`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48575516
score: 4

http://stackoverflow.com/q/48640143
has body: While installing Turicreate using pip on my macOS it gave me an error, Could not find a version that satisfies the requirement turicreate (from versions: ) No matching distribution found for turicreate I did the following steps: conda create -n venv python=2.7 anaconda source activate venv pip install -U turicreate pip install --upgrade pip Requirement already up-to-date: pip in ./anaconda/lib/python3.5/site-packages
tagged with: pip
tagged with: python
has title: Cannot Install Apple Turi Create
type: AnsweredQuestion
score: 0
tagged with: anaconda
answer count: 1
accepted answer: http://stackoverflow.com/a/48648071
tagged with: turi-create
tagged with: macos
has answer: http://stackoverflow.com/a/48648071
type: Question

http://stackoverflow.com/a/48491897
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83978152
has comment: http://stackoverflow.com/comment/125693220
score: 14
has comment: http://stackoverflow.com/comment/83977199
accepted answer of: http://stackoverflow.com/q/48491577
has body: To round every number in an expression, use the following function def round_expr(expr, num_digits): return expr.xreplace({n : round(n, num_digits) for n in expr.atoms(Number)}) It can be applied to any SymPy expression, including matrices. x = symbols('x') M = 1/10**6 * Matrix(([1, 10*x, 100], [1000, 10000*x, 100000])) round_expr(M, 3) yields Matrix([ [ 0.0, 0, 0.0], [0.001, 0.01*x, 0.1]]) For numeric matrices, the following is simpler and preserves trailing zeros: &gt;&gt;&gt; M.applyfunc(lambda x: Symbol('{:.3f}'.format(x))) Matrix([ [0.000, 0.000, 0.000], [0.001, 0.010, 0.100]]) Here, applyfunc applies the given function to each entry of M. A natural thing to try would be lambda x: '{:.3f}'.format(x) but SymPy matrices aren't really meant to hold strings: the strings get parsed back into numbers and the trailing zeros get dropped, resulting in Matrix([ [ 0.0, 0.0, 0.0], [0.001, 0.01, 0.1]]) So I wrap each string in Symbol, thus making a new symbol out of it. Symbols can appear in matrices, and they printed as their names, in this case the names are "0.000" and so on.
type: Answer
answers question: http://stackoverflow.com/q/48491577
upvote count: 14
has comment: http://stackoverflow.com/comment/83976989

http://stackoverflow.com/a/48588664
has comment: http://stackoverflow.com/comment/84174637
upvote count: 0
has comment: http://stackoverflow.com/comment/84174762
downvote count: 1
has comment: http://stackoverflow.com/comment/84179391
has body: Download and install this. That should take care of it. Not sure if it matters, but this is the exact string I use 'Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq='
type: Answer
has comment: http://stackoverflow.com/comment/84174956
score: -1
has comment: http://stackoverflow.com/comment/84175286
has comment: http://stackoverflow.com/comment/84174472
answers question: http://stackoverflow.com/q/48587950

http://stackoverflow.com/comment/84273083
comment on: http://stackoverflow.com/q/48638398
type: Comment
score: 0
type: QuestionComment
has text: PS I know that `round(0.5)==0` and `round(1.5)==2`.

http://stackoverflow.com/q/48639185
tagged with: pyqt
downvote count: 0
answer count: 7
tagged with: pyqt5
favorite count: 0
has answer: http://stackoverflow.com/a/70314807
has answer: http://stackoverflow.com/a/68220805
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48641097
has answer: http://stackoverflow.com/a/48641097
has answer: http://stackoverflow.com/a/62403027
tagged with: python
linked to: http://stackoverflow.com/q/33445109
has body: Considering the following code from PyQt5.QtWidgets import QMainWindow, QLabel, QSizePolicy, QApplication from PyQt5.QtGui import QPixmap, QImage from PyQt5.QtCore import Qt import numpy as np import sys class Test(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(10,10,640, 400) pixmap_label = QLabel() pixmap_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) pixmap_label.resize(640,400) pixmap_label.setAlignment(Qt.AlignCenter) im_np = np.ones((1800,2880,3),dtype=uint8) im_np = np.transpose(im_np, (1,0,2)) qimage = QImage(im_np, im_np.shape[1], im_np.shape[0], QImage.Format_RGB888) pixmap = QPixmap(qimage) pixmap = pixmap.scaled(640,400, Qt.KeepAspectRatio) pixmap_label.setPixmap(pixmap) self.setCentralWidget(pixmap_label) self.show() def main(): app = QApplication(sys.argv) win = Test() sys.exit(app.exec_()) if __name__=="__main__": main() I get the following error TypeError: arguments did not match any overloaded call: QImage(): too many arguments QImage(QSize, QImage.Format): argument 1 has unexpected type 'numpy.ndarray' QImage(int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray' QImage(bytes, int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray' QImage(sip.voidptr, int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray' QImage(bytes, int, int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray' QImage(sip.voidptr, int, int, int, QImage.Format): argument 1 has unexpected type 'numpy.ndarray' QImage(List[str]): argument 1 has unexpected type 'numpy.ndarray' QImage(str, format: str = None): argument 1 has unexpected type 'numpy.ndarray' QImage(QImage): argument 1 has unexpected type 'numpy.ndarray' QImage(Any): too many arguments According to this post this can be caused by numpy creating a view. Modifying the lines im_np = np.array(img) im_np = np.transpose(im_np, (1,0,2)) To im_np = np.array(img) im_np = np.transpose(im_np, (1,…
has title: PyQt5 QImage from Numpy Array
possible better answer: http://stackoverflow.com/a/68220805
has answer: http://stackoverflow.com/a/71436366
has answer: http://stackoverflow.com/a/71436334
type: Question
upvote count: 15
tagged with: numpy
tagged with: python-3.x
score: 15
has answer: http://stackoverflow.com/a/50755965

http://stackoverflow.com/q/48600755
answer count: 1
has comment: http://stackoverflow.com/comment/84198156
tagged with: import
favorite count: 0
type: Question
tagged with: neurolab
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84198143
has comment: http://stackoverflow.com/comment/84198548
has answer: http://stackoverflow.com/a/48600965
tagged with: neural-network
tagged with: python
has title: ImportError: No module named neurolab
downvote count: 0
has body: I try to import nuurolab using this code: import neurolab as nl But it gives this error : ModuleNotFoundError: No module named 'neurolab' Then I try to install neurolab using sudo pip3 install neurolab Then this message shows : Requirement already satisfied: neurolab in /usr/local/lib/python3.5/dist-packages How to solve this problem?
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84198243
has comment: http://stackoverflow.com/comment/84198283

http://stackoverflow.com/comment/84125225
comment on: http://stackoverflow.com/a/48562157
has text: Actually, you have a misleading title. It says `<Object id> is not JSON serializable` and then in post `TypeError: <User 145> is not JSON serializable`. You are passing user object to jsonify, but it accepts values like dictionaries. First, you need to convert user obj to a dictionary. Try `return jsonify(name=new_user.name)`
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/48589848
score: 2
accepted answer of: http://stackoverflow.com/q/48588960
upvote count: 2
has comment: http://stackoverflow.com/comment/84176937
has comment: http://stackoverflow.com/comment/84303151
downvote count: 0
has body: Is this what you need ? df=df.replace('',np.nan).ffill() df.assign(DxN=df.groupby('CASE').cumcount()).set_index(['CASE','DxN']).Diagnosis.unstack(fill_value='') Out[709]: DxN 0 1 CASE S1 nodiagnosis S2 fungus squamouslesion S3 fungus S4 squamouslesion glandularlesion
has comment: http://stackoverflow.com/comment/84177006
answers question: http://stackoverflow.com/q/48588960
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84303145
type: Answer

http://stackoverflow.com/a/48598643
answers question: http://stackoverflow.com/q/48598558
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84197435
downvote count: 0
has comment: http://stackoverflow.com/comment/84193816
has body: k += 1 That's where the problem is. Try this code: for k in range(1, 1002): print(k) and then: for k in range(1, 1002): k += 1 print(k)

http://stackoverflow.com/q/48522775
has title: Mapping numeric values to string
accepted answer: http://stackoverflow.com/a/48522887
has body: Here I have a dataset: Dataset I want to map numeric value to CASE_STATUS values df.CASE_STATUS.value_counts() CERTIFIED 2615623 CERTIFIED-WITHDRAWN 202659 DENIED 94346 Here is what I do but have a string indices must be integers, not str error: for dataset in df: dataset['CASE_STATUS'] = dataset['CASE_STATUS'].map( {'CERTIFIED':1 , 'CERTIFIED-WITHDRAWN': 1, 'DENIED': 0} ).astype(int) How should I map values to CASE_STATUS?
has answer: http://stackoverflow.com/a/48522887
tagged with: dataframe
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48522900
score: 1
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48522900
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/48532751
has body: Assuming the objects are collections.namedtuples: from collections import namedtuple Data = namedtuple('Data', ['Id', 'value', 'ratio']) s = [Data(Id=1, value='abc', ratio= 0.1), Data(Id=2, value='def', ratio= 0.3), Data(Id=3, value='ghi', ratio= 0.15), Data(Id=4, value='xyz', ratio= 0.5)] new_s = [(i.Id, i.value, i.ratio) for i in s] Output: [(1, 'abc', 0.1), (2, 'def', 0.3), (3, 'ghi', 0.15), (4, 'xyz', 0.5)]
type: Answer
accepted answer of: http://stackoverflow.com/q/48532721
downvote count: 1
has comment: http://stackoverflow.com/comment/84061491
has comment: http://stackoverflow.com/comment/84061643
has comment: http://stackoverflow.com/comment/84061369
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48532721
score: 1

http://stackoverflow.com/q/48563045
tagged with: class
score: 0
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84124239
has title: Moving points across a screen using PIL
tagged with: python-imaging-library
type: UnansweredQuestion
has body: I wrote a sample code to draw a set of points in a black background. What i would like to do is to take one point and move it along specific set of coordinates. I would also like to calculate the time taken for one point to move from one coordinate to another. I am really stuck with the implementation. Any suggestion will be appreciated? from PIL import Image, ImageDraw, ImageFont, ImageChops from random import randrange import time class ImageHandler(object): # reso_width = 100 reso_height = 100 radius = 5 def __init__(self,width,height,spot_lightradius = 5): self.reso_width = width self.reso_height = height self.radius = spot_lightradius def get_image_spotlight(self,set_points): image,draw = self.get_black_image() for (x,y) in set_points: draw.ellipse((x-self.radius,y-self.radius,x+self.radius,y+self.radius),fill = 'white') image.show("new_image") return image def get_black_image(self): image = Image.new('RGBA',(self.reso_width,self.reso_height),"black") draw = ImageDraw.Draw((image)) return image,draw counter = 1 hi = ImageHandler(1000,1000) points = [(52,700)] img = hi.get_image_spotlight(points) time.sleep(500)
tagged with: python
has answer: http://stackoverflow.com/a/48625892

http://stackoverflow.com/a/48592907
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48592831
type: Answer
accepted answer of: http://stackoverflow.com/q/48592831
has body: There is a way to do this, but it's kind of ugly: lst = iter(lst) # so it wont restart while True: try: for fst, snd in lst: # stuff break # if the loop was successful except: pass
has comment: http://stackoverflow.com/comment/84183156
score: 1

http://stackoverflow.com/comment/84226577
has text: @Sraw I don't think this is applicable to provide multiple answers for, it's _"Why..."_. If it was, however, _"How to ..."_ I'd not have merged my two solutions.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48614584

http://stackoverflow.com/comment/84280340
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48641654
has text: It's most likely because the page didn't reach a complete state within the allowed time. Check the console from the browser, you'll probably see that the browser failed to load a resource.

http://stackoverflow.com/comment/84311791
score: 0
has text: im writing a python script in such a way that when it is executed in a client computer it will give the browser details.how do i do it?
type: QuestionComment
comment on: http://stackoverflow.com/q/48643601
type: Comment

http://stackoverflow.com/q/48496874
has answer: http://stackoverflow.com/a/48497008
answer count: 1
has comment: http://stackoverflow.com/comment/83986700
has body: I am trying to create a new column from an existing one result['details.dealReference'].str.split('-') This returns a list of lists 0 [Gen1, ImfcGKceLY] 1 [Gen2, jxoKLGmLKa] 2 [Gen5, XGbTqEJxVh] 3 [Gen5, UNqZFhLLct] 4 [Gen2, OKybhoAxew] 5 [Gen8, TgmOLWHiDr] Doing something like result['details.dealReference'].str.split('-')[0][0] returns the value I want, but only from the first row. Ideally what I want is result['newColumn'] = result['details.dealReference'].str.split('-')&lt;insert magic here&gt; where the new column contains 0 Gen1 1 Gen2 2 Gen5 3 Gen5 4 Gen2 5 Gen8 How can I achieve this?
has comment: http://stackoverflow.com/comment/83987690
favorite count: 0
type: Question
has title: Create new column in DF from first value of split()
accepted answer: http://stackoverflow.com/a/48497008
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/128926606
comment on: http://stackoverflow.com/a/48725336
type: Comment
score: 0
type: AnswerComment
has text: How could this be updated in order to keep the centres fix and optimise the covariances instead?

http://stackoverflow.com/comment/133111638
comment on: http://stackoverflow.com/a/73642693
score: 0
type: AnswerComment
type: Comment
has text: Okay that makes sense, thanks! However OP was asking about performing the same on AWS env I think.

http://stackoverflow.com/q/48524613
tagged with: django
tagged with: python
has body: I am a newcomer to Django programming. Here I am working on the server side. The thing I want to do is when client-side type a location in a string, the server will response a longitude and latitude using the geocoding API. But the problem is I can't even successfully import 'google maps' or 'django_google_maps' API in the visual studio How can I import them successfully and apply them to my server-side code? Thank you for answering
tagged with: google-maps-api-3
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84044257
tagged with: http://stackoverflow.com/tag/json
has title: Response a json type longitude and latitude using Google geocoding API in django using Python
type: Question
has comment: http://stackoverflow.com/comment/84129522
tagged with: google-maps
type: UnansweredQuestion

http://stackoverflow.com/q/48590180
accepted answer: http://stackoverflow.com/a/48590258
has body: I have a model that needs to include the ID in another field when its created... see below: id = models.AutoField(primary_key=True) ticket_number = models.CharField(max_length=200, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) ... def save(self, *args, **kwargs): shortname = self.brand.shortname super(Job, self).save(*args, **kwargs) self.ticket_number = shortname.upper() + '-' + str(self.id) super(Job, self).save(*args, **kwargs) It works, which is good, and creates a unique ticket number. I'm new to Django, but I know enough that I feel like saving a post twice is inefficient. Is there something like .save(commit=False) for Models? I'd like to only save it once per save.
has answer: http://stackoverflow.com/a/48590258
type: Question
has comment: http://stackoverflow.com/comment/84177540
has answer: http://stackoverflow.com/a/48591069
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48591069
has title: I need to do something like form.save(commit=False) in my model in Django

http://stackoverflow.com/comment/84227351
score: 0
comment on: http://stackoverflow.com/q/48615031
has text: Sorry, just updated with my attempts!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84225715
has text: You have searched through the edited string for the location of '_' , and change that and the next character, so you are working on the edited string. Your iteration isn't really necessary, it just tells you how many underscores there are.
comment on: http://stackoverflow.com/a/48614313
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84057218
has text: Because I was copying from an old file and didn't think. That is a good suggestion.
score: 0
comment on: http://stackoverflow.com/a/48512007
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84260446
comment on: http://stackoverflow.com/a/48535658
score: 0
has text: can you kindly please tell how to save these mfcc's that are generated in the last step : ` required_mfcc = librosa.feature.mfcc(y=required_slice, sr=sr) `
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84105745
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48543248
score: 0
has text: Yes , I did refer to the stackoverflow question you mentioned in the reply before posting this query. We used the `getObject` method to check the details of the disk . For passing the id to this particular method, we used `getBlockDevices` method. And in the query,I have masked few characters of the ID. They are not the actual IDs.

http://stackoverflow.com/q/48511555
has comment: http://stackoverflow.com/comment/84018056
tagged with: split
tagged with: overwrite
type: UnansweredQuestion
has title: Python: create new text file with only last item saved
linked to: http://stackoverflow.com/q/37799078
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48511593
answer count: 1
upvote count: 1
downvote count: 1
has body: I am trying to create a single text file of all items from the last column from a series of other files, separated with new lines (so if I have 4 existing text files, the new file should have 4 rows). The code I have is properly is creating a new file that has all the last items in the last column from a file: with open('originalfile1.txt') as f: lines = [line.strip().split()[-1] for line in f.readlines()] with open('newtextfile.txt', 'w') as f: f.write(' '.join(lines) + '\n' + ' ') Without getting into the for loop to go over the files, just running this manually for the next file: with open('originalfile2.txt') as f: lines = [line.strip().split()[-1] for line in f.readlines()] with open('10_stimtimes.txt', 'w') as f: f.write(' '.join(lines) + '\n' +' ' + '\n' + ' ') ...overwrites the original output. And this: with open('IAPS_id10_run1.txt') as f: lines = [line.strip().split()[-1] for line in f.readlines()] with open('10_stimtimes.txt', 'w') as f: f.write(' '.join(lines) + '\n' + ' '.join(lines)) ...writes the output of the last column from the second file twice and overwrites the output from the first file. What am I doing incorrectly to be able to maintain the output from all files? Thank you!
favorite count: 0
type: Question

http://stackoverflow.com/q/48497566
tagged with: exception
has comment: http://stackoverflow.com/comment/83992646
has comment: http://stackoverflow.com/comment/84023457
answer count: 2
has comment: http://stackoverflow.com/comment/83988925
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83990146
has comment: http://stackoverflow.com/comment/83995701
has comment: http://stackoverflow.com/comment/83993831
has title: 401 Client Error: Unauthorized for url
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/83990675
has comment: http://stackoverflow.com/comment/83988686
has comment: http://stackoverflow.com/comment/113965721
tagged with: http-error
tagged with: soundcloud
has answer: http://stackoverflow.com/a/65822613
has answer: http://stackoverflow.com/a/74000478
downvote count: 0
has comment: http://stackoverflow.com/comment/83990746
favorite count: 0
has body: Recently I started to get requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.soundcloud.com/oauth2/token using soundcloud (0.5.0) Python library. It happens in client = soundcloud.Client(client_id='id', client_secret='secret', username='user@mail.com', password='passwd') I double checked my credentials to make sure they are not the cause. I tried to get a Client instance from different IPs and different machines. At some random times during a day I can get a Client instance, but 99.99% of the day I get the error. Does the error mean I was banned for some reason?
type: Question

http://stackoverflow.com/comment/84082659
has text: @Piinthesky edited
comment on: http://stackoverflow.com/q/48543554
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48579739
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48550250
has body: You need to override get_query and get_query_count methods of your ModelView class. For example: class DataView(ModelView): def get_query(self): current_user_id = get_current_user_id() return self.session.query(self.model).filter(Data.user_id == current_user_id) def get_count_query(self): current_user_id = get_current_user_id() return self.session.query(func.count('*')).select_from(self.model).filter(Data.user_id == current_user_id) ... admin.add_view(UsersView(Users, db.session)) admin.add_view(DataView(Data, db.session)) If you are using something like Flask-Security or Flask-Login it is easy to get the current logged in user.

http://stackoverflow.com/comment/84079020
comment on: http://stackoverflow.com/q/48542005
type: Comment
type: QuestionComment
has text: You're probably trying to decode a string which is already decoded!
score: 0

http://stackoverflow.com/comment/93310986
has text: Good, thanx for clarififcation .. just to ensure
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48512157

http://stackoverflow.com/comment/84036875
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48521072
has text: @Piinthesky this question is not really relevant. The `+` here is a unary operator.

http://stackoverflow.com/comment/84243757
type: AnswerComment
comment on: http://stackoverflow.com/a/48614348
type: Comment
has text: Have also a look at the [examples](https://github.com/bokeh/bokeh/tree/master/examples/howto/server_embed), this one and others
score: 0

http://stackoverflow.com/comment/83990866
type: QuestionComment
has text: paste `urls.py` file as well for both `mysite` as well as for `polls`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48497115

http://stackoverflow.com/a/48643721
score: 1
upvote count: 1
has body: You are re-using x and y at the end, but only replacing indices up to 100. So do this at the end and it works: for i in range(10000): # Or use xrange in Python 2.7 y[i] = MLf(x[i], 1) plt.plot(x,y) plt.show() Or make different arrays for this part.
has comment: http://stackoverflow.com/comment/84284064
answers question: http://stackoverflow.com/q/48643475
type: Answer
has comment: http://stackoverflow.com/comment/84284401
accepted answer of: http://stackoverflow.com/q/48643475
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84343542
has text: Ok! This did work to an extent. I followed the get with just `print(response.text)`. I started a hello world flask app on port 5000, and I got the "hello world." However, when I made a get request to a jupyter notebook running on port 8888, I get the page malformed. I compared the source to what I get from a direct call, and the source is identical. So I may need to start a new issue to find out what is not working.
comment on: http://stackoverflow.com/a/48635553
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48490437
tagged with: python
has answer: http://stackoverflow.com/a/48502686
type: AnsweredQuestion
has body: Found here (stackoverflow) a way to handle a file selection on local host. I'm using Autoit and run a local script which writes in the file path. But how can I run this on the remote node, when I'm using selenium hub. Is there a way run on a remote node a command line (windows) process ? Prefer Python example. Thank you!
downvote count: 3
tagged with: selenium
tagged with: file-upload
tagged with: webdriver
favorite count: 0
type: Question
has title: How to upload a file with selenium on remote node [Python]
upvote count: 0
accepted answer: http://stackoverflow.com/a/48502686
score: -3
answer count: 1

http://stackoverflow.com/comment/84121518
comment on: http://stackoverflow.com/a/48562720
type: AnswerComment
has text: http://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations I following this. I did not need to save projectsPermissionSerializer to the database. I will just run it in for loop inside the create function.
type: Comment
score: 0

http://stackoverflow.com/q/48594308
tagged with: python
has comment: http://stackoverflow.com/comment/84185823
favorite count: 0
type: Question
has title: Python 3-x: Nested list in a for loop - how to get a "horizontal" output
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84185977
possible better answer: http://stackoverflow.com/a/48594701
accepted answer: http://stackoverflow.com/a/48594521
has answer: http://stackoverflow.com/a/48594439
has body: for i, j in cards: # cards = a list containing list of cards - RANDOM OUTPUTS, more pairs can be added to the list depending on the number that the user puts in print(i) print(j) print("\t") How do I make it so that the output becomes: TS 6S JS AH 5S AS Instead of: TS AH 6S 5S JS AS I posted a question similar to this but I wasn't being specific enough, and I edited too late. Apologies in advance EDIT - 'cards' code: deck = deck_create() def deal_cards(deck, num_players): cards= [] for i in range(num_players): hands.append([deck.pop(), deck.pop()]) return hands
downvote count: 0
has answer: http://stackoverflow.com/a/48594701
has answer: http://stackoverflow.com/a/48594521
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84185842
score: 3
has comment: http://stackoverflow.com/comment/84186123
answer count: 3
upvote count: 3

http://stackoverflow.com/q/48499713
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48566384
tagged with: pyqt5
has answer: http://stackoverflow.com/a/48566384
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84130306
has comment: http://stackoverflow.com/comment/84009315
tagged with: sockets
has comment: http://stackoverflow.com/comment/83993802
has comment: http://stackoverflow.com/comment/84009091
tagged with: python
type: AnsweredQuestion
score: 2
has title: Server-client connection in PyQt
upvote count: 2
tagged with: pyqt
has body: I would like to write a simpe program that can handle a server-client connection (1:1 connection is enough) in PyQt. I was able to write the socket part but with the GUI I have no idea. I just want to have 2 dialogs one for the server and one for the client(very simple, only 1 button for sending and a textfield to type the message). I want to send a message from the server to the client and then reply to server with another message. Do you have any idea how to begin? Or maybe a sample code? Thank you Code: The GUI was created by the Desginer. from PyQt5 import QtCore, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(353, 266) self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(20, 30, 47, 13)) self.label.setObjectName("label") self.pushButton = QtWidgets.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(80, 110, 75, 23)) self.pushButton.setObjectName("pushButton") self.textEdit = QtWidgets.QTextEdit(Dialog) self.textEdit.setGeometry(QtCore.QRect(80, 20, 141, 71)) self.textEdit.setObjectName("textEdit") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.label.setText(_translate("Dialog", "Message:")) self.pushButton.setText(_translate("Dialog", "Send")) This the Dialog class: class Dialog(QDialog, Ui_Dialog): def __init__(self,socket): super(Dialog, self).__init__() self.setupUi(self) self.socket = socket def send(self): message = self.textEdit.toPlainText() self.socket.send(message.encode()) Server class: class Server(): def __init__(self): host = socket.gethostname() port = 5000 server_socket = socket.socket() server_socket.bind((host, port)) server_socket.listen(2) conn, address = server_socket.accept() print("Connection from: " + str(address)) gui = Dialog(server_socket) gui.show() while True: data = conn.recv(1024)…

http://stackoverflow.com/q/48504316
answer count: 4
has answer: http://stackoverflow.com/a/48504468
accepted answer: http://stackoverflow.com/a/48504468
tagged with: split
tagged with: bash
has answer: http://stackoverflow.com/a/48504711
score: 5
downvote count: 0
has title: Regex or split in python for shell awk equivalent
has comment: http://stackoverflow.com/comment/84006806
has answer: http://stackoverflow.com/a/48504421
possible better answer: http://stackoverflow.com/a/48504421
has answer: http://stackoverflow.com/a/48504568
tagged with: awk
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 5
has body: I've a agent version file that I need to parse to get the application version details. The (example) contents of version file /opt/app_folder/agent_version.txt is as below: Version: 10.2.4.110 Pkg name: XXXX-10.2.4-Agent-Linux-x86_64 Revision: 110 Patch version: 23 I need the output as 1st 3 numbers from Version and the number from Release version. For e.g.: Current Version: 10.2.4.23 So, I've used the below to achieve this in shell using awk FILE=/opt/app_folder/agent_version.txt my_ver=`awk -F[:.] '/Version/ {gsub(" ",""); print $2"."$3"."$4}' ${FILE}` OR my_ver=`awk -F[-] '/Pkg/ {print $2}' ${FILE}` my_patch=`awk -F[:.] '/version/ {gsub(" ",""); print $NF}' ${FILE}` my_cur_ver="$my_ver.$my_patch" echo $my_cur_ver 10.2.4.23 How do I achieve this result in Python? Use regex or split or a combination of both? I'm using Python 3.3 on RHEL 6.2 x86_64
has comment: http://stackoverflow.com/comment/84003123
tagged with: python
has comment: http://stackoverflow.com/comment/84084869
tagged with: regex

http://stackoverflow.com/comment/84139345
type: Comment
has text: I'll edit the question. But for the later part, I have a total of 1 million roads out of which I want to identify the ones that are present in a given address string. there can be no roads, 1 road or maybe 2 roads, completely depends on the input address
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48570724

http://stackoverflow.com/comment/84037335
type: AnswerComment
comment on: http://stackoverflow.com/a/48519054
has text: Thanks, I will get back to you after training the model with different filters
type: Comment
score: 0

http://stackoverflow.com/a/48573180
has body: You can use this, and adapt the repeat value: from itertools import product values = [x*.1 for x in range(1, 10)] for X in product(values, repeat=3): print(['%.1f' % x for x in X]) # ['0.1', '0.1', '0.1'] # ['0.1', '0.1', '0.2'] # ['0.1', '0.1', '0.3'] # ['0.1', '0.1', '0.4'] # # ['0.1', '0.9', '0.9'] # ['0.2', '0.1', '0.1'] # ['0.2', '0.1', '0.2'] # ['0.2', '0.1', '0.3'] # # ['0.9', '0.9', '0.7'] # ['0.9', '0.9', '0.8'] # ['0.9', '0.9', '0.9']
answers question: http://stackoverflow.com/q/48573004
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84166098
type: Answer

phantomjs
tags question: http://stackoverflow.com/q/48555250
tags question: http://stackoverflow.com/q/48616051
type: Tag
tags question: http://stackoverflow.com/q/48617624
tag name: phantomjs

http://stackoverflow.com/q/48591394
tagged with: docker
score: 0
has comment: http://stackoverflow.com/comment/84185197
answer count: 0
has title: Simultaneous requests with uWSGI / Nginx
tagged with: flask
has body: My flask server responds to requests one at a time. Is it possible to make it respond to e.g. 8 requests at a time? For reference, my configuration is below: app.ini for uWSGI [uwsgi] plugins = python3 chdir = /app module = app:app uid = nginx gid = nginx socket = /run/uwsgiApp.sock pidfile = /run/.pid processes = 4 threads = 2 enable-threads = true nginx.conf for nginx user nginx; worker_processes 8; pid /run/nginx.pid; error_log /dev/stdout info; events { worker_connections 20000; } worker_rlimit_nofile 40000; http { include mime.types; sendfile on; keepalive_timeout 65; gzip off; server { listen 80; server_name example.com; location / { try_files $uri @flaskApp; } location @flaskApp { include uwsgi_params; uwsgi_pass unix:/run/uwsgiApp.sock; } } } entrypoint.sh for Docker container #!/bin/bash echo "Running app in production mode!" nginx &amp;&amp; uwsgi --ini /app.ini --master Dockerfile FROM alpine:edge RUN cat /etc/apk/repositories RUN echo "http://nl.alpinelinux.org/alpine/edge/testing" &gt;&gt; /etc/apk/repositories RUN echo "ipv6" &gt;&gt; /etc/modules RUN apk update # basic flask environment RUN apk add --no-cache bash git nginx uwsgi uwsgi-python3 \ &amp;&amp; pip3 install --upgrade pip \ &amp;&amp; pip3 install flask # For uWSGI RUN apk add linux-headers # expose web server ports EXPOSE 80 # application folder ENV APP_DIR /app # app dir RUN mkdir ${APP_DIR} \ &amp;&amp; chown -R nginx:nginx ${APP_DIR} \ &amp;&amp; chmod 777 /run/ -R \ &amp;&amp; chmod 777 /root/ -R VOLUME ${APP_DIR} WORKDIR ${APP_DIR} # copy config files into filesystem COPY nginx.conf /etc/nginx/nginx.conf COPY app.ini /app.ini COPY entrypoint.sh /entrypoint.sh # execute start up script ENTRYPOINT ["/entrypoint.sh"] app.py for Flask from flask import Flask app = Flask(__name__) app.config['DEBUG'] = False @app.route('/test') def test(): return 'hello world'
tagged with: uwsgi
type: Question
has comment: http://stackoverflow.com/comment/84181862
tagged with: nginx
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84182037
tagged with: python
has comment: http://stackoverflow.com/comment/84182005

http://stackoverflow.com/a/48522003
has comment: http://stackoverflow.com/comment/84038551
has body: Did you try saving the notebook in the same directory where the CSV file exists and use a relative path to import the CSV? data/titatic.csv or titatic.csv
score: 0
answers question: http://stackoverflow.com/q/48521458
type: Answer
has comment: http://stackoverflow.com/comment/84039856

http://stackoverflow.com/q/48591157
accepted answer: http://stackoverflow.com/a/48593154
tagged with: pandas
tagged with: join
tagged with: pivot
has answer: http://stackoverflow.com/a/48593154
answer count: 1
downvote count: 0
has title: Combine pandas pivot table multi-index headers - one timestamp, one string
favorite count: 0
type: AnsweredQuestion
has body: I have a pandas dataframe like so: weatherdate publishdate weathernode value 384 2018-01-30 2018-01-30 CYWG -11.67 385 2018-01-31 2018-01-30 CYWG -15.56 432 2018-01-30 2018-01-30 CYYZ -8.33 433 2018-01-31 2018-01-30 CYYZ -5.00 512 2018-01-31 2018-01-31 CYWG -17.22 560 2018-01-31 2018-01-31 CYYZ -6.67 Both date columns are of datetime64 format. I convert df to a pivot table like so: dffcst = pd.pivot_table(df, index='weatherdate', columns=['weathernode','publishdate'], values='value') And get an output like so: weathernode CYWG CYYZ publishdate 2018-01-30 2018-01-31 2018-01-30 2018-01-31 weatherdate 2018-01-30 -11.67 NaN -8.33 NaN 2018-01-31 -15.56 -17.22 -5.00 -6.67 I would like to combine the two rows of column names above, to get an output like the following which I built in excel (note the format below is the best case scenario - remove the dashes between year/month/day, no spaces between date and airport code): weatherdate CYWG20180130 CYWG20180131 CYYZ20180130 CYYZ20180131 1/30/2018 -11.67 NaN -8.33 NaN 1/31/2018 -15.56 -17.22 -5 -6.67 I've tried to join them like so: dffcst.columns = [''.join(col) for col in dffcst.columns] But I get the following error: TypeError: sequence item 1: expected str instance, Timestamp found So pandas is having trouble joining the date in the first row of column names to the string in the second row of column names. I've tried the following code: dffcst.columns = [''.join(str(col)) for col in dffcst.columns] It works, but the new column headers are two unwieldy for me to use, so I need an alternative solution, like what I built in Excel above. This is an example of the unwieldy column header: ('CYWG', Timestamp('2018-01-30 00:00:00')) The goal is to export this table to a csv which would be pulled into an excel model. I could look up the excel model with an offset match so I can lookup various weather stations, on various different forecast dates. Happy to hear anyones thoughts on that idea as well.
tagged with: python
score: 4
tagged with: multi-index
type: Question
upvote count: 4

http://stackoverflow.com/comment/84185525
comment on: http://stackoverflow.com/q/48594086
type: QuestionComment
has text: Read [this](https://stackoverflow.com/q/5202648/5267751) and [this](https://stackoverflow.com/questions/6048085/writing-unicode-text-to-a-text-file).
score: 0
type: Comment

http://stackoverflow.com/q/48518011
answer count: 2
has title: Display a list of web pages for prolonged period using Python - Selenium
has answer: http://stackoverflow.com/a/48524685
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48518876
linked to: http://stackoverflow.com/q/48389938
favorite count: 0
tagged with: internet-explorer
downvote count: 1
tagged with: selenium
score: -1
has body: I have a set of url's in an xml file. I'm planning to write a python program which will read each url and navigate to that web page and wait for a fixed time (eg. 30 sec) and then navigate to next url. The program will have to run for a very long time (say for 2 months and more). from selenium import webdriver driver = webdriver.Ie("e:\\IEDriver\\IEDriverServer.exe") for url in url_list: driver.get(url) So using the above, are there any chances of program getting crashed while running for such prolonged period due to some reason unknown to me? Also any checks I need to do within the program like, memory usage, space usage etc. that will prevent the program from crashing. If there are better ways to do this, please help me. Thanks in advance
type: Question
upvote count: 0

http://stackoverflow.com/a/48623362
accepted answer of: http://stackoverflow.com/q/48622746
type: Answer
has body: I can reproduce your issue. Use time.localtime, not time.gmtime: time.localtime(time.mktime(tmp))
answers question: http://stackoverflow.com/q/48622746
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/84233533
comment on: http://stackoverflow.com/q/48618015
has text: In addition to the comment made by @rahnema1, it also depends on different languages ultimately due to the way the code eventually gets translated into machine code. This website can provide more insight: https://0.30000000000000004.com
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84100186
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48533596
has text: I was missing the 'branches' part of that query. My google-fu failed me. pyplot.countour seems like a much better way of doing all this than how I went about it

http://stackoverflow.com/q/48516776
linked to: http://stackoverflow.com/q/20974640
has comment: http://stackoverflow.com/comment/84028013
has comment: http://stackoverflow.com/comment/84028487
tagged with: python
has body: This code looks like it should be invalid, but python 2.7 seems to accept it as valid: sf[(sf['id'] &gt;= 1) &amp; (sf['id'] &lt;= 2)] where sf is an SFrame object, and sf['id'] refers to a column of the SFrame. This operation results in an SFrame containing only rows for which the expression in the square brackets is true. Note: I am asking for a python feature, such as a 'list comprehension', 'generator', etc. rather than a feature of SFrame. This line of code is used an example in the documentation for graphlab.SFrame in the section titled Logical Filters.
has comment: http://stackoverflow.com/comment/84028058
has answer: http://stackoverflow.com/a/48516994
possible better answer: http://stackoverflow.com/a/48516994
type: Question
answer count: 2
upvote count: 2
has title: What feature of python makes this expression, with square brackets containing a boolean expression as if it were an index or key, valid?
downvote count: 0
has answer: http://stackoverflow.com/a/48517359
accepted answer: http://stackoverflow.com/a/48517359
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/84027988
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/q/48612987
favorite count: 0
type: Question
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48619114
has title: Cannot improve accuracy of AlexNet on Oxford-102 (Tensorflow)
downvote count: 0
tagged with: machine-learning
score: 1
upvote count: 1
answer count: 1
has body: Hi I tried to implement AlexNet without using pretrained weights. I tried to train the net on Oxford-102 dataset, but I keep getting 0.9% accuracy throughout the process and changing the parameters are not helping, below the code can someone help me out? I was following this tutorial I switched the given test set (which is larger) to use as training set, and given training to use as testing set. I used Gradient Descent as the optimizer. I constructed pretty much the same AlexNet as the given article did, might be something wrong with the way I calculate the accuracy? Below is the way I load data import os import sys import warnings import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline from skimage.io import imread from skimage.transform import resize from scipy.io import loadmat import tensorflow as tf warnings.filterwarnings('ignore', category=UserWarning, module='skimage') set_ids = loadmat('setid.mat') set_ids test_ids = set_ids['trnid'].tolist()[0] train_ids = set_ids['tstid'].tolist()[0] def indexes_processing(int_list): returned_list = [] for index, element in enumerate(int_list): returned_list.append(str(element)) for index, element in enumerate(returned_list): if int(element) &lt; 10: returned_list[index] = '0000' + element elif int(element) &lt; 100: returned_list[index] = '000' + element elif int(element) &lt; 1000: returned_list[index] = '00' + element else: returned_list[index] = '0' + element return returned_list raw_train_ids = indexes_processing(train_ids) raw_test_ids = indexes_processing(test_ids) train_images = [] test_images = [] train_labels = [] test_labels = [] image_labels = (loadmat('imagelabels.mat')['labels'] - 1).tolist()[0] labels = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'english marigold', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle', 'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'pur…
tagged with: tensorflow

http://stackoverflow.com/q/48567851
type: UnansweredQuestion
has title: How to configure Ipython to automatically revert back to the directory it was opened in after running a script, even if the script errors out
tagged with: python
tagged with: ipython
has comment: http://stackoverflow.com/comment/84132025
has comment: http://stackoverflow.com/comment/84131932
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/299446
tagged with: jupyter
type: Question
has comment: http://stackoverflow.com/comment/84132673
tagged with: qtconsole
has body: End goal: After running a script regardless of ending perfectly or erroring out, I would like to have my ipython environment revert back to the directory it was in before running the script. I have successfully used the advice given in the SO post, how-do-i-change-directory-back-to-my-original-working-directory-with-python. This works great if the script runs without failing. Ideas: 1) I have considered wrapping my code in one large try: and except: utilizing the advice in the post mentioned above. As this would surely handle the issue. However, it seems tedious and unnecessary to have to write this into all my scripts. 2) I was thinking a good a solution would be to have ipython automatically run a "revert directory" script after every user ran script, that would change the directory back to the original one. I have looked around a bit to see how one would configure ipython to run a script automatically after every run. From my search so far I have not found this to be an option. I was expecting to find a method to accomplish this through the ipython config file. 3) Another solution that would be easy would be to somehow use the information found by using the line magic command %dhist. As the first result given by this command is the original directory that ipython was opened in. However, other than having the results print from executing the command %dhist... I am not sure how to work with the printed information. 4) I must be not searching the right terms, as I feel like this is probably something that is possible or has been asked. If indeed someone has asked this, please point me in the right direction and I will remove this question promptly. Relevant information: Working on os x Using Jupyter QtConsole 4.3.1 IPython 6.2.1

http://stackoverflow.com/a/48561854
score: 2
accepted answer of: http://stackoverflow.com/q/48559319
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48559319
downvote count: 1
type: Answer
has body: You've tagged this as flask-sqlalchemy, so it is safe to say that models.Users.query is using the default scoped session db.session to fetch those entities. You then try and commit in another session, but all the changes you've performed are actually held by db.session. So the fix is simple: import db from where you have it and instead of s.commit(): db.session.commit() But: such a simple operation could be performed as a bulk update to begin with: models.Users.query.\ filter(models.Users.id.in_(ids_to_update)).\ update({models.Users.group: 'design_team'}, synchronize_session=False) # Use the correct session db.session.commit() In order to use db outside a request you might need a suitable context.

http://stackoverflow.com/q/48502828
tagged with: scipy
type: Question
type: UnansweredQuestion
answer count: 1
has title: Scipy constrained minimization does not respect constraint
score: 0
has answer: http://stackoverflow.com/a/48503183
has comment: http://stackoverflow.com/comment/83999496
tagged with: python
has body: I apologize if the question seems straightforward and easy. I tried to look for an answer, but did not find one that could solve my problem. I have a very simple minimization problem: I need to maximize an expected value (in a second phase the objective function will become more complicated): def EV(q, P): return (-1)*np.sum(100 * q * (2*P - 1)) q is a 12 dimensional vector whose elements need to be between 0 and 1 and, clearly, the sum of the elements of q is 1. So I proceed to set the bounds and constraints: cons = {'type': 'eq', 'fun': lambda q: np.sum(q) - 1} bds = [(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)] P = array([ 0.32510069, 0.96284943, 0.33966465, 0.61696874, 0.77368336, 0.10127222, 0.47836665, 0.87537657, 0.2086234 , 0.52468426, 0.31931169, 0.86424427]). Then I call scipy.optimize.minimize: X0 = np.array([0.5,0,0,0,0,0,0,0,0,0,0.4,0]) qstar = scipy.optimize.minimize(fun = EV, x0 = X0, args = (P), method = 'L-BFGS-B', bounds = bds, constraints = cons). However, when I print the solution qstar I get the following: fun: -323.56132559388169 hess_inv: &lt;12x12 LbfgsInvHessProduct with dtype=float64&gt; jac: array([ 34.97985972, -92.56988847, 32.06706651, -23.39374987, -54.7366767 , 79.74555274, 4.32666525, -75.0753145 , 58.27532163, -4.93685093, 36.13766353, -72.84884873]) message: 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_&lt;=_PGTOL' nfev: 26 nit: 1 status: 0 success: True x: array([ 0., 1., 0., 1., 1., 0., 0., 1., 0., 1., 0., 1.]) Why isn't the solution satisfying the equality constraint? Is it, perhaps, because of the message? Any help is very much appreciated.
tagged with: minimize

http://stackoverflow.com/a/48561988
has body: You can extend your regex so that it also matches up to 30 words before and after the pattern: pattern = r'(?:\w+\W+){,30}\b' + \ r' (?:\w+ )?(?:\w+ )?'.join(my_words_markers) + \ r'\b(?:\W+\w+){,30}' Then loop over all sentences, and if the regex matches, use match.start() and match.end() to check if you have to insert an ellipsis ...: for sentence in sentences: match = re.search(pattern, sentence) if match: text = '{}{}{}'.format('...' if match.start() &gt; 0 else '', match.group(), '...' if match.end() &lt; len(sentence) else '') print(text)
has comment: http://stackoverflow.com/comment/84124698
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48561729
has comment: http://stackoverflow.com/comment/84124798
score: 1
type: Answer

http://stackoverflow.com/comment/84246700
type: QuestionComment
score: 0
has text: yes. They call FTS3 extension.. check this resources.. https://stackoverflow.com/questions/35020797/how-to-use-full-text-search-in-sqlite3-database-in-django, http://www.rkblog.rk.edu.pl/w/p/fulltext-search-sqlite-and-django-app/
comment on: http://stackoverflow.com/q/48622050
type: Comment

http://stackoverflow.com/a/48539792
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/48527645
score: 4
has body: SonarPython failed to execute the "pylint" process. You should try to locate "pylint" executable, e.g.: &gt; which pylint /usr/local/bin/pylint Then provide explicitly the pylint path to SonarPython using the sonar.python.pylint property, e.g.: sonar.python.pylint=/usr/local/bin/pylint Documentation: Pylint Report If with 'sonar.python.pylint' property, SonarPython still cannot start pylint. Then you can run pylint yourself before SonarScanner, and provide the pylint result path to SonarPython using the sonar.python.pylint.reportPath property, e.g.: sonar.python.pylint.reportPath=pylint-reports/pylint-result-*.txt
has comment: http://stackoverflow.com/comment/100923495

http://stackoverflow.com/comment/84090662
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to drop a list of rows from Pandas dataframe?](https://stackoverflow.com/questions/14661701/how-to-drop-a-list-of-rows-from-pandas-dataframe)
comment on: http://stackoverflow.com/q/48547406

http://stackoverflow.com/comment/90933842
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48613534
type: Comment
has text: @BallpointBen I suppose it would spuriously assign a 1 to the last row in the group.

http://stackoverflow.com/comment/83999608
type: QuestionComment
score: 0
has text: KNN also scales bad for high-dimensions. Look up KD-trees (or Ball-trees). To be honest: i think all image-search approaches scale-down those images before doing anything. E.g. 100x100. Also: many approaches just do grayscale.
comment on: http://stackoverflow.com/q/48502667
type: Comment

http://stackoverflow.com/q/48542243
has answer: http://stackoverflow.com/a/48542300
favorite count: 0
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84079538
accepted answer: http://stackoverflow.com/a/48542300
tagged with: python
tagged with: ipython
type: Question
has title: Import Error: No module named arch
has body: I am facing this error in iPython notebook even after installing running pip install arch command and successfully installing it. Any help would be highly appreciated.
answer count: 1
downvote count: 0
tagged with: arch
upvote count: 1

http://stackoverflow.com/comment/84056602
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48530306
has text: Step 1: avoid `git pull`, it's a bad tool. Step 2: read up on `git fetch` and try `git fetch origin`. Step 3: read up on `git merge` and consider whether you want `git merge origin/master`, or some other command (not merge at all?) or some other thing to merge (not `origin/master` perhaps). All `git pull` does is make you do steps 2 and 3 together, which makes it too hard and painful.
score: 0

deep-learning
tags question: http://stackoverflow.com/q/48558677
tags question: http://stackoverflow.com/q/48555290
tags question: http://stackoverflow.com/q/48639348
tags question: http://stackoverflow.com/q/48614675
tags question: http://stackoverflow.com/q/48549101
tags question: http://stackoverflow.com/q/48534517
tags question: http://stackoverflow.com/q/48615037
tags question: http://stackoverflow.com/q/48520103
tags question: http://stackoverflow.com/q/48603371
tags question: http://stackoverflow.com/q/48610981
tags question: http://stackoverflow.com/q/48490280
tags question: http://stackoverflow.com/q/48492164
tags question: http://stackoverflow.com/q/48600374
tags question: http://stackoverflow.com/q/48529169
tags question: http://stackoverflow.com/q/48538404
tags question: http://stackoverflow.com/q/48542473
type: Tag
tags question: http://stackoverflow.com/q/48504543
tags question: http://stackoverflow.com/q/48577014
tags question: http://stackoverflow.com/q/48498920
tags question: http://stackoverflow.com/q/48608501
tags question: http://stackoverflow.com/q/48529625
tags question: http://stackoverflow.com/q/48505759
tags question: http://stackoverflow.com/q/48617167
tags question: http://stackoverflow.com/q/48547660
tags question: http://stackoverflow.com/q/48583421
tags question: http://stackoverflow.com/q/48489538
tags question: http://stackoverflow.com/q/48544188
tags question: http://stackoverflow.com/q/48618525
tags question: http://stackoverflow.com/q/48541336
tags question: http://stackoverflow.com/q/48531039
tags question: http://stackoverflow.com/q/48543155
tags question: http://stackoverflow.com/q/48617771
tags question: http://stackoverflow.com/q/48616893
tags question: http://stackoverflow.com/q/48527808
tags question: http://stackoverflow.com/q/48587696
tags question: http://stackoverflow.com/q/48502854
tags question: http://stackoverflow.com/q/48509253
tags question: http://stackoverflow.com/q/48621559
tags question: http://stackoverflow.com/q/48600929
tags question: http://stackoverflow.com/q/48588507
tags question: http://stackoverflow.com/q/48579079
tags question: http://stackoverflow.com/q/48611376
tags question: http://stackoverflow.com/q/48545477
tag name: deep-learning
tags question: http://stackoverflow.com/q/48550159
tags question: http://stackoverflow.com/q/48560227
tags question: http://stackoverflow.com/q/48608585
tags question: http://stackoverflow.com/q/48494087
tags question: http://stackoverflow.com/q/48634151
tags question: http://stackoverflow.com/q/48628041
tags question: http://stackoverflow.com/q/48534636
tags question: http://stackoverflow.com/q/48586429
tags question: http://stackoverflow.com/q/48638760
tags question: http://stackoverflow.com/q/48516113
tags question: http://stackoverflow.com/q/48582311
tags question: http://stackoverflow.com/q/48558915
tags question: http://stackoverflow.com/q/48594627
tags question: http://stackoverflow.com/q/48574173
tags question: http://stackoverflow.com/q/48541652
tags question: http://stackoverflow.com/q/48519317

http://stackoverflow.com/q/48601743
answer count: 1
has comment: http://stackoverflow.com/comment/84248657
type: Question
tagged with: python
tagged with: pygame
tagged with: pygame-surface
linked to: http://stackoverflow.com/q/14177744
tagged with: python-3.x
has body: I started work on my own version of Super Mario Kart in python, just as a small project for myself. So far I've managed to transform an image to look like the player is moving over a pseudo-3D track. However, there is no perspective at all, which somewhat ruins the illusion of 3D. I know that I could pretty much fix this issue if I had a way of skewing the image so that the bottom of the surface is wider than the top, as this would help to simulate perspective. I've been looking for quite a while online to see if there is a way to achieve this, as I really have no idea where to start. Although my searches have been inconclusive, and I have not found anything useful. So how would I go about doing this to skew the image of the track? Here is my code so far: import os, sys, pygame from pygame.locals import * from math import * pygame.init() path, file_name = os.path.split(__file__) path = os.path.join(path, 'data') WIDTH = 800 HEIGHT = 600 SCREEN = pygame.display.set_mode((WIDTH,HEIGHT)) CLOCK = pygame.time.Clock() FPS = 30 pygame.mouse.set_visible(False) pygame.display.set_caption('Mario Kart') class Driver(object): def __init__(self, image, start_pos): self.surface = pygame.image.load(os.path.join(path, image)).convert() self.surface.set_colorkey(MAGENTA) self.surface = pygame.transform.scale(self.surface, (64, 64)) self.pos = list(start_pos) self.angle = 0 self.velocity = 0 def move(self): keys = pygame.key.get_pressed() if keys[K_a] or keys[K_LEFT]: self.angle -= 14 / (1 + e ** (-0.3 * self.velocity)) - 7 #Sigmoid function to contain the angular velocity between 7 and -7 if keys[K_d] or keys[K_RIGHT]: self.angle += 14 / (1 + e ** (-0.3 * self.velocity)) - 7 if keys[K_w] or keys[K_UP]: self.velocity += 3 elif keys[K_s] or keys[K_DOWN]: self.velocity -= 1 self.velocity *= 0.85 self.pos[0] += self.velocity * sin(radians(self.angle)) self.pos[1] -= self.velocity * cos(radians(self.angle)) def render(self): SCREEN.blit(self.surface, (WIDTH / 2 - 32, HEIGHT / 2 - 32)) cl…
score: 0
has title: How to skew an image
has answer: http://stackoverflow.com/a/48604418
type: UnansweredQuestion

machine-learning
tags question: http://stackoverflow.com/q/48623439
type: Tag
tags question: http://stackoverflow.com/q/48510741
tags question: http://stackoverflow.com/q/48609276
tags question: http://stackoverflow.com/q/48620057
tags question: http://stackoverflow.com/q/48608501
tags question: http://stackoverflow.com/q/48593029
tags question: http://stackoverflow.com/q/48552149
tags question: http://stackoverflow.com/q/48628870
tags question: http://stackoverflow.com/q/48493936
tags question: http://stackoverflow.com/q/48604004
tags question: http://stackoverflow.com/q/48522775
tags question: http://stackoverflow.com/q/48617247
tags question: http://stackoverflow.com/q/48558155
tags question: http://stackoverflow.com/q/48627182
tags question: http://stackoverflow.com/q/48507546
tags question: http://stackoverflow.com/q/48639129
tags question: http://stackoverflow.com/q/48574173
tags question: http://stackoverflow.com/q/48497092
tags question: http://stackoverflow.com/q/48583421
tags question: http://stackoverflow.com/q/48528933
tags question: http://stackoverflow.com/q/48567861
tags question: http://stackoverflow.com/q/48571080
tags question: http://stackoverflow.com/q/48618525
tags question: http://stackoverflow.com/q/48495372
tags question: http://stackoverflow.com/q/48535287
tags question: http://stackoverflow.com/q/48570021
tags question: http://stackoverflow.com/q/48621833
tags question: http://stackoverflow.com/q/48643395
tags question: http://stackoverflow.com/q/48543155
tags question: http://stackoverflow.com/q/48581155
tags question: http://stackoverflow.com/q/48547931
tags question: http://stackoverflow.com/q/48587696
tags question: http://stackoverflow.com/q/48580762
tags question: http://stackoverflow.com/q/48605843
tags question: http://stackoverflow.com/q/48625720
tags question: http://stackoverflow.com/q/48610981
tags question: http://stackoverflow.com/q/48579891
tags question: http://stackoverflow.com/q/48591768
tags question: http://stackoverflow.com/q/48535829
tags question: http://stackoverflow.com/q/48558085
tags question: http://stackoverflow.com/q/48527321
tags question: http://stackoverflow.com/q/48600374
tags question: http://stackoverflow.com/q/48494356
tags question: http://stackoverflow.com/q/48624974
tags question: http://stackoverflow.com/q/48539256
tags question: http://stackoverflow.com/q/48542473
tags question: http://stackoverflow.com/q/48571985
tags question: http://stackoverflow.com/q/48597099
tags question: http://stackoverflow.com/q/48588507
tags question: http://stackoverflow.com/q/48525481
tags question: http://stackoverflow.com/q/48579079
tags question: http://stackoverflow.com/q/48605800
tags question: http://stackoverflow.com/q/48570146
tags question: http://stackoverflow.com/q/48614790
tags question: http://stackoverflow.com/q/48532761
tags question: http://stackoverflow.com/q/48570654
tags question: http://stackoverflow.com/q/48556353
tags question: http://stackoverflow.com/q/48608585
tags question: http://stackoverflow.com/q/48502667
tags question: http://stackoverflow.com/q/48505435
tags question: http://stackoverflow.com/q/48625353
tags question: http://stackoverflow.com/q/48513777
tags question: http://stackoverflow.com/q/48589249
tags question: http://stackoverflow.com/q/48628041
tags question: http://stackoverflow.com/q/48524869
tags question: http://stackoverflow.com/q/48535962
tags question: http://stackoverflow.com/q/48580703
tags question: http://stackoverflow.com/q/48643181
tags question: http://stackoverflow.com/q/48534636
tags question: http://stackoverflow.com/q/48553974
tags question: http://stackoverflow.com/q/48578235
tags question: http://stackoverflow.com/q/48493755
tags question: http://stackoverflow.com/q/48549635
tag name: machine-learning
tags question: http://stackoverflow.com/q/48567012
tags question: http://stackoverflow.com/q/48586429
tags question: http://stackoverflow.com/q/48494667
tags question: http://stackoverflow.com/q/48608739
tags question: http://stackoverflow.com/q/48550201

http://stackoverflow.com/comment/84107646
has text: because the `Click` method is not static, you should use instace of Wait class to call `Click` or declare it as static method by changing code to `static Click(selector) {}`, if you change `Click` to static, you have to change `ElementVisibility` to static also and remove `this.` inside `Click` function
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48551528
type: Comment

http://stackoverflow.com/a/48601950
downvote count: 0
upvote count: 1
has body: In my view there is no need for the loop, as you can already do the check using xpath text() function: Check If Alert Contains Errormessage [Arguments] ${alert-message} Page Should Contain Element ... xpath://div[@class='alert-content']/span[@class='alert-description' and text()='${alert-message}'] ... message=The message "${alert-message}" is not found.
type: Answer
answers question: http://stackoverflow.com/q/48591317
score: 1

http://stackoverflow.com/q/48512194
score: 0
has body: I am using huge binary numbers, they come with 1024 digits and sometimes this code works well, but sometimes not. I think that this is very strange. This is the code that I'm using to transform binary into decimal def binToDec(d): z1 = (Random binary number) z = z1[:d] n = int(z,2) num=float(n) return num when the code fail they write to me n = int(z,2) ValueError: invalid literal for int() with base 2: '' somebody can help?
upvote count: 1
has comment: http://stackoverflow.com/comment/84019305
downvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84019338
type: Question
tagged with: python
has title: Error: Invalid literal for int() with base 2: ' '
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84019333
has answer: http://stackoverflow.com/a/48512238
tagged with: int
tagged with: binary
has comment: http://stackoverflow.com/comment/84092023
has comment: http://stackoverflow.com/comment/84019264

http://stackoverflow.com/q/48507800
type: Question
has answer: http://stackoverflow.com/a/72341577
tagged with: django-admin
has body: I have a model whose pre_save() signal is connected to a remove service (json, REST, etc.) in the following way: before saving locally, query the remote service, asking for remote insertion remote service does its things, the main being checking that a relevant entry does not already exist. On success (HTTP 201), all is good, the local model uses the remote service response to populate the db. on failure, the service returns an HTTP 400 (the status code is debatable but that is for a different question on SO :-) ) The error response is in the following form: {'local_model_field': [u'This element already exists']} The local model pre_save signal then raises a ValidationError: raise ValidationError(json_response['local_model_field'][0]) This works nicely. Now, on the django admin, when I try to simulate the remote insertion of an already-existing object, I get a 500 page, which is fine but not ideal. Is there any way to have the pre_save() error bubble all the way up to the ModelAdmin and be displayed as a standard error message, populated with the relevant content? I have tried the following but to no avail: def changeform_view(self, request, object_id=None, form_url='', extra_context=None): """ trying to display the right message when pre_save() fails on model save() method (after asking CC) """ try: return super(ObjectAdmin, self).changeform_view(request, object_id, form_url, extra_context) except IntegrityError as e: self.message_user(request, e, level=messages.ERROR) return HttpResponseRedirect(form_url) Is a ValidationError the right thing to do? Knowing that the pre_save() must lock out any chance of ending with with duplicates both locally and remotely. The main reason is that the local/remote object creation can be made form the admin but also from other website instances/types (front-end, end-user facing, for example). Thanks
tagged with: django-1.11
tagged with: python
score: 4
tagged with: django-signals
upvote count: 4
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
has title: Django pre_save signal and ModelAdmin custom error message
favorite count: 0

http://stackoverflow.com/q/48526888
tagged with: tkinter
tagged with: fonts
has body: I have written this code to get a list of installed fonts on my system, which should then create a text widget with all the fonts displayed. However, I find that some of the fonts in the list are named but not displayed correctly. They are not 'clickable' so I guess that a tag has not been created for that item. Anyone have an idea why this would be? import tkinter as tk from tkinter import * from tkinter import font def on_click(event): fontname=display.index('@{},{}'.format(event.x,event.y)) print (display.tag_names(fontname)) return None root = Tk() fonts=list(font.families()) fonts.sort() display = Text(root) display.pack(fill=BOTH, expand=YES, side=LEFT) scroll = Scrollbar(root) scroll.pack(side=RIGHT, fill=Y, expand=NO) scroll.configure(command=display.yview) display.configure(yscrollcommand=scroll.set) for item in fonts: i=fonts.index(item) i+=1 i=str(i) display.tag_add (item, ('{}.0'.format(i)) ,END) display.tag_config(item,font=(item,25,'normal')) display.tag_bind(item,'&lt;Double-1&gt;',on_click) display.insert(END, (item +'\n'),(item)) root.mainloop() my output for example 'Arial Black' is ('Arial', 'Black') but for 'Comic Sans MS' I get nothing. By passing 'font=(item,15,'normal) spaces should not be an issue or did I misread that? or could it be the way the font titles are formatted in the font file? This is all new to me the last time I did any coding it was on a zx81
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has title: Creating tag names for installed fonts and displaying font name in font style
score: 1
has answer: http://stackoverflow.com/a/48527112
has comment: http://stackoverflow.com/comment/84048925
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/84084850
score: 0
comment on: http://stackoverflow.com/q/48533882
has text: from my link the code is only 25 lines but on my page it always more than 100 lines..so lots of invisible elements unless i scroll it
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84059778
type: Comment
comment on: http://stackoverflow.com/a/48531046
score: 0
type: AnswerComment
has text: Yeah I've tried every combination and it's still saying that the band is not in the list

http://stackoverflow.com/q/48583384
has comment: http://stackoverflow.com/comment/84163170
downvote count: 1
tagged with: python
has body: I'm trying to create and play with classes in Python 3.6 but I'm getting the following error when I try to call a method that prints info about my class: 'TypeError: not enough arguments for format string' And here's the code I'm trying to run: class Restaurant(object): def __init__(self, name, type): self.name = name self.type = type def describe(self): print("Restaurant name: %s , Cuisine type: %s" % self.name, self.type) def open_restaurant(self): print("%s is now open!" % self.name) my_restaurant = Restaurant("Domino", "Pizza") my_restaurant.describe() my_restaurant.open_restaurant() The open_restaurant() method works fine but with my_restaurant.describe() I receive the error message I mentioned.
favorite count: 0
has comment: http://stackoverflow.com/comment/84163694
has answer: http://stackoverflow.com/a/48583434
has answer: http://stackoverflow.com/a/48583435
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48583609
type: Question
has title: "TypeError: not enough arguments for format string " using %s in Python 3.6
score: 0
answer count: 3

http://stackoverflow.com/comment/83997131
score: 1
type: Comment
type: QuestionComment
has text: Generally it's all the same as on the internet. Setup server (Apache, Nginx, whatever) and run it as in production.
comment on: http://stackoverflow.com/q/48501832

http://stackoverflow.com/a/48545022
accepted answer of: http://stackoverflow.com/q/48544925
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48544925
score: 0
type: Answer
has body: You can try to use list comprehension and index of the list colors= ["#049FBB", "#5DF10A", "#BF5B3F", "#A95058", "#9C6BE1","#6CC43C","#7B3001", "#B3D407","#97CE66"] #hex colours x = [1,2,3,4] y = [3,4,8,6] z= [4,6,8,2] plt.scatter(x,y,c=[colors[i] for i in z])

http://stackoverflow.com/comment/84193012
type: Comment
type: QuestionComment
has text: You can add one more context key and slice your query set fetched data you will get two lists than you can iterate
comment on: http://stackoverflow.com/q/48597920
score: 0

http://stackoverflow.com/comment/84075969
comment on: http://stackoverflow.com/a/48539883
has text: I am already aware that I basically don't need much mathematical background to perform such operations because library like scipy (or sklearn, and bunch of others) have already implemented the maths in a good way. But I need to comprehend how the mathematics work in order to get good. ;)
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/48627109
tagged with: pandas
has answer: http://stackoverflow.com/a/48627155
tagged with: python
linked to: http://stackoverflow.com/q/21954197
duplicate of: http://stackoverflow.com/q/28009370
has body: Would anyone know how to convert the string output to a float? What I am attempting to do create separate data frames for "Month" and "day of the week" based on the time stamp index. The df.index.strftime outputs a string but I need a float based on the months numerical value (0-11 or 1-12 for a Jan thru December) and a day of the week numerical value (0-6 or 1-7 for Sunday thru Saturday) from numpy.random import randint import pandas as pd # Create a df with a date-time index with data every 6 hours rng = pd.date_range('1/5/2018 00:00', periods=5, freq='6H') df = pd.DataFrame({'Random_Number':randint(1, 10, 5)}, index=rng) # Getting different time information in the columns df['month'] = df.index.strftime('%b') df['Day_of_week'] = df.index.strftime('%a') df
favorite count: 0
tagged with: time-series
score: 2
upvote count: 2
duplicate of: http://stackoverflow.com/q/21954197
answer count: 1
downvote count: 0
has title: Pandas time series data Index from a string to float
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48627155

http://stackoverflow.com/comment/84217358
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48565011
has text: Running it as a Python file still gives me the same error. I am using MacOs. Just tested it on ubuntu system and it worked fine!

http://stackoverflow.com/a/58437874
upvote count: 5
score: 5
type: Answer
answers question: http://stackoverflow.com/q/48518300
downvote count: 0
has body: "no_pm = true" doesn't seem to work now. so add "@commands.guild_only()" below @client.command() example: @client.command() @commands.guild_only() async def commandname():

http://stackoverflow.com/a/48629145
type: Answer
has comment: http://stackoverflow.com/comment/84268836
has comment: http://stackoverflow.com/comment/84292829
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48628755
has comment: http://stackoverflow.com/comment/84288309
has body: imaplib has a separate set of functions to operate on IMAP UIDs. status, response = self.imap.uid('search', None, "ALL") for uid in reversed(response[0].split()): status, response = self.imap.uid('fetch', uid, '(RFC822)')
has comment: http://stackoverflow.com/comment/84291711
has comment: http://stackoverflow.com/comment/84292929
has comment: http://stackoverflow.com/comment/84255569

http://stackoverflow.com/comment/109436232
has text: @Yatin My original answer indeed said `lst` instead of `list`, however prudence70 changed it to `list`, thinking it was a typo... (as can be seen in the edit history). I changed it back to the original.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48537762

http://stackoverflow.com/a/65753956
has body: I don't know if you fixed this problem or not. But this answer helps to resolve this issue. Git hub link Edit: Basically, the problem is with the Kafka package which uses an older version. You need to install the current version to resolve this issue. Try to install 'kafka-python' package using pip cmd. This works for me, hope will work for you too.
answers question: http://stackoverflow.com/q/48589678
has comment: http://stackoverflow.com/comment/116256999
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/116257665

http://stackoverflow.com/a/48649085
score: 3
has body: Python seems wrong, although I'm not sure it is an oversight or it has a deeper meaning. The explanation of BlackJack seems reasonable, but I don't understand, why they would give additional digits that are wrong. You can check this yourself by using the formula under More efficient series. In Mathematica, you can calculate it up to 70 (35 summands) with log2 = 2*Sum[1/i*(1/3)^i, {i, 1, 70, 2}] (* 79535292197135923776615186805136682215642574454974413288086/ 114745171628462663795273979107442710223059517312975273318225 *) With N[log2,30] you get the correct digits 0.693147180559945309417232121458 which supports the correctness of Wikipedia and W|A. If you like, you can do the same calculation for machine precision numbers. In Mathematica, this usually means double. logC = Compile[{{z, _Real, 0}}, 2.0*Sum[1/i*((z - 1)/(z + 1))^i, {i, 1, 100, 2}] ] Note that this code gets completely compiled to a normal iteration and does not use some error reducing summation scheme. So there is no magical compiled Sum function. This gives on my machine: logC[2]//FullForm (* 0.6931471805599451` *) and is correct up to the digits you pointed out. This has the precision that was suggested by BlackJack $MachinePrecision (* 15.9546 *) Edit As pointed out in comments and answers, the value you see in _math.c might be the 53 bit representation digits = RealDigits[log2, 2, 53]; N[FromDigits[digits, 2], 21] (* 0.693147180559945286227 *)
answers question: http://stackoverflow.com/q/48644767
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/comment/95416503
type: Comment
has text: plus one for the first two sentences. Better not using jinja2 for generating json.
comment on: http://stackoverflow.com/a/48720031
type: AnswerComment
score: 1

http://stackoverflow.com/comment/84034224
type: AnswerComment
has text: Hmmm, getting a 'TypeError: unsupported operand type(s) for |: 'float' and 'bool'' after fixing the float issue. Any idea?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48519677

http://stackoverflow.com/q/48600409
tagged with: sockets
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84203041
accepted answer: http://stackoverflow.com/a/48604090
score: 1
tagged with: tcp
has answer: http://stackoverflow.com/a/48604090
has title: How to run interactive commands using python tcp socket?
type: Question
tagged with: python-3.x
tagged with: python-sockets
has body: Say if I wanted to run vim ./foo.txt I want to be able to edit foo.txt with my tcp socket client. But whenever I try to do this it executes on the server but not on my client. I do not want to use paramiko or any other ssh-like modules I want to stay using the python socket module. I am using python 3.

http://stackoverflow.com/a/50111244
has comment: http://stackoverflow.com/comment/87302021
type: Answer
answers question: http://stackoverflow.com/q/48572831
has body: Use the .__args__ on your constructs. So the magic function you need is something like -- get_type_args = lambda genrc_type: getattr(genrc_type, '__args__') My question is, how can I access these type arguments? In situations like these -- how do I access ... Use Python's powerful introspection features. Even as a non-pro programmer I know I am trying to inspect stuff and dir is a function which is like IDE in terminal. So after &gt;&gt;&gt; import typing &gt;&gt;&gt; str_to_bool_dict = typing.Dict[str, bool] I want to see if there's anything that does the magic you want so &gt;&gt;&gt; methods = dir(str_to_bool_dict) &gt;&gt;&gt; methods ['__abstractmethods__', '__args__', .....] I see too much info, to see if I am correct I verify &gt;&gt;&gt; len(methods) 53 &gt;&gt;&gt; len(dir(dict)) 39 Now let us find the methods which were designed specifically for generic types &gt;&gt;&gt; set(methods).difference(set(dir(dict))) {'__slots__', '__parameters__', '_abc_negative_cache_version', '__extra__', '_abc_cache', '__args__', '_abc_negative_cache', '__origin__', '__abstractmethods__', '__module__', '__next_in_mro__', '_abc_registry', '__dict__', '__weakref__'} among these, __parameters__, __extra__, __args__ and __origin__ sound helpful. __extra__ and __origin__ won't work without self so we are left with __parameters__ and __args__. &gt;&gt;&gt; str_to_bool_dict.__args__ (&lt;class 'str'&gt;, &lt;class 'bool'&gt;) Hence the answer. Introspection allows py.test's assert statements to make JUnit derived testing frameworks look obsolete. Even languages like JavaScript / Elm / Clojure don't have a straight-forward thingy like dir of Python. Python's naming convention allows you to discover the language without actually reading (grokking in some cases such as these) the documentations. So hunt using introspection and read documentation/mailing-lists to confirm your findings. P.S. To OP -- this method also answers your question What&#39;s the correct way to check if an object…
upvote count: 4
score: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/87243876

http://stackoverflow.com/comment/84227949
type: QuestionComment
comment on: http://stackoverflow.com/q/48614934
type: Comment
score: 0
has text: Theuse of `array(where(...` is odd. So is the `np.size...`. Print `index`, and make sure `j` is giving good values.

http://stackoverflow.com/comment/84089432
type: Comment
has text: [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter)s are the best data structures for this
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48546827

python-internals
tags question: http://stackoverflow.com/q/48525560
tag name: python-internals
tags question: http://stackoverflow.com/q/48609111
type: Tag

http://stackoverflow.com/q/48544207
answer count: 1
has title: Generate a correct scrapy hidden input form values for asp doPostBack() function
tagged with: web-scraping
tagged with: scrapy
tagged with: asp.net
favorite count: 0
type: Question
tagged with: python
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48649509
has body: tldr; My attempts to overwritte the hidden field needed by server to return me a new page of geocaches failed (__EVENTTARGET attributes) , so server return me an empty page. Ps : My original post was closed du to vote abandon, so i repost here after a the massive edit i produce on the first post. I try to scrap some webpages which contain cache on a famous geocaching site using Scrapy 1.5.0. Because you need an account if you want to run this code, i create a new temporary and free account on the website to make some test : dumbuser with password stackoverflow A) The actual working part of the process : First, i enter the website by login page (needed to search page) : https://www.geocaching.com/account/login After successful login, i search item (geocaches) in some geographic places (for exemple France, Haute-Normandie). This first search works without problem, and i have no difficulties to parse the first geocaches. B) The problem part of the process : requesting next pages When i try to simulate a click to go to the next page of geocaches. For example going to page 1 to page 2. The website use ASP with synchronised state between client and server, so we need to go to page1 then page2 then page3 then etc. during the scrap in order to maintain the __VIEWSTATE variable (an hidden input) generated by server between each FORM query. The link of each number (see the image) call a link with javascript function javascript:__doPostBack(...), which inject content into already existing hidden field before submitting the entire form. As you can see in the __doPostBack function : &lt;script type="text/javascript"&gt; //&lt;![CDATA[ var theForm = document.forms['aspnetForm']; if (!theForm) { theForm = document.aspnetForm; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]&gt; &lt;/script&gt; Exemple : …
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/48649509

http://stackoverflow.com/q/48620110
accepted answer: http://stackoverflow.com/a/48644247
has comment: http://stackoverflow.com/comment/84236833
has answer: http://stackoverflow.com/a/48644247
has comment: http://stackoverflow.com/comment/84236945
has comment: http://stackoverflow.com/comment/84237129
tagged with: python
has comment: http://stackoverflow.com/comment/84239221
has comment: http://stackoverflow.com/comment/84237223
has comment: http://stackoverflow.com/comment/84237200
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84237616
has body: basically i read file.txt line by line and the problem is that he reads some invisible symbols. To prove that i try to show length of the string and it's is greater by 1 than real is. Here is my code: new_words = [] with open("./file.txt") as f: new_words = [word.strip() for word in f] for w in new_words: print("word: " +str(w) + "length: " + str(len(w))) And it shows that length is a bigger by 1 that the real length, for example instead of 10 it shows 11.
has comment: http://stackoverflow.com/comment/84238274
has title: How to delete invisible symbols python
has comment: http://stackoverflow.com/comment/84237590
answer count: 1
has comment: http://stackoverflow.com/comment/84237179
upvote count: 1
has comment: http://stackoverflow.com/comment/84237422
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84236882
has comment: http://stackoverflow.com/comment/84236934
score: 0

data-structures
tags question: http://stackoverflow.com/q/48621457
tag name: data-structures
tags question: http://stackoverflow.com/q/48596726
tags question: http://stackoverflow.com/q/48552061
tags question: http://stackoverflow.com/q/48600165
tags question: http://stackoverflow.com/q/48492750
tags question: http://stackoverflow.com/q/48572494
tags question: http://stackoverflow.com/q/48645730
tags question: http://stackoverflow.com/q/48566534
type: Tag
tags question: http://stackoverflow.com/q/48574363
tags question: http://stackoverflow.com/q/48593572

http://stackoverflow.com/q/48517177
has comment: http://stackoverflow.com/comment/84028918
has title: How to search nested dictionary in Python using returned values from user inputs
tagged with: for-loop
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48519302
has comment: http://stackoverflow.com/comment/84030173
tagged with: nested
has comment: http://stackoverflow.com/comment/84028929
tagged with: loops
has answer: http://stackoverflow.com/a/48519302
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/84028886
has body: I am looking for the most efficient means of returning a value within a nested dictionary. At this point in the code, the Airline name (e.g. 'Delta') and the fare class (e.g. 'N') have already been inputted by the user and validated using re. The variables 'airline_name' and 'fare_class' are already defined. There are multiple fare classes that contain the same value; 'Delta' > 'F' 'J' > '2' What would be the best way to search for a nested dictionary value (e.g. '1.5') using the passed in variable names 'airline_name' and 'fare_class'? Thanks for any and all feedback! (if I need to restructure my dict, I am more than happy to as well) `FARE_CLASS_MULTIPLIER_DICTIONARY = { 'Delta': { ('N'): 0, ('E', 'H', 'K', 'L', 'M', 'Q', 'S', 'T', 'U', 'V', 'W+', 'X'): 1, ('A', 'B', 'C', 'D', 'G', 'I', 'P', 'W', 'Y', 'Z'): 1.5, ('F', 'J'): 2 }, 'United': { ('N'): 0, ('M', 'E', 'U', 'H', 'Q', 'V', 'W', 'S', 'T', 'L', 'K', 'G'): 1, ('Y', 'B'): 1.5, ('A', 'C', 'D', 'Z', 'P'): 2, ('F', 'J'): 3 }, 'American': { ('A'): 0, ('H', 'K', 'M', 'L', 'V', 'G', 'S', 'N', 'Q', 'O'): 1, ('Y', 'W', 'P'): 1.5, ('A', 'D', 'I', 'R'): 2, ('F', 'J'): 3 } }
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84028948

http://stackoverflow.com/comment/83985050
comment on: http://stackoverflow.com/q/48495899
has text: which line has the error? Can you post full stack trace?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48491525
tagged with: python-3.x
upvote count: 5
has title: implement query language on python
has comment: http://stackoverflow.com/comment/83976415
has answer: http://stackoverflow.com/a/48491690
possible better answer: http://stackoverflow.com/a/48491690
tagged with: python
has comment: http://stackoverflow.com/comment/83976411
type: AnsweredQuestion
answer count: 2
score: 5
tagged with: abstract-syntax-tree
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
has body: I'm looking for a way to expose filtering functionality at my workplace to other developers and optionally customers. Problem i want to implement a simple query language over my data (python dicts) based on user defined filters exposed to my other developers and later on to our customers. the language should be simple enough to be used by non-developers safe enough to avoid remote code execution on my servers expressive enough to query data like the below example Exposing SQL interface over my dict / json data would be great (I prefer not to setup server) Example Scenario db = [ {'first': 'john', 'last': 'doe', 'likes': ['cookies', 'http']}, {'first': 'jane', 'last': 'doe', 'likes': ['cookies', 'donuts']}, {'first': 'danny', 'last': 'foo', 'likes': ['http', 'donuts']}, ] query = '(first == "john" or last == "doe") and likes contains "cookies"' results = run_query(db, query) this should return (in results): [ {'first': 'john', 'last': 'doe', 'likes': ['cookies', 'http']}, {'first': 'jane', 'last': 'doe', 'likes': ['cookies', 'donuts']}, ] note: i do not mind changing the operator names, e.g. or -&gt; OR contains -&gt; inside or anything else as long as it is human readable and keeps the same expressiveness of the language Solutions I Tried DSL I looked at some DSL libraries like PLY but they seems to me too complex and involves some magic to get things done (not really sure where to start and if its worth it) Plugins didnt find any plugin system to expose a sandboxed functionality for my users (i.e. safer eval) JSON Query Packages I looked at TinyDB and others that implement some sort of SQL over json but couldn't find something that work without alot of customizations. I also looked at pandasql which seems good overall but unmaintained library :( there is a lucene package parser - luqum based on PLY but its different from my syntax tree (they have more methods) and the lib is not really maintained, (I do consider manipulating this lib a bit to get what i want) SQLit…
has answer: http://stackoverflow.com/a/59927654
accepted answer: http://stackoverflow.com/a/59927654
has comment: http://stackoverflow.com/comment/83976268
favorite count: 0
type: Question

http://stackoverflow.com/comment/84225989
comment on: http://stackoverflow.com/q/48530293
score: 0
has text: Is there any improvement if you set the timeout to a different value? It may be possible to alter the strategy altogether and manage concurrent login requests, by allowing different user authentication at an a minimum interval from one another. You can determine a minimum delay value, that never allows users to login too soon. In this way, no resulting duplicate accounts occur.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84203572
type: Comment
type: QuestionComment
score: 0
has text: Thanks! I was looking forward to make my code more efficient too. :)
comment on: http://stackoverflow.com/q/48588810

http://stackoverflow.com/comment/84133295
type: AnswerComment
comment on: http://stackoverflow.com/a/48564670
has text: Thanks it worked and i was using two nested for loops thats why i think i cannot get a single list and getting first alphabet of each word
type: Comment
score: 0

http://stackoverflow.com/q/48592416
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84218500
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/84222913
score: 0
tagged with: python
has title: Save tensor as image doesn't work
type: Question
has comment: http://stackoverflow.com/comment/84223000
answer count: 0
has body: I have the following problem: I have the Tensor Tensor("content_vgg/conv1_1/Relu:0", shape=(1, 224, 224, 64), dtype=float32, device=/device:CPU:0) and I want to save it as an image, but whatever I try to do I get an InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [1,224,224,3] [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[1,224,224,3], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]] error This is my code, I already tried to add the placeholder but even that doesn't work self.conv1_1 = self.conv_layer(bgr, "conv1_1") print(self.conv1_1) x = tf.placeholder_with_default(input=self.conv1_1,shape=[1,224,224,64], name='x') images = tf.reshape(tf.cast(x, tf.uint8), [224, 224, 64]) images_encode = tf.image.encode_jpeg(images) fname = tf.constant('test.jpeg') fwrite = tf.write_file(fname, images_encode) self.sess.run(fwrite)` Can someone help me or give me an advice or let me knwo how I can save the Tensor as image with another solution?
tagged with: tensor

http://stackoverflow.com/a/48637535
has body: In you mysite/urls.py file change this line: url(r'^polls/', include('polls.urls')), to this line: url(r'^polls/', include('polls.urls', namespace='polls')),
answers question: http://stackoverflow.com/q/48637431
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48615031
tagged with: python
has title: How to structure listen and disseminate with asyncio websockets?
has comment: http://stackoverflow.com/comment/84234132
type: Question
score: 0
has body: I'm trying to write a server using asyncio/websockets that listens to a single websocket connection on one port, and when it gets a message, it sends that to all of the websockets that are listening to it on a separate port. There could be hundreds of clients on the second port, so I know I need to use the non-blocking await websocket.send(msg). But I can't figure out how to structure this listen/disseminate paradigm in terms of the event loops. Here's my first attempt: import asyncio import websockets import time LISTEN_PORT = 8080 SPEAK_PORT = 8081 audience = [] async def add_audience_member(websocket, path): global audience print('New audience member!') audience.append(websocket) async def add_source(websocket, path): global audience while True: msg = await websocket.recv() for ws in audience: await ws.send(msg + ' ' + str(time.time())) loop = asyncio.get_event_loop() loop.run_until_complete(websockets.serve(add_audience_member, HOST, SPEAK_PORT)) loop.run_until_complete(websockets.serve(add_source, HOST, LISTEN_PORT)) loop.run_forever() Then I have a client running: from websocket import create_connection ws = create_connection('ws://{}:{}'.format(HOST, 8081)) while True: data = ws.recv(); print data The problem is that add_audience_member closes the connection as soon as it adds the new websocket to the audience list, so I get the error: websocket._exceptions.WebSocketConnectionClosedException: Connection is already closed.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84227162
tagged with: websocket
has comment: http://stackoverflow.com/comment/84227351
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84234217
tagged with: python-asyncio

http://stackoverflow.com/q/48523267
has answer: http://stackoverflow.com/a/48525410
tagged with: scrapy
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Scrapy: Grabbing information AFTER an end tag nested in a data cell
score: 0
has body: I want to grab a specific link. My issue is that that link is identified within a cell without a specific tag. For example: &lt;td class="tableText" style="padding-left: 10px;"&gt; &lt;a href="/link"&gt;John&lt;/a&gt;;&amp;nbsp; &lt;a href="/link"&gt;Jacob&lt;/a&gt;;&amp;nbsp; (Primary) &lt;br/&gt; &lt;a href="/link"&gt;Jingle&lt;/a&gt;;&amp;nbsp; &lt;a href="/link"&gt;Bud&lt;/a&gt;;&amp;nbsp; &lt;/td&gt; Basically, I only want to scrape the link labeled "Jacob", identified through the text ("Primary") following it. In this case, my code so far looks like this: item['stuff'] = response.xpath('//div[@id = "mainBody"]/table/tr/td/a/text()').extract() In this case, I want scrapy to get a**[2]**.
accepted answer: http://stackoverflow.com/a/48525410
answer count: 1

http://stackoverflow.com/q/48637327
type: UnansweredQuestion
tagged with: operating-system
tagged with: python
has title: Recognize the interrupt every time a folder is double clicked and pass the info to nodejs inorder to generate an otp.
tagged with: node.js
has comment: http://stackoverflow.com/comment/84271127
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84272952
has comment: http://stackoverflow.com/comment/84272994
type: Question
has body: I am working on a project to generate an otp every time a folder is to be accessed and send the otp to the owner of the system. Unable to find out how to Catch the interrupt originated to access the folder. Comfortable with both Windows and Linux.
tagged with: linux

http://stackoverflow.com/q/48597120
type: Question
has answer: http://stackoverflow.com/a/48619652
score: 2
has title: Installing PySimulator
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
favorite count: 0
tagged with: modelica
tagged with: dymola
has answer: http://stackoverflow.com/a/48649740
tagged with: python
has body: I tried to install PySimulator: https://github.com/PySimulator/PySimulator After following the first step: "Start "Install PySimulator.bat". This batch file installs the 32 Bit Python(x,y) and all other necessary packages.", there isn't a "PySimulator-Icon" only a Python(x,y)-Icon. 1. Is this correct? I don't know how to use this.. 2. How can I open the GUI "Simulation and Analysis Environment", like it is shown here: http://elib.dlr.de/81304/1/PySimulator-MODPROD.pdf Thankful for any help! When I'm trying to install it via conda like in https://modelica.org/events/modelica2017/documents/3ds_TestingTutorialSlides.pdf (slide 43) It works until python setup.py install Then I get the following error: Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.34.tar.gz Traceback (most recent call last): File "setup.py", line 5, in &lt;module&gt; distribute_setup.use_setuptools() File "C:\pysim\src\distribute_setup.py", line 154, in use_setuptools return _do_download(version, download_base, to_dir, download_delay) File "C:\pysim\src\distribute_setup.py", line 133, in _do_download to_dir, download_delay) File "C:\pysim\src\distribute_setup.py", line 203, in download_setuptools src = urlopen(url) File "C:\Users\annes\AppData\Local\conda\conda\envs\PySim\lib\urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "C:\Users\annes\AppData\Local\conda\conda\envs\PySim\lib\urllib2.py", line 435, in open response = meth(req, response) File "C:\Users\annes\AppData\Local\conda\conda\envs\PySim\lib\urllib2.py", line 548, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\annes\AppData\Local\conda\conda\envs\PySim\lib\urllib2.py", line 473, in error return self._call_chain(*args) File "C:\Users\annes\AppData\Local\conda\conda\envs\PySim\lib\urllib2.py", line 407, in _call_chain result = func(*args) File "C:\Users\annes\AppData\Local\conda\conda\envs\PySim\lib\urllib2.py", line 556, in http_error_default raise HTTPErr…

http://stackoverflow.com/comment/83994545
type: QuestionComment
has text: So you want: `"*INHERIT_POS": [0,0,0]` and `'*NODE_NAME': '"30deg017"'`, but not: `'*NODE_NAME': ['"30deg017"']`
type: Comment
comment on: http://stackoverflow.com/q/48500167
score: 0

http://stackoverflow.com/q/48604831
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84206241
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84216139
tagged with: python
score: 0
has body: What the Monty Hall game is: The stage is set up with three large doors labeled #1, #2, and #3. Behind two of the doors is a goat. Behind the other door is a new car. You don’t know which door has the car, but Monty Hall wants you to pick a door. Suppose you pick door #1. Monty Hall then opens one of the other doors (say, door #3) and shows you that there’s a goat behind it. He then says: "I’ll give you a chance to change your mind. Do you want to change your mind and pick door number 2?" After you make a decision, they open the door you finally picked and you find out whether you’ve won a new car or a new goat. To clarify: the locations of the car and the goats are fixed before your game starts. Monty does not get a chance to switch things around in the middle of the game. What I have to do: I need to create a stimulator of the game using Python 3. I have to incorporate a random number generator. The program will ask the user for the Random Number generator seed. The goal of a random number generator is to be random. Before my program begins simulating “Let’s Make a Deal,” it's supposed to ask the user for an integer and set it as the seed. If the user gives an input that is not a number, the program should exit immediately by displaying "Seed is not a number!" IF the user gives a number for the input, the game will begin. The game will then ask the user how many games the user wants to run. If the user says 5, the game will repeat five times. Once the game runs the amount of times the user says (like 5), then the game will ask the user AGAIN how many times the user wants to play again.(I'm having difficulty with this looping the game to the number of times the user says and then asking the question once it's done). If the user says 'exit' anytime, the game immediately ends. When asked how many games the user wants to run, if the user does not input a number, the program will just say "Please enter a number" until the user finally enters a number. What the program …
answer count: 0
has title: Having difficulty with my Monty Hall stimulator code (python)
type: Question

http://stackoverflow.com/q/48615438
answer count: 1
has comment: http://stackoverflow.com/comment/84228882
has comment: http://stackoverflow.com/comment/84229493
tagged with: git
type: Question
tagged with: python-3.x
has title: type of object 'NewsletterUsuario' has no len()
has body: I'm new using django as a framework, I got a problem when I try to save a newsletter on my custom control_panel, I can save the message but the web crash and show me a typeError telling me about a class model I made 'NewsletterUsuario' but just on the custom control_panel, in django admin mode it works normally, the problem start to happen after I eliminate some files from a app that I did not want to use and even I did a git reset to a working version still get this similar typeError, here is my models, views and traceback: models.py from django.db import models # Create your models here. class NewslettersUsuario(models.Model): email = models.EmailField() fecha_agregado = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Newsletter(models.Model): EMAIL_STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) subject = models.CharField(max_length =250) body = models.TextField() email = models.ManyToManyField(NewslettersUsuario) status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.subject Views.py from django.conf import settings from django.contrib import messages from django.shortcuts import render from django.core.mail import send_mail, EmailMultiAlternatives from django.template.loader import get_template from .models import NewslettersUsuario, Newsletter from .forms import NewslettersUsuarioSignUpForm, NewsletterCreacionForm # Create your views here. def newsletter_signup(request): form = NewslettersUsuarioSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewslettersUsuario.objects.filter(email=instance.email).exists(): messages.warning(request, "Lo siento! este Correo ya existe.", 'alert alert-warning alert-dismissible') else: instance.save() messages.success(request, "Tu e-mail a sido agregado!", 'alert alert-success alert-dismissible…
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84229411
has answer: http://stackoverflow.com/a/48616449

http://stackoverflow.com/q/48492906
answer count: 1
has answer: http://stackoverflow.com/a/48494020
type: Question
has title: Anaconda crashes when I attempt to use certain Numpy, Scipy, or Matplotlib functions
tagged with: anaconda
has body: I receive an error when I try to run some functions on Anaconda (specifically the Jupyter Notebook). For example, when I attempt to use linalg from Numpy, I receive the following error and the kernel crashes: The procedure entry point mkl_aa_fw_init_workdivision could not be located in the dynamic link library C:\Users\myusername\Anaconda3\Library\bin\mkl_intel_thread.dll The file mkl_intel_thread.dll is located in the directory, so I'm not sure what this error exactly means. The same error is displayed when I run other functions from Scipy or Matplotlib. Some functions like the dot function in Numpy work, but some others don't. For further reference, the message on the command prompt reads: Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll [I 16:38:02.361 NotebookApp] KernelRestarter: restarting kernel (1/5) Any help resolving this issue would be thoroughly appreciated!
tagged with: python
has comment: http://stackoverflow.com/comment/83979014
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/83981158
type: UnansweredQuestion

http://stackoverflow.com/comment/84060636
has text: If the service on port 1524 is configured to give you back a shell then just passing the parameter (`sock.send(cmd)`) will work (if not what's the traceback). Also another and of course easier way to do it is using `pwntools`.
score: 0
comment on: http://stackoverflow.com/q/48531883
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84090699
type: QuestionComment
comment on: http://stackoverflow.com/q/48547420
has text: It's not a *function*, it's a *field* or *attribute* to the object. Try `a = 5 + 3j`, `print(a.real)`.
type: Comment
score: 0

http://stackoverflow.com/comment/84159723
type: AnswerComment
comment on: http://stackoverflow.com/a/48580406
has text: @Netwave that's what I already do in the previous example. In other words dothejob(50,22,11) starts, dothejob(50,22,12) starts, dothejob(50,22,12) finished, (50,22,12) logged. Computation stopped (but dothejob(50,22,11) hadn't finished!). When we'll restart the last log will be (50,22,12), making us believe we should begin at (50,22,13). Wrong: we never finished (50,22,11). Well anyway that's not a big issue, all I need to is to log all items done, and then when doing your `while True: if next(the_args) == (i, j, k): break` I'll modify to break at the first item not already present in the log.
type: Comment
score: 0

http://stackoverflow.com/q/48537503
favorite count: 0
type: Question
answer count: 2
has body: How can I make directory &amp; put image in the directory? I wrote the following code in data.py: import os import cv2 import argparse import numpy as np import math parser = argparse.ArgumentParser(description='') parser.add_argument('input_dir' ,help='input directory') parser.add_argument('output_dir' ,help='out directory') args = parser.parse_args() def find_all_files(directory): for root, dirs, files in os.walk(directory): for file in files: p=os.path.join(root, file) p=p.split("/")[len(p.split("/"))-2] name, ext = os.path.splitext(p) yield os.path.join(root, file) dirname=args.output_dir if not os.path.exists(dirname): os.mkdir(dirname) folder_img = find_all_files(args.input_dir) im =cv2.imread(folder_img) cv2.imwrite(args.output_dir ,im) Now when I run command python data.py ./photo ./copy_photo, find a writer for the specified extension in function imwrite error happens. I want to make a directory copy_photo and put images made by this code in the directory. The copy_photo folder is made, so what is wrong in my code? How should I fix this? Am I wrong to write the way of putting images in the copy_photo folder?
has answer: http://stackoverflow.com/a/48537719
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84070262
tagged with: python
score: 2
has title: How can I make directory & put image in the directory?
upvote count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/48537761

rs485
tags question: http://stackoverflow.com/q/48561631
type: Tag
tag name: rs485

http://stackoverflow.com/q/48533885
downvote count: 1
tagged with: http
favorite count: 0
tagged with: post
type: Question
has comment: http://stackoverflow.com/comment/84063952
has answer: http://stackoverflow.com/a/50128651
has comment: http://stackoverflow.com/comment/84064299
tagged with: api
tagged with: python
tagged with: request
accepted answer: http://stackoverflow.com/a/50128651
has title: Find the api call for getting the bitcoin price on Robinhood
score: 2
has body: I am interested in writing a python algorithmic trading bot for cryptocurrencies on Robinhood. Currently, I have been playing around with this wrapper, but it is not yet updated for cryptocurrencies. If I want to fetch the price of google stock, going to https://api.robinhood.com/quotes/GOOG/ shows the result, but I can't figure out the equivalent for say, bitcoin. I have tried sniffing packets from my android phone to see what the app uses for its updates to the the value, but I think I am too inexperienced to figure it out that way. How can I use the python request module to find the value?
type: AnsweredQuestion
upvote count: 3
answer count: 1

http://stackoverflow.com/comment/83994015
has text: @MikeMüller In this case yes, but this is only for sake of the MCVE. My real example is more complicated. I'll link it to the question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48500152

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/48501703

http://stackoverflow.com/a/48508376
type: Answer
has comment: http://stackoverflow.com/comment/89625706
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48505013
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48505013
has comment: http://stackoverflow.com/comment/84032985
has body: Using IntervalIndex: # create an IntervalIndex from start/end iv_idx = pd.IntervalIndex.from_arrays(df['start'], df['end'], closed='both') # generate the desired index of individual times new_idx = pd.date_range(df['start'].min(), df['end'].max(), freq='s') # set the index of 'status' as the IntervalIndex, then reindex to the new index result = df['status'].set_axis(iv_idx, inplace=False).reindex(new_idx) The resulting output for result: 2017-01-01 13:09:01 OK 2017-01-01 13:09:02 OK 2017-01-01 13:09:03 OK 2017-01-01 13:09:04 OK 2017-01-01 13:09:05 OK 2017-01-01 13:09:06 NaN 2017-01-01 13:09:07 ERROR 2017-01-01 13:09:08 ERROR 2017-01-01 13:09:09 ERROR 2017-01-01 13:09:10 NaN 2017-01-01 13:09:11 NaN 2017-01-01 13:09:12 OK 2017-01-01 13:09:13 OK 2017-01-01 13:09:14 OK Freq: S, Name: status, dtype: object
has comment: http://stackoverflow.com/comment/89602501

http://stackoverflow.com/comment/84111475
comment on: http://stackoverflow.com/q/48557613
score: 1
type: Comment
type: QuestionComment
has text: @DmitriChubarov. The original array is already a sequence of rows. It's pretty clear that you understand what's going on. these questions I'm asking are meant for OP only really, to assess what they know and don't know. The problem here is that the basic answer is trivial, which means that there is a large gap in OP's knowledge to fill in. Estimating the size of the gap will tell me if I should direct them to a tutorial or answer the question.

http://stackoverflow.com/q/48561429
tagged with: tkinter
upvote count: 0
has comment: http://stackoverflow.com/comment/84118685
has body: I'm very new to coding and have been trying to create a fairly basic login window using Tkinter. So far it works as intended but I'm trying to make it look more appealing. class LoginFrame(Frame): def __init__(self, master): super().__init__(master) self.master = master master.title("SEN Tracker Login") master.geometry("500x320") self.grid() self.labelLogin = Label(self, text = "Login") self.labelLogin.grid(row=1, column=3, columnspan=2) self.label_Username = Label(self, text="Username") self.label_Password = Label(self, text="Password") self.entry_User = Entry(self) self.entry_Pass = Entry(self, show="*") self.label_Username.grid(row=2, column=1, columnspan=2) self.label_Password.grid(row=3, column=1, columnspan=2) self.entry_User.grid(row=2, column=3, columnspan=3) self.entry_Pass.grid(row=3, column=3, columnspan=3) This is the code I have created so far, it does not include the part which compares the text entered for the login. Using this creates a window as follows: I was hoping to get some help moving the top left widgets to the center and enlarging them, I don't mind how big, I just want to know how to do it really.
answer count: 1
accepted answer: http://stackoverflow.com/a/48567183
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48567183
has comment: http://stackoverflow.com/comment/84119869
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84127303
tagged with: python
score: -1
has title: How do I increase the size of the login boxes and move them into the middle of the window
has comment: http://stackoverflow.com/comment/84126961
has comment: http://stackoverflow.com/comment/84119977
type: Question

http://stackoverflow.com/q/48566256
type: Question
has answer: http://stackoverflow.com/a/48566444
has body: I can not create GAE app neither from console or gcloud command with Editor role. Does anyone know how to create GAE app in Editor role or any solution to create GAE app without owner role? Thanks
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has title: How to create GAE app with Editor role
score: 0
tagged with: google-cloud-platform
answer count: 1
tagged with: deployment

http://stackoverflow.com/comment/84042284
has text: as per my pseudo-code, you are looping through 2 lists: list of filenames (strings) and list of dataframe objects. That's what you have in your question, correct?
comment on: http://stackoverflow.com/a/48521810
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48577588
answers question: http://stackoverflow.com/q/48570903
has body: odoo 11 error when installing module subtype_id Hello, I tried to install the module which you have been made.This gave the error of "ImportError: No module named 'models'" . So you have to write in init.py file like this.... from . import models this will solved your error. you ask about an error in mail module this is caused by your another custom module in your path. there is no other error in this module.so check your other custom modules.
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/84092722
score: 0
has text: Do you want an array of strings, or a structured array with one field of strings, the other integers?
comment on: http://stackoverflow.com/q/48546699
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48578149
has comment: http://stackoverflow.com/comment/84158752
has body: &gt;&gt;&gt; diff_dict = {k:[x for x in v if x not in second_dict.get(k, [])] for k,v in mydict.items()} &gt;&gt;&gt; diff_dict {'c': [['a'], [4, 5]], 'a': [[5, 6]], 'b': []} &gt;&gt;&gt; diff_dict = {k:v for k,v in diff_dict.items() if v} &gt;&gt;&gt; diff_dict {'c': [['a'], [4, 5]], 'a': [[5, 6]]} I would recommend the having the values in mydict and second_dict as set instead of list for efficiency and cleaner code.
answers question: http://stackoverflow.com/q/48577890
type: Answer
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84159108
accepted answer of: http://stackoverflow.com/q/48577890
score: 2

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/48585827
type: Tag
tags question: http://stackoverflow.com/q/48511256

http://stackoverflow.com/comment/88109361
type: AnswerComment
has text: Find the "Processes" in the result, where you will find Process ID @K.Wanter
comment on: http://stackoverflow.com/a/48515395
type: Comment
score: 0

http://stackoverflow.com/q/48524552
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/48525307
has title: Creating records in python based on conditions from dataframe
has comment: http://stackoverflow.com/comment/84044520
type: UnansweredQuestion
has body: I have a dataframe A like this. Timestamp A B C D 1/1/2018 0:00 10 10 10 10 1/1/2018 0:10 10 25 1/1/2018 0:20 10 25 1/1/2018 0:30 25 1/1/2018 0:40 25 1/1/2018 0:50 25 25 25 25 1/1/2018 1:00 30 30 30 30 1/1/2018 1:10 42 42 42 42 1/1/2018 1:20 1/1/2018 1:30 1/1/2018 1:40 40 40 40 1/1/2018 1:50 35 35 1/1/2018 2:00 37 1/1/2018 2:10 49 1/1/2018 2:20 51 51 51 I want to delete some rows based on the following dataframe as follows. StartTime EndTime Comment 1/1/2018 1:20 1/1/2018 1:30 to be removed 1/1/2018 2:00 1/1/2018 2:20 to be removed To get the dataframe A without the above timestamps as Timestamp A B C D 1/1/2018 0:00 10 10 10 10 1/1/2018 0:10 10 25 1/1/2018 0:20 10 25 1/1/2018 0:30 25 1/1/2018 0:40 25 1/1/2018 0:50 25 25 25 25 1/1/2018 1:00 30 30 30 30 1/1/2018 1:10 42 42 42 42 1/1/2018 1:40 40 40 40 1/1/2018 1:50 35 35 And I want results like as follows: StartTime EndTime Column Comment 1/1/2018 0:10 1/1/2018 0:40 A NULL 1/1/2018 1:50 1/1/2018 1:50 A NULL 1/1/2018 0:10 1/1/2018 0:40 B NULL 1/1/2018 1:40 1/1/2018 1:50 B NULL 1/1/2018 0:30 1/1/2018 0:40 C NULL Thanks for the help in advance.
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48525966
downvote count: 1
has comment: http://stackoverflow.com/comment/84043944
favorite count: 0
has comment: http://stackoverflow.com/comment/84044400
score: 0
tagged with: pandas
tagged with: records
has comment: http://stackoverflow.com/comment/84044832
tagged with: dataframe
type: Question

http://stackoverflow.com/comment/84085083
has text: You can automate a browser with selenium and python. Sounds like it would be easiest solution.
comment on: http://stackoverflow.com/q/48544859
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48545150
downvote count: 1
tagged with: opencv
has answer: http://stackoverflow.com/a/48545995
tagged with: python
score: -1
tagged with: image-processing
has body: Why is it if i read a video file using cv2.VideoCapture('video.avi') the fps is very very very low? I want the fps to be the same as when i play the video using a video player(30fps). What changes should i make to achieve this? Btw, i am using a raspberry pi 3 with python. import cv2 import numpy as np cap = cv2.VideoCapture('Fchecking.avi') kernel = np.ones((5,5), np.uint8) while(1): # Take each frame ret, frame = cap.read() img2gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ret,mask = cv2.threshold(img2gray,140,255,cv2.THRESH_BINARY) w3w = cv2.adaptiveThreshold(mask,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,47,2) cv2.imshow("mask", mask) mask_inv = cv2.bitwise_not(w3w) img2_fg = cv2.bitwise_and(frame, frame, mask=mask_inv) hsv = cv2.cvtColor(img2_fg, cv2.COLOR_BGR2HSV) lower_red= np.array([0,58,130]) upper_red = np.array([255,255,255]) erosion = cv2.erode(mask,kernel,iterations = 3) rmask = cv2.inRange(hsv, lower_red, upper_red) mask2 = cv2.morphologyEx(rmask, cv2.MORPH_CLOSE, kernel) final = cv2.bitwise_and(frame, frame, mask=mask2) cv2.imshow('final',final) cv2.imshow('original',frame) k = cv2.waitKey(5) &amp; 0xFF if k == 27: break cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/84087458
has title: Reading a video file VideoCapture
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1

imagedownload
tag name: imagedownload
type: Tag
tags question: http://stackoverflow.com/q/48594673

http://stackoverflow.com/comment/84090242
comment on: http://stackoverflow.com/q/48547172
type: Comment
type: QuestionComment
score: 0
has text: ok thanks ill check

http://stackoverflow.com/comment/84136569
type: AnswerComment
has text: You have to add a reference. after adding a Reference (Project Menu) to Windows Script Host Object Model. OR don't change it at all.
score: 0
comment on: http://stackoverflow.com/a/48551489
type: Comment

http://stackoverflow.com/comment/84169886
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48586179
score: 0
has text: From google vision api im getting text from image and from that text im detecting license no. Now i have to take location from text. Using regex im geeting License Id as PS 18 16373 73773 and actual text is FPS 18 16373 73773. So to add location in json file with license id. So to compare text with value so i need that logic.

http://stackoverflow.com/comment/84346821
type: AnswerComment
has text: you are welcome ! if you want all values in one row and without any description you can change the line with the .to_csv() to: pd.DataFrame(df).T.to_csv("pywu.cache.csv", index=False, header=False, sep=",")
type: Comment
comment on: http://stackoverflow.com/a/48596155
score: 0

http://stackoverflow.com/comment/84139549
comment on: http://stackoverflow.com/q/48571259
score: 0
has text: I changed it and it did nothing.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48562099
has comment: http://stackoverflow.com/comment/84158573
answer count: 2
has title: Keras : Why does Sequential and Model give different outputs?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84119916
downvote count: 0
tagged with: neural-network
upvote count: 7
tagged with: keras
has comment: http://stackoverflow.com/comment/84130735
favorite count: 0
has comment: http://stackoverflow.com/comment/84123100
has comment: http://stackoverflow.com/comment/84121185
has answer: http://stackoverflow.com/a/51200423
tagged with: keras-layer
score: 7
has comment: http://stackoverflow.com/comment/84123170
has body: I am using Keras for computing a simple sequence classification neural network. I played with the different module and I found that there are two way to create Sequential neural network. The first way is to use Sequential API. This is the most common way which I found in a lot of tutorial/documentation. Here is the code : # Sequential Neural Network using Sequential() model = Sequential() model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu', input_shape=(27 , 300,))) model.add(MaxPooling1D(pool_size=2)) model.add(LSTM(100)) model.add(Dense(len(7, activation='softmax')) model.summary() The second ways is to build de sequential neural network from "scratch" with the Model API. Here is the code. # Sequential neural network using Model() inputs = Input(shape=(27 , 300)) x = Conv1D(filters=32, kernel_size=3, padding='same', activation='relu')(inputs) x = MaxPooling1D(pool_size=2)(x) x = LSTM(100)(x) predictions = Dense(7, activation='softmax')(x) model = Model(inputs=inputs, outputs=predictions) model.summary() I trained it both with a fixed seed (np.random.seed(1337)), with the same training data and my output are different... Knowing that the only difference in the summary is the first layer of inputs with the Model API. Is there anyone that knows why this neural network are different ? And if there are not, why did i get different results ? Thanks
has answer: http://stackoverflow.com/a/61802624
tagged with: python
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/136082198
type: Question

http://stackoverflow.com/comment/84133601
has text: Added an extra column. yes, in actuality the value columns are months, so I need the % within each month. I don't want to have to iterate over every column, I'm looking for a vectorized solution.
comment on: http://stackoverflow.com/q/48567300
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84111358
type: Comment
has text: Since `arrR` and `arrB` are Numpy 2D arrays, `list(arr_ndvi)` returns instead a list of rows of the NDVI matrix, so each value in each array is the NDVI of the corresponding pixel, e.g. `arr_ndvi[0,0] == 0.44554455` is the NDVI of the top-left pixel.
type: QuestionComment
comment on: http://stackoverflow.com/q/48557613
score: 1

http://stackoverflow.com/comment/84050367
type: Comment
type: QuestionComment
has text: Got it. I had read the docs previously and thought I understood, but clearly I did not. Here is the salient point: "It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function)." I should have re-read this before posting my question. Sorry.
comment on: http://stackoverflow.com/q/48527513
score: 0

http://stackoverflow.com/a/65008965
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48569024
has body: 1 I used a custom class holding name, roman suffix and the integer value of roman suffix. 2 Used a comparator which sorts on the basis of integer value if names match. 3 romanToInt is implemented below. class Name{ String first; String roman; int num; Name(String f, String r, int n){ this.first = f; this.roman = r; this.num = n; } } List&lt;String&gt; sortRoyal(List&lt;String&gt; names){ PriorityQueue&lt;Name&gt; pq = new PriorityQueue&lt;&gt;((x,y)-&gt;{ if((x.first).compareTo(y.first)==0) return x.num - y.num; return (x.first).compareTo(y.first); }); for(String str : names){ int index = str.indexOf(&quot; &quot;); String first = str.substring(0, index); String second = str.substring(index+1); int num = romanToInt(second); pq.add(new Name(first, second, num)); } List&lt;String&gt; res = new ArrayList&lt;&gt;(); while(pq.size()!=0){ Name curr = pq.remove(); res.add(curr.first+&quot; &quot;+curr.roman); } return res; } public int romanToInt(String s) { int num = 0; for(int i =0; i&lt;s.length(); i++){ if(s.charAt(i) == 'I') num+=1; if(s.charAt(i) == 'V') { if(i&gt;=1 &amp;&amp; s.charAt(i-1) == 'I') num+=3; else num+=5; } if(s.charAt(i) == 'X') { if(i&gt;=1 &amp;&amp; s.charAt(i-1) == 'I') num+=8; else num+=10; } if(s.charAt(i) == 'L') { if(i&gt;=1 &amp;&amp; s.charAt(i-1) == 'X') num+=30; else num+=50; } if(s.charAt(i) == 'C') { if(i&gt;=1 &amp;&amp; s.charAt(i-1) == 'X') num+=80; else num+=100; } if(s.charAt(i) == 'D') { if(i&gt;=1 &amp;&amp; s.charAt(i-1) == 'C') num+=300; else num+=500; } if(s.charAt(i) == 'M') { if(i&gt;=1 &amp;&amp; s.charAt(i-1) == 'C') num+=800; else num+=1000; } } return num; }

http://stackoverflow.com/a/48506802
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: Change your file.write() function to file.write('Name:{}\nScreen-Name:{}\nCreated_at:{}\nTweet-Text:{}\nRetweeted:{}\nlanguage:{}\nLocation:{}\nTime_zone:{}'.format(tweet2.author.name, tweet2.author.screen_name, tweet2.created_at, tweet2.text, tweet2.retweeted ,tweet2.lang ,tweet2.user.location,tweet2.user.time_zone))
answers question: http://stackoverflow.com/q/48506647
type: Answer
accepted answer of: http://stackoverflow.com/q/48506647

http://stackoverflow.com/a/48519677
has body: In your DataFrame you have the y-values of the data-points and the y-values of the lines in a single line. Therefore, you could use np.where for this purpose. C = np.where(condition, A, B) A is set if the condition is True and B if the condition is False. If you want to check against the Upper99 and Lower99 lines you could achieve this as follows: sqlDF2['Outside'] = np.where((sqlDf2['Success'] &gt; sqlDf2['Upper99']*100) | (sqlDf2['Success']&lt;sqlDf['Lower99']*100), True, False) This will result in a new column containing True if the data-point lies outside of the given boundaries and False if it is inside of the boundaries.
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84034224
has comment: http://stackoverflow.com/comment/84035943
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48518881
has comment: http://stackoverflow.com/comment/84034535
has comment: http://stackoverflow.com/comment/84034074
accepted answer of: http://stackoverflow.com/q/48518881

http://stackoverflow.com/q/48623389
score: 1
has comment: http://stackoverflow.com/comment/84244011
answer count: 1
tagged with: django
has body: My question is about getting Django query result in Django-rest-framework api's response. I have the following models of Product, Attribute and Productoptions in my Django project: class Product(models.Model): productid = models.AutoField(db_column='productId', primary_key=True) productname = models.CharField(db_column='productName', max_length=200) class Attribute(models.Model): attributeid = models.AutoField(db_column='attributeId', primary_key=True) attributename = models.CharField(db_column='attributeName', max_length=200, blank=True, null=True) class Productoptions(models.Model): optionsid = models.AutoField(db_column='OptionsId', primary_key=True) optionproductid = models.ForeignKey(Product, models.DO_NOTHING, db_column='optionProductId', blank=True, null=True) optionattributeid = models.ForeignKey(Attribute, models.DO_NOTHING, db_column='optionAttributeId', blank=True, null=True) I have filled sample data in all three tables and when trying to get the products whose attribute name is nike, the following Django query perfectly worked in Python shell. Productoptions.objects.filter(optionattributeid__attributename='nike').values('optionproductid__productname') Get the result &lt;QuerySet [{'optionproductid__productname': 'nike shirt'}, {'optionproductid__productname': 'nike tracksuit'}]&gt; But the related model class query is not working in my view class ProductOptionsView(APIView): serializer_class = ProductOptionsSerializer def get(self,request): queryset = Productoptions.objects.filter(optionattributeid__attributename='nike').values('optionproductid__productname') serializer = self.serializer_class(queryset, many=True) return Response(serializer.data) I am not getting the desired result from this view. Is there any way that all Django query will simply provide result with Django-rest-framework. All get and post queries are perfectly working in Python shell. Is there any other way or DRF has its own method for it to use nested models result in rest api. I hav…
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/84243492
favorite count: 0
type: Question
has title: How to get filtered Django ORM query result in Django rest framework response
has comment: http://stackoverflow.com/comment/84244996
has comment: http://stackoverflow.com/comment/84243375
tagged with: django-models
tagged with: python
tagged with: mysql
has answer: http://stackoverflow.com/a/48624208
accepted answer: http://stackoverflow.com/a/48624208
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84243635
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84243989

http://stackoverflow.com/q/48566821
downvote count: 0
favorite count: 0
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/57189587
type: Question
upvote count: 12
type: UnansweredQuestion
has body: I think the title is self explanatory but to ask it in details, there's sklearn's method train_test_split() which works like: X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.3, stratify = Y) It means: the method will split data with 0.3 : 0.7 ratio and will try to make percentage of labels in both data equal. Is there a keras equivalent of this?
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/84133291
has answer: http://stackoverflow.com/a/51811590
tagged with: keras
has title: Is there a keras method to split data?
score: 12
has comment: http://stackoverflow.com/comment/84129920
answer count: 2
has comment: http://stackoverflow.com/comment/84130097

http://stackoverflow.com/q/48489694
tagged with: timestamp
score: 2
type: AnsweredQuestion
has body: I've being trying to convert the date below from Timestamp to float. I have already tried all functions in all orders (fromtimestamp, strftime, strptime, .date()... etc etc etc) and nothing. I have also read all related questions available on google and none works for me. Anyone could please help? The closest to a solution I got is the code below and the error states: "TypeError: an integer is required (got type Timestamp)" and I quit confident that other errors will pop up after this. The imported file can be found here: https://www.dropbox.com/s/oe0h7mu2k0vwpn2/Linx%20Revenues.xls?dl=0 import pandas as pd import datetime #Upload Data df = pd.read_excel("Linx Revenues.xls") #Rename Columns df.columns = ['Date', 'Gross'] #Adjust Dates for index, row in df.iterrows(): df['Date'][index] = datetime.datetime(df['Date'][index], '%d/%m/%y').date().strftime('%d/%m/%Y') df["Date"][index] = float(datetime.strptime(df["Date"][index], '%d/%m/%Y').date().strftime('%Y%m%d'))
tagged with: pandas
downvote count: 0
answer count: 1
has title: Timestamp date format impossible to convert to float
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/48489784
tagged with: datetime
has answer: http://stackoverflow.com/a/48489784
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83973671

http://stackoverflow.com/q/48638868
accepted answer: http://stackoverflow.com/a/48795070
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: blockly
has title: Error blockly on compilation
has body: I'm trying to compile blockly, I compile the file blockly_uncompressed.js well but the others compressed do not compile them. I do not know where the error may be. This is a development that was left two years ago, and I have retaken it. The error I get is the following: Traceback (most recent call last): File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner self.run() File "build.py", line 176, in run self.gen_core() File "build.py", line 208, in gen_core self.do_compile(params, target_filename, filenames, "") File "build.py", line 273, in do_compile json_data = json.loads(json_str) File "C:\Python27\lib\json\__init__.py", line 339, in loads return _default_decoder.decode(s) File "C:\Python27\lib\json\decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded I have never played blockly and I do not know where this can come from
type: Question
has answer: http://stackoverflow.com/a/48795070
tagged with: javascript
tagged with: python

http://stackoverflow.com/q/48499885
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83993375
favorite count: 0
has comment: http://stackoverflow.com/comment/84177092
has comment: http://stackoverflow.com/comment/84006427
has comment: http://stackoverflow.com/comment/84175382
type: Question
has comment: http://stackoverflow.com/comment/83993949
has comment: http://stackoverflow.com/comment/83993140
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84175155
has title: cx_freeze python making executable file
has body: I do not know whether we can turn the python modules into executable file for window , and it can then write or modify a file in window (without the need of moving that file into the setup directories at the beginning). That mean when I run the application, some text file in D directory will be modified for example. Is it possible? Thank you very much
has comment: http://stackoverflow.com/comment/84175478
tagged with: executable

http://stackoverflow.com/a/48593494
answers question: http://stackoverflow.com/q/48593345
type: Answer
has body: Why not just use pandas? df = pd.DataFrame(grades).set_index(0).iloc[1:].mean(axis=1).astype(int) Output: John 90 McVay 53 Rita 64 Ketan 54 Saranya 70 Min 96 or list(df.values) Output: [90, 53, 64, 54, 70, 96]
score: 0
has comment: http://stackoverflow.com/comment/84184329

http://stackoverflow.com/q/48615775
accepted answer: http://stackoverflow.com/a/48624003
has title: regarding sampling a two dimensional array and let the sampling array has three-dimension shape
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/48624003
has comment: http://stackoverflow.com/comment/84229651
tagged with: scipy
favorite count: 0
has body: There are two numerical arrays, train_wiggle and train_spike. Both of which have shape like (1000,101). Physically, they respectively represent 1000 points where each point has 101 features. I would like to generate two corresponding random samples, wiggle_sample and spike_sample from train_wiggle and train_spike respectively. The sample size is 10. In specific, I want wiggle_sample and spike_sample have shape (10,101,1). This is what I do def generate_train_samples(): sample_id = np.random.randint(low=0,high=999,size=10) input_seq = np.take(train_wiggle,sample_id,axis=0) output_seq = np.take(train_spike,sample_id,axis=0) return input_seq, output_seq # in shape: (batch_size, time_steps, feature_dim) x,y = generate_train_samples() When calling the above function, the x and y have shape (10, 101), instead of (10,101,1) as I want. How to modify the code?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84229883
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7

memoization
type: Tag
tags question: http://stackoverflow.com/q/48552832
tag name: memoization
tags question: http://stackoverflow.com/q/48544411
tags question: http://stackoverflow.com/q/48600127

http://stackoverflow.com/a/48533596
score: 0
accepted answer of: http://stackoverflow.com/q/48529905
has body: If you want plot an implicit equation curve, you can use pyplot.contour(), here is an example: np.random.seed(1) w = np.random.randn(6) def f(x, y, w): return w[0] + w[1]*x**2 + w[2]*y**2 + w[3]*x*y + w[4]*x + w[5]*y X, Y = np.mgrid[-2:2:100j, -2:2:100j] pl.contour(X, Y, f(X, Y, w), levels=[0])
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84064014
has comment: http://stackoverflow.com/comment/84100186
type: Answer
answers question: http://stackoverflow.com/q/48529905

http://stackoverflow.com/q/48505470
has comment: http://stackoverflow.com/comment/84005706
has comment: http://stackoverflow.com/comment/84005050
duplicate of: http://stackoverflow.com/q/43951558
has title: Pandas DataFrame.drop_duplicates() missing something?
tagged with: python
has comment: http://stackoverflow.com/comment/84004996
has answer: http://stackoverflow.com/a/48505568
accepted answer: http://stackoverflow.com/a/48505568
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84005058
downvote count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/43951558
answer count: 1
favorite count: 0
has body: I am relatively new to Python, and even newer to pandas. I am trying to develope a simple web scraper to search Indeed for job postings. This is mostly about learning the language, but if I find a new job from it, all the better. The nature of the data means there are going to be a lot of duplicates, and that is what I have seen so far. As a result, I wanted to remove the duplicates before sending the dataframe to a .csv file. I tried implementing the DataFrame.drop_duplicates() in the code i was working on, but it didnt work. So i created a seperate script to only test the drop.duplicates() method without having to go through all the other code first to make sure i got the syntax right and it functions as expected. This is what I have: import pandas as pd df=pd.DataFrame({'A':['1', '2', '3'], 'B':['1', '2', '4']}) print(df) df1=df.drop_duplicates() print(df1) My expectation was that drop_duplicates() would remove the first two rows from df and assign the result to df1. Except, they both were the same. So then I tried the following figuring the default index column applied by the DataFrame was interfering: import pandas as pd df=pd.DataFrame({'A':['1', '2', '3'], 'B':['1', '2', '4']}) print(df) df1=df.drop_duplicates(subset=["A", "B"]) print(df1) That didnt work either. There were a couple other iterations of the same code I tried involving 'keep' and 'inplace' but the result is always a dataframe that is the same as the original. What am I missing? I am expecting it to remove the first two rows since they are the same. Are they not? Or am I just expecting the wrong thing...
type: Question
has comment: http://stackoverflow.com/comment/84005537
tagged with: pandas

http://stackoverflow.com/comment/84035189
has text: You are multiplying string 40 times "cost = days * 40". days == "Pittsburgh"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48520244
score: 0

http://stackoverflow.com/comment/84066670
has text: Which graphical environment are you using on Debian? This is probably more related to the GUI (I'm guessing Gnome) and its configuration, than anything specifically about Python or even generally programming-related.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48535593
score: 0

http://stackoverflow.com/comment/84032244
type: Comment
has text: Exactly ...who ever downvoted may not be understand the full question
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48518519

http://stackoverflow.com/comment/84235248
type: Comment
comment on: http://stackoverflow.com/a/48618766
type: AnswerComment
has text: You should point out that this should be done in the `main()` section not the `__init__()`, where the binding would (probably?) have no effect.
score: 0

http://stackoverflow.com/q/48527252
answer count: 2
type: UnansweredQuestion
upvote count: 18
tagged with: python
tagged with: flask
has title: Tensorflow Serving: When to use it rather than simple inference inside Flask service?
has answer: http://stackoverflow.com/a/51990061
tagged with: tensorflow-serving
score: 17
has answer: http://stackoverflow.com/a/51959439
has body: I am serving a model trained using object detection API. Here is how I did it: Create a Tensorflow service on port 9000 as described in the basic tutorial Create a python code calling this service using predict_pb2 from tensorflow_serving.apis similar to this Call this code inside a Flask server to make the service available with HTTP Still, I could have done things much easier the following way : Create a python code for inference like in the example in object detection repo Call this code inside a Flask server to make the service available with HTTP As you can see, I could have skipped the use of Tensorflow serving. So, is there any good reason to use Tensorflow serving in my case ? If not, what are the cases where I should use it ?
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/84214658
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48602239
has text: Brian, that's a great question! The default User model that Django provides simply won't allow me to accomplish the goals of the web app I'm building. Granted, Django provides some good user based functionality out of the box, but in this case, it won't suffice.

http://stackoverflow.com/a/66179698
type: Answer
answers question: http://stackoverflow.com/q/48583567
score: 1
downvote count: 0
upvote count: 1
has body: Another option using a comprehension list: [dict(v) for _, v in df.iterrows()]

http://stackoverflow.com/comment/84210959
comment on: http://stackoverflow.com/a/48597358
score: 0
type: Comment
type: AnswerComment
has text: When i write "numpy.array" im referring to numpy module or numpy class ?

http://stackoverflow.com/q/48602954
has body: As the title says, I'm trying to generate a list of datetimes corresponding to the occurrences of a specific day of the month between two dates. So given a start date, an end date, and a day of the month, I want to see every occurrence of that day of the month: from datetime import datetime end_date = datetime(2012, 9, 15, 0, 0) start_date = datetime(2012, 6, 1, 0, 0) day_of_month = 16 dates = "magic code goes here" dates would then hold an array as such: dates == [ datetime(2012, 6, 16, 0, 0), datetime(2012, 7, 16, 0, 0), datetime(2012, 8, 16, 0, 0) ] The issue I'm running into is the number of checks I have to perform. First I have to check if it's the start year, if so, then I have to start at the beginning month, but if the day of the month is before the start date, then I have to skip that month. This same thing applies for the end of the period. Not to mention I have to check if the period starts and ends in the same year. All in all it's turning into quite a mess of nested if and for statements. Here is my solution: import numpy as np for year in np.arange(start_date.year, end_date.year + 1): for month in np.arange(1, 13): date = datetime(year, month, day_of_month, 0, 0) if start_date &lt; date &lt; end_date: dates.append(date) Is there a more Pythonic way to accomplish this?
favorite count: 0
answer count: 2
has title: Reference each occurence of a day of the month given start datetime and an end datetime
upvote count: 2
downvote count: 0
type: Question
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48603044
accepted answer: http://stackoverflow.com/a/48603111
has answer: http://stackoverflow.com/a/48603044
tagged with: datetime
has answer: http://stackoverflow.com/a/48603111
tagged with: python

http://stackoverflow.com/q/48496001
upvote count: 0
has comment: http://stackoverflow.com/comment/84015237
has body: I am trying to deploy a simple "Hello World" Python app in Heroku, but it told me that the deployment is not compatible with buildpack. I've tried to search for the solution in previous similar situation, and did all stuff (e.g. including runtime.txt, requirements.txt etc.) that others can finally solve their problems, but I still have this error message. Would you pls assist to tell why that happens and how I can get it solved? Many thx! What I did:- Created hello_4.py In cmd, go to the respective folder, and run “python hello_4.py” and use browser to go to http://localhost:5000/ Hello world message successfully appears Ctrl+C to stop the localhost $git init saw the .git folder created $git add . $git commit -m "initial commit 4" $pip freeze > requirements.txt Created Procfile in 1 line: web: gunicorn hello_4:app Created runtime.txt in 1 line: python_version = "3.6.3" $heroku create mthd010 --buildpack heroku/python Successful without error message. Refreshed dashboard in Heroku website, and saw that mthd010 app was created $git push heroku master [error message appears] My error message: Image 1 requirements.txt: Image 2 runtime.txt: python_version = "3.6.3" Procfile: web: gunicorn hello_4:app hello_4.py: from flask import Flask app = Flask(__name__) @app.route('/') def source(): html = 'Hello World!' return html if __name__ == '__main__': app.run()
has title: Python Heroku App Deployment - not compatible with buildpack
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: git
favorite count: 0
type: Question
tagged with: heroku
downvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83985204
has answer: http://stackoverflow.com/a/48653494

http://stackoverflow.com/comment/84222404
type: Comment
has text: @poke Answers are not required to adhere to bad design restrictions posed by questions. Stating that they're bad and offering the better alternative is the *preferred* way to answer. As a 173k user, you should know better than to promote bad code.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48612766

http://stackoverflow.com/a/72909880
has body: The accepted answer will not work when trying to rename the layers in tensorflow.keras. As seen in this question, layer.name cannot be overriden, and layer._name should be used instead. If you're working with tensorflow, try adapting the last part of @jfk's answer to: for i, layer in enumerate(model1.layers): layer._name = 'layer'+str(i)+'_model1'
score: 0
has comment: http://stackoverflow.com/comment/128777380
answers question: http://stackoverflow.com/q/48595625
type: Answer

http://stackoverflow.com/comment/84205518
has text: `max(Tscore[i])` returns the highest of a single value which doesn't make much sense.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48604403

http://stackoverflow.com/q/48641340
favorite count: 0
type: Question
answer count: 0
has body: As I used Solr for search backend, and once my product get index and now the second time when I add new products and change price after index created that product not being search in and sorting of price also not worked for new change ( i need to rebuild index then start the java server then will work properly ), is there any other solution for the same . I am using Solr 4.7.2.
has comment: http://stackoverflow.com/comment/84281788
tagged with: django
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84310891
has title: when i am adding new product or modifying the record it is not showing the result set in search after building index in django oscar
upvote count: 2
tagged with: solr
has comment: http://stackoverflow.com/comment/84321523
score: 1
has comment: http://stackoverflow.com/comment/86268406
downvote count: 1
tagged with: django-oscar

http://stackoverflow.com/comment/84068628
type: QuestionComment
has text: Well, we can't know what is `data_dim` unless you specify the line where it is initialized. But my bet would be that `data_dim = whatever_input_matrix_you_have.shape()` which is the dimensions of your matrix (`m * n`). `x_train` only seems to be random generated numbers with the size of your real data, in order to initialize your ML model to show you the behavior (as you said : dummy training).
comment on: http://stackoverflow.com/q/48536676
score: 0
type: Comment

http://stackoverflow.com/comment/132593305
score: 1
has text: Looks like your ImageExporter link is out of date: https://pyqtgraph.readthedocs.io/en/latest/user_guide/exporting.html
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48561092

http://stackoverflow.com/comment/84113725
has text: This code was not executed, without any error message or exception. It just "doesn't work" :)
comment on: http://stackoverflow.com/q/48558805
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/84024342
score: 0
comment on: http://stackoverflow.com/q/48513900
type: QuestionComment
type: Comment
has text: Besides, Cloudera does not offer Nifi. Don't know why you tagged it. Given that the README uses Pandas, and no reference to Hadoop, that API doesn't need to connect to Hadoop. You download a file and upload it to HDFS, or Google Cloud Storage

http://stackoverflow.com/q/48519894
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48520028
tagged with: pandas
score: 1
upvote count: 1
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48520069
has body: I want to use a dictionary in order to create a new field/column in a dataframe. If the values don't match, I want the value to be set to 'NA' or something similar. So, I am using something like this: #Creation of a dictionary after combining two lists country_Codes = ['us', 'de', 'fr'] values = ['US', 'EU', 'EU'] dictionary = dict(zip(country_Codes, values)) df['new'] = df['Country_Code'].map(dictionary, na_action=None) and it creates the new column normally when I export everything to a CSV. The problem is that it skips the non-matched rows. My script excludes some rows if there is no match from the dictionary. I thought the issue was related to this line: na_action='ignore' Here is an example code I used in jupyter where I created temporarily the s and d series: s = pd.Series(['us', 'de', 'random1','random2', 'fr', 'random3']) d = pd.Series(['us', 'de', 'random1','random2', 'fr', 'random3']) #Creation of a dictionary after combining two lists country_Codes = ['us', 'de', 'fr'] values = ['US', 'EU', 'EU'] dictionary = dict(zip(country_Codes, values)) a = s.map(dictionary, na_action=None) b = d.map(dictionary, na_action='ignore') and this is what I can see after printing: My first question is how do I see the same results? It seems as if the na_action does not apply. Secondly, how can I keep the rows in a more complex dataframe with multiple columns? I checked that the type is correct after printing the type(): class 'pandas.core.frame.DataFrame' Is there a way to keep the rows after there is no match for this field (Country_Code) with the dictionary values? Also, is there a way to print the rows where the field (Country_Code) does not have a match with the dictionary values?
downvote count: 0
has answer: http://stackoverflow.com/a/48520069
has title: Python: do not exclude rows after map(dictionary)
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/48520028

http://stackoverflow.com/comment/84181155
comment on: http://stackoverflow.com/q/48591898
score: 0
has text: pickle does not handle functions well
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84132542
score: 0
type: AnswerComment
has text: @Djangonewbie just use a `dict`
type: Comment
comment on: http://stackoverflow.com/a/48567658

latitude-longitude
tags question: http://stackoverflow.com/q/48590140
tag name: latitude-longitude
type: Tag

http://stackoverflow.com/a/48533589
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84172125
has body: @duhaime There is an installer for OSX on the official wxPython web-site. Just download it and install. You don't need to play with anaconda just to install and run such a simple application.
has comment: http://stackoverflow.com/comment/84121094
type: Answer
answers question: http://stackoverflow.com/q/48531006
score: 0
has comment: http://stackoverflow.com/comment/84143511
has comment: http://stackoverflow.com/comment/84129420

http://stackoverflow.com/comment/83981870
has text: `if number not in '10':` would be a lot more readable/pythonic in my opinion.
type: AnswerComment
comment on: http://stackoverflow.com/a/48494394
score: 1
type: Comment

http://stackoverflow.com/comment/84142364
type: QuestionComment
comment on: http://stackoverflow.com/q/48572764
score: 1
has text: `GET` requests can only send parameters through the query string.
type: Comment

http://stackoverflow.com/a/48612656
has comment: http://stackoverflow.com/comment/84223614
type: Answer
answers question: http://stackoverflow.com/q/48611906
accepted answer of: http://stackoverflow.com/q/48611906
score: 0
type: AcceptedAnswer
has body: If, as it can be understood by the re-writing, you are creating the s3 object inside the function, the reason for non-working can be the fact that you are calling read() multiple times on the same file object. The first call returns the whole content of the file, but moves the "position" of the file object to the end, so subsequent calls of the same function return nothing - as there's nothing more to read. Reading the value only once just works, as would seek()ing back to the beginning of the file and reading again each time. I'd advise to read the value only once, to avoid unnecessary I/O and related overhead.
has comment: http://stackoverflow.com/comment/84231950

http://stackoverflow.com/q/48619553
has comment: http://stackoverflow.com/comment/84235871
has body: I don't know the type of this algmaybe it's famous.. I have a liste of this form L = [ ["a"] , ["b"] , ["c"] ] , [ ["d"] , ["e"] , ["f"] ] , ["g"], ["h"], ["i"] ] ,[ ["j"] , ["k"] , ["l"] ] where the letter are words and the length of L could be from 2 to 50 elements but inside the list are always 3 elements long. And I want to create a list who build all this string : "adgj" "adgk" "adgl" "adhj" "adhk" "adhl" "adij" "adik" "adil" "aegj" ect all the way to "cfil" could someone tell me what to do or where to look for? Thank's a lot for your help..
favorite count: 0
tagged with: search
type: Question
accepted answer: http://stackoverflow.com/a/48619822
answer count: 2
has title: building string from big list of words
upvote count: 2
has answer: http://stackoverflow.com/a/48619822
downvote count: 0
tagged with: python
tagged with: design-patterns
possible better answer: http://stackoverflow.com/a/48619710
has answer: http://stackoverflow.com/a/48619710
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/48524544
has comment: http://stackoverflow.com/comment/84045420
has comment: http://stackoverflow.com/comment/84045225
has body: The problem is that you have included the password reset urls inside the polls app. That means that you would reverse the URL with 'polls:password_reset_done' instead of 'password_reset_done'. Since you don't want to have to edit Django's password reset views, The easiest fix would be to move the password reset URLs out of polls/urls.py and into your main urls.py (the one in the same directory as settings.py)
score: 0
has comment: http://stackoverflow.com/comment/84045658
has comment: http://stackoverflow.com/comment/84045343
has comment: http://stackoverflow.com/comment/84045773
type: Answer
answers question: http://stackoverflow.com/q/48524468

http://stackoverflow.com/comment/84216329
type: Comment
type: QuestionComment
has text: If it is just for your own use, you can represent your data as you like. Different thing, if it is published. You could treat positive and negative values as [two groups in your plot, so they can have different scales](https://stackoverflow.com/a/7734614/8881141)
comment on: http://stackoverflow.com/q/48609442
score: 2

http://stackoverflow.com/comment/84141172
score: 0
has text: But in Store.GetDefaultFolder how do I specify the specific email addresses inbox
comment on: http://stackoverflow.com/a/48543958
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48591341
has title: How to install python on windows without admin privilege
upvote count: 7
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84180221
answer count: 2
type: UnansweredQuestion
has body: I was looking to install python on my school computer so that I can code at school, but I don't have any admin privileges. So far I've downloaded python using msiexec /a python-2.7.14.msi /qb TARGETDIR=C:\filepath Then I set the path to python.exe using rundll32 sysdm.cpl,EditEnvironmentVariables Now when I run python in the command prompt I get This program is blocked by group policy. For more information, contact your system administrator. Is there a way around this, or will I not be able to run python without admin privileges? Thanks!
has answer: http://stackoverflow.com/a/48591377
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/64695759
has comment: http://stackoverflow.com/comment/97418327
tagged with: python-2.7

http://stackoverflow.com/a/49072005
has body: You can use nlp = spacy.load('/tmp/model') to load your model after you saved it to disk. Doing what you did apparently only loads the binary data according to the Spacy documentation (https://spacy.io/usage/training#section-saving-loading)
answers question: http://stackoverflow.com/q/48524817
upvote count: 14
downvote count: 0
score: 14
type: Answer

http://stackoverflow.com/a/48634653
has comment: http://stackoverflow.com/comment/84268343
downvote count: 0
answers question: http://stackoverflow.com/q/48634622
has body: Keep in mind that the input from raw_input() will be a string, so when comparing, use: increase != "1" Also I think that you are looking for this actually: increase != "1" and increase != "2" Notice that I've changed the or by an and To use int as input, you can do something like: int(raw_input("Insert number here"))
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84266501

http://stackoverflow.com/a/48648367
type: AcceptedAnswer
downvote count: 0
upvote count: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/48631546
score: 4
answers question: http://stackoverflow.com/q/48631546
has body: UPDATE This capability was added in Bokeh 0.12.16, you can now do: p.xaxis.major_label_orientation = "vertical" p.xaxis.subgroup_label_orientation = "normal" p.xaxis.group_label_orientation = 0.8 It's not possible in Bokeh 0.12.13, the orientation of labels for levels other than the first one is always parallel: https://github.com/bokeh/bokeh/blob/0.12.13/bokehjs/src/coffee/models/axes/categorical_axis.coffee#L89-L92 You're welcome to create a GitHub issue with a feature request if you need this functionality.

http://stackoverflow.com/q/48515686
tagged with: python
has answer: http://stackoverflow.com/a/48515709
has title: How to pick elements of specific index in python?
favorite count: 0
type: Question
has body: Say, A = [1,2,3,4] What I'm trying to get is the specific elements of A, e.g. only first and third element. So the output should look like this: [1, 3] How do I do this? print(A(0,2)) is not the right command I know, so looking for the right command.
has answer: http://stackoverflow.com/a/48515726
has answer: http://stackoverflow.com/a/48515761
upvote count: 2
type: UnansweredQuestion
downvote count: 1
answer count: 3
score: 1

http://stackoverflow.com/q/48600308
type: Question
linked to: http://stackoverflow.com/q/20625582
answer count: 2
linked to: http://stackoverflow.com/q/14463277
type: UnansweredQuestion
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/20625582
has answer: http://stackoverflow.com/a/48600433
has answer: http://stackoverflow.com/a/48600927
tagged with: pandas
score: 1
tagged with: group-by
tagged with: dataframe
tagged with: python
has body: My need is to get a new column created in pandas dataframe which is count and sum based on grouping. I am using method chaining like below. df['total_sum']=df.groupby('column1')['column 2'].transform('sum') df['total_cnt']=df.groupby('column1')['column 2'].transform('count') but I am getting the setting with copy warning. I am getting correct results but I want to avoid warning. I am trying workarounds but could not get one.
has title: setting with copy warning in python method chaining with df.groupby.transform()
has comment: http://stackoverflow.com/comment/84202369
favorite count: 0

http://stackoverflow.com/q/48593155
has answer: http://stackoverflow.com/a/48594509
type: AnsweredQuestion
score: 0
tagged with: python
has body: Always image cannot be sent normally. I wrote in views.py def photo(request): d = { 'photos': Post.objects.all(), } return render(request, 'registration/accounts/profile.html', d) def upload_save(request): form = UserImageForm(request.POST, request.FILES) if request.method == "POST" and form.is_valid(): data = form.save(commit=False) data.user = request.user data.save() return render(request, 'registration/photo.html') else: return render(request, 'registration/profile.html') in profile.html {% csrf_token %} in forms.py class UserImageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = ImageAndUser fields = ('image',) n my system,I can send 3 images at most each one time, so there are 3 blocks.Now always program goes into else statement in upload_save method, I really cannot understand why always form.is_valid() is valid.When I send only 1 image, same thing happens.So the number of image does not cause the error. When I print out print(form.errors) ,it is image This field is required How should I fix ?What is wrong in my code?
has title: Always image cannot be sent normally What is wrong in my code?
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/84184766
tagged with: django
accepted answer: http://stackoverflow.com/a/48594509

http://stackoverflow.com/a/48605370
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48605313
downvote count: 0
upvote count: 1
has body: Try to replace get_price = BtcAPI(url, api_id, json_tree) with get_price = BtcAPI(self.url, self.api_id, self.json_tree)

http://stackoverflow.com/a/48512785
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48512393
score: 2
answers question: http://stackoverflow.com/q/48512393
has body: Here is one way to achieve this: df = pd.DataFrame( { 'xyz': [1, 2, 3], 'ijk': [1, 2, 3], 1: [1, 2, 3], 'val1': [1, 2, 3], 'test1': [1, 2, 3] } ) df.loc[:, ~((df.columns.astype(str).str.contains('\d$')) &amp; (df.columns.astype(str).str.len() &gt; 1))] # 1 ijk xyz #0 1 1 1 #1 2 2 2 #2 3 3 3 Your code in the comments produced an error because you were missing parentheses around the two boolean Series. You could have written it as: df.columns[(~df.columns.astype(str).str.match("(.*\d.*)")) &amp; (df.columns.astype(str).str.len() &gt; 1)] #Index([u'ijk', u'xyz'], dtype='object') But this would have actually given you the wrong answer. Instead, your logic could be modified slightly to: df.columns[~((df.columns.astype(str).str.match("(.*\d)")) &amp; (df.columns.astype(str).str.len() &gt; 1))] #Index([1, u'ijk', u'xyz'], dtype='object')

http://stackoverflow.com/q/48637793
type: Question
tagged with: numpy
upvote count: 2
has title: matplotlib ignore missing data
has body: The question has already been asked and has a good solution using masks. Asking again because I'd like to know if is there a way to make matplotlib handle missing data on its own, something like if any of x or y data is missing just ignore it and draw a line through it. Here's some sample code: import numpy as np import matplotlib.pyplot as plt plt.figure() x = np.arange(0, 100, 10) y = np.random.randint(0, 10, 10) plt.plot(x,y, "*-") x_nan = np.arange(100) y_nan = np.asarray([np.nan] * 100) y_nan[::10] = np.random.randint(0, 10, 10) plt.plot(x_nan,y_nan,"*-") mask = np.isfinite(y_nan) plt.plot(x_nan[mask],y_nan[mask],"--") plt.show() The second plot draws dots only for the non-nan points, but no line through them. The easiest way to make it look like the first is to define a mask like in the third plot. I'd like to know if is there a way to make matplotlib behave like this automatically without the extra mask.
answer count: 1
linked to: http://stackoverflow.com/q/14399689
tagged with: missing-data
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48640423
has answer: http://stackoverflow.com/a/48640423
score: 1
tagged with: matplotlib
tagged with: python
favorite count: 0

yaml
tags question: http://stackoverflow.com/q/48545794
tags question: http://stackoverflow.com/q/48580836
tags question: http://stackoverflow.com/q/48561818
tags question: http://stackoverflow.com/q/48551508
tag name: yaml
type: Tag
tags question: http://stackoverflow.com/q/48645391

http://stackoverflow.com/comment/95146721
type: AnswerComment
score: 0
has text: You're absolutely right on that. That would be the proper way to debug what's going on. Using print is just a hacky way to quickly asses, in this case, what the response URLs are looking like.
type: Comment
comment on: http://stackoverflow.com/a/53884772

tensorflow-estimator
tags question: http://stackoverflow.com/q/48617656
tag name: tensorflow-estimator
tags question: http://stackoverflow.com/q/48614529
type: Tag
tags question: http://stackoverflow.com/q/48640599

http://stackoverflow.com/q/48537025
score: 1
has comment: http://stackoverflow.com/comment/84069377
tagged with: python
has comment: http://stackoverflow.com/comment/84068944
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84069218
has body: I created a management command and there I want to download the csv file from ftp and update the database if necessary. The code that I have is as follows: class Command(BaseCommand): @staticmethod def update_database(row): code = row['CODE'] vat_number = row['BTWNR'] if code != "" and vat_number != "": # pdb.set_trace() print("Code: {0} --- BTW: {1}").format(code, vat_number) def read_file(self): path_to_relations_csv_file = "{0}/{1}".format(destination, file_name) with open(path_to_relations_csv_file) as csvfile: relations_reader = csv.DictReader(csvfile, delimiter=';') for row in relations_reader: self.update_database(row) def handle(self, *args, **options): # Open ftp connection ftp = ftplib.FTP(ftp_host, ftp_username, ftp_password) try: ftp.cwd(source) # Goes to remote folder where the relations file is os.chdir(destination) # Goes to local folder where the relations file will be downloaded print("Switched to the directory successful. Current directory: {}".format(destination)) except OSError: pass except ftplib.error_perm: print("Error: could not change to {0}".format(source)) sys.exit("Ending Application") try: # Get the file relations = open(file_name, "wb") # Opens the remote file ftp.retrbinary('RETR {0}'.format(file_name), relations.write) # Writes to the local file print("File {0} downloaded successfully.".format(file_name)) relations.close() # Closes the local file print("Local file closed.") ftp.quit() # Closes the ftp connection print("FTP Connection quited.") try: self.read_file() except: print("Error: Unable to read the file.") except: print("Error: File {0} could not be downloaded.".format(file_name)) But in read_file method the for loop gives me the error. If I place pdb.set_trace()before for loop I can see that relations_reader is &lt;csv.DictReader object at 0x10e67a6a0&gt;, thus it seems ok, but if I try to loop over it it goes to the except and it execute print("Error: Unable to read the file.") The path are correct. If the same code is execut…
has comment: http://stackoverflow.com/comment/84069065
has comment: http://stackoverflow.com/comment/84069044
has title: How to loop through csv file in Python/Django
downvote count: 0
answer count: 1
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/84069253
favorite count: 0
accepted answer: http://stackoverflow.com/a/48537464
type: Question
has answer: http://stackoverflow.com/a/48537464
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/48596759
score: 0
has body: The error is in the line score = 0, by doing thisscore stops being an instance of NumericProperty class to become an int instance, and therefore it stops generating events when it is modified. from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.lang.builder import Builder from kivy.properties import NumericProperty Builder.load_string(''' &lt;MainWindow&gt;: orientation: "vertical" Label: id: lb_score text: "Score " + str(root.score) Button: size_hint_y: 0.1 text: "+1" on_press: root.add_score() ''') class MainWindow(BoxLayout): score = NumericProperty(0) def add_score(self): self.score += 1 class TestApp(App): def build(self): return MainWindow() if __name__ == "__main__": TestApp().run()
has comment: http://stackoverflow.com/comment/84192182
type: Answer
answers question: http://stackoverflow.com/q/48596277

http://stackoverflow.com/a/48583271
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/84163781
has comment: http://stackoverflow.com/comment/84165132
downvote count: 0
answers question: http://stackoverflow.com/q/48583142
has comment: http://stackoverflow.com/comment/84163289
has body: The example in itself is useless. In fact it mocks the wrong thing. Mocking should be used to replace things like services/databases etc. For example: mocking the requests.get would be totally fine: you already assume that the requests library works, so during the test you can just avoid to perform the HTTP call and simply return the page content. In this way you'd be testing the logic of the posts method, without taking account what requests does (even if in this case it is extremely simple). Certainly it does not make sense to mock the class you are testing. You should mock its dependencies!
upvote count: 5

http://stackoverflow.com/q/48616893
tagged with: deep-learning
upvote count: 2
has answer: http://stackoverflow.com/a/48617124
has comment: http://stackoverflow.com/comment/84233546
answer count: 1
has comment: http://stackoverflow.com/comment/84232825
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84231709
tagged with: gpu
type: UnansweredQuestion
tagged with: python
has body: Hi I am new to Tensorflow and I am assigned a task to change the "Demo.py" in a Github project "tf-faster-rcnn" to achieve multi-GPU inferencing. And this is generally what I plan to do (suppose the number of images I have is the same as the number of GPUs, and I will use a queue which is not illustrated here for simplicity reason): for id, gpu in gpu_dict: with tf.device(gpu): im_detect(images[id]) The "im_detect" function is provided in the the source file (I can straight away call it) and it contains some non-GPU code (like conditions and data preparation) def im_detect(sess, net, im): blobs, im_scales = _get_blobs(im) assert len(im_scales) == 1, "Only single-image batch implemented" im_blob = blobs['data'] blobs['im_info'] = np.array([im_blob.shape[1], im_blob.shape[2], im_scales[0]], dtype=np.float32) _, scores, bbox_pred, rois = net.test_image(sess, blobs['data'], blobs['im_info']) boxes = rois[:, 1:5] / im_scales[0] scores = np.reshape(scores, [scores.shape[0], -1]) bbox_pred = np.reshape(bbox_pred, [bbox_pred.shape[0], -1]) if cfg.TEST.BBOX_REG: # Apply bounding-box regression deltas box_deltas = bbox_pred pred_boxes = bbox_transform_inv(boxes, box_deltas) pred_boxes = _clip_boxes(pred_boxes, im.shape) else: # Simply repeat the boxes, once for each class pred_boxes = np.tile(boxes, (1, scores.shape[1])) return scores, pred_boxes Since I have never played with GPU before and I am a newbie to Tensorflow, I would like to ask is it okay to assign each GPU such a function call in Tensorflow? ----------------below is updated------------------------ I know there's a "alow_soft_placement" option in Tensorflow and that assigned those non-GPU code to CPU, but when there are multiple GPUs, how can one CPU handle those requests from all the GPUs? Should I create a CPU thread for each GPU?
score: 2
has comment: http://stackoverflow.com/comment/84232155
has title: Can CPU code exist under "with tf.device(gpu_id) :" in multiple GPU case?

http://stackoverflow.com/q/48642537
has comment: http://stackoverflow.com/comment/84281499
type: AnsweredQuestion
downvote count: 4
answer count: 1
has body: I have a csv file with columns containing pixel values as shown in the image. I want to read/access each value, I tried using numpy.genfromtxt but cudn't access the values. csv file snapshot
has title: How to access csv file values in python?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48642789
has comment: http://stackoverflow.com/comment/84281514
linked to: http://stackoverflow.com/q/41585078
has answer: http://stackoverflow.com/a/48642789
upvote count: 0
has comment: http://stackoverflow.com/comment/84281524
tagged with: python
score: -4
has comment: http://stackoverflow.com/comment/84281489
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/48494543
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83982237
has title: Flask - jinja2.exceptions.UndefinedError: 'index' is undefined
has body: it's a just simple task of a flask that picks jpg format file from user & saves to the particular folder but it gives me this error: jinja2.exceptions.UndefinedError: 'index' is undefined this is my Flask Code: import os from flask import Flask, render_template, request app = Flask(__name__) app_root = os.path.dirname(os.path.abspath(__file__)) @app.route("/") def index(): target = os.path.join(app_root, 'txt/') print(target) if not os.path.isdir(target): os.mkdir(target) for file in request.files.getlist("mp3_file"): print(file) file_name = file.filename destination = '/'.join([target, file_name]) print(destination) file.save(destination) return render_template('index.html') if __name__ == '__main__': app.run(debug=True) & this is my HTML Code(this code could have Bugs but right now flask showing error): Title Upload Your Audio file here: {% if file %} {% else %} {% endif %}
has comment: http://stackoverflow.com/comment/83982288
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48494634
answer count: 1
upvote count: 1
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/48494634

http://stackoverflow.com/comment/84245541
score: 0
comment on: http://stackoverflow.com/a/48622080
type: AnswerComment
type: Comment
has text: The scroll bar is now visible using `.1` as `pos_hint_y`. It briefly flashes as active then fades to inactive. I cannot scroll using `bars` or `content`. Using `pos_hint: 1, .1` designates the scrollview to 1/10th of the screen space, forcing all `GridLayout` content to the bottom of the screen and below. :(

http://stackoverflow.com/q/48628493
score: 1
tagged with: plotly
linked to: http://stackoverflow.com/q/32034689
downvote count: 0
upvote count: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/113584513
type: UnansweredQuestion
has body: I'm currently trying to set up a jupyter notebook that has some plotting functionality. For the latter, I want to test plotly, the data is coming from a PostgreSQL server. I fetch the data directly into a pandas dataframe using df = pd.read_sql(query.statement, query.session.bind). Now, I want to plot multiple time series into one single plot. So x-axis is a series of datetime objects (df['timestamp']) and y are floats (df['data']). Plotting two datasets from different data frames works like this: import pandas as pd import plotly.graph_objs as go import plotly.offline as py trace1 = go.Scatter(x = df1['timestamp'],y = df1['data']) trace2 = go.Scatter(x = df2['timestamp'],y = df2['data']) data = [trace1, trace2] fig = dict(data=data) py.iplot(fig) The data represents two measurement time series. The two datasets are recorded on different days, but I'm interested in a temporal comparison. So my idea was to remove a temporal bias (first timestamp df['timestamp'][0] or earliest timestamp min(df['timestamp'])) by subtraction: df['timestamp'] = df['timestamp'] - df['timestamp'][0] However, this results in a series of pandas._libs.tslib.Timedelta objects. Plotting multiple timedelta series in one plot works with matplotlib, but not in plotly. For some reason, the two graphs are weirdly concatenated (see picture, if available), although they should appear on the same timescale. Any ideas?
tagged with: python
has comment: http://stackoverflow.com/comment/87962107
has title: Plotting multiple panda timedelta series with plotly
tagged with: pandas
answer count: 0

http://stackoverflow.com/comment/84118367
has text: just put a parameter before like `if len('marg'')==len('grammar'):` or add it to the logical: `set('marg')==set('grammar') and len('marg')==len('grammar') >>false ` and boom universal anagram testing
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48547894
type: Comment

http://stackoverflow.com/comment/84140403
type: AnswerComment
comment on: http://stackoverflow.com/a/48571703
type: Comment
has text: I didn't see what was the input, but I think you'll still need to cast as 'uint8' instead of 'int'. Otherwise you'll still get something similar to the original pic.
score: 0

http://stackoverflow.com/a/48671386
answers question: http://stackoverflow.com/q/48644137
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48644137
has body: A friend helped me figure it out- Clustering uses a library called joblib that splits the job into parallel processes. When running such functions on a Windows machine, care needs to be taken to make sure we use if __name__ == '__main__' in order to protect the code and allow the parallel processing to work. After adding if __name__ == '__main__' and placing all of the code there, the clustering ran smoothly and quickly
upvote count: 1

batch-file
tags question: http://stackoverflow.com/q/48559692
tag name: batch-file
type: Tag
tags question: http://stackoverflow.com/q/48622002

http://stackoverflow.com/comment/83999489
score: 0
has text: See my comment regarding code sample on your answer.
type: Comment
comment on: http://stackoverflow.com/q/48488496
type: QuestionComment

http://stackoverflow.com/comment/91311893
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52160022
type: Comment
has text: agreed, but just a thought why do you want to query this data using Mongo type queries? As in the end its just a JSON data you can use other ways to do the same work. Something like this or maybe something else out there. i think if you write your custom solution the performance may not the same as other solutions out there.

http://stackoverflow.com/comment/84030313
has text: This worked beautifully after you expanded your answer. Thanks!
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48517697

http://stackoverflow.com/q/48540401
has body: Is there a possibility to get the classification score for each ova estimator in a multi class SVM in scikit? The overall score of the muldi class SVM is not what i need. To be more specific. If i have a trained multi class SVM and i use it on my test data i want not only the overall score from the multi class SVM for each sample. I also need let me say the 10 best ova classifier reults from inside the multi class SVM. The confusion matrix would maybe one possibility but i'm not sure if the matrix reflects each classification process.
tagged with: scikit-learn
tagged with: python
tagged with: multilabel-classification
has title: How to get the estimator result for each ova estimator in a multi class svm with scikit?
tagged with: svm
type: Question
has comment: http://stackoverflow.com/comment/84081152
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84080701

http://stackoverflow.com/a/48594521
downvote count: 2
type: AcceptedAnswer
has body: I think you need, for i in range(len(cards[0])): for items in cards: if items[i] in cards[-1]: print(items[i],end="\n") else: print(items[i],end="\t")
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48594308
answers question: http://stackoverflow.com/q/48594308
upvote count: 2

pymc
tags question: http://stackoverflow.com/q/48589141
tags question: http://stackoverflow.com/q/48596018
type: Tag
tag name: pymc

http://stackoverflow.com/q/48533799
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1347791
tagged with: python
duplicate of: http://stackoverflow.com/q/1347791
has body: Whenever I try to read a csv file, I get this message! import pandas as pd read = pd.read_csv('C:\Users\Devika\Desktop\New.csv') File "&lt;ipython-input-12-15a303f06c16&gt;", line 1 read = pd.read_csv('C:\Users\Devika\Desktop\New.csv') ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape Am I making any silly mistakes?
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48533818
answer count: 1
has title: Python: how to read files
score: 1
downvote count: 1

http://stackoverflow.com/q/48528146
has body: I'm learning Python and pandas and I very often end up with long chains of method calls. I know how to break lists and chains of operators in a way that compiles, but I can't find a way to break method chains in a way that doesn't feel like cheating. There's plenty of examples of breaking up operator chains and lists in the googles, but I can't find anything decent for method chains. How can I break a long chain of method calls into multiple lines? Say a line like this one: t_values = df_grouped_by_day.sort_values('day_of_week').groupby(['day_of_week', 'day_of_week_name'])['Show_up'].apply(lambda sample: ttest_ind(population, sample)).reset_index()
favorite count: 0
type: Question
has title: Breaking long method chains into multiple lines in Python
has answer: http://stackoverflow.com/a/79401064
tagged with: pandas
answer count: 5
tagged with: method-chaining
score: 10
tagged with: python
has comment: http://stackoverflow.com/comment/84051396
linked to: http://stackoverflow.com/q/53162
upvote count: 11
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79401064
has answer: http://stackoverflow.com/a/48528147
possible better answer: http://stackoverflow.com/a/48528147
has comment: http://stackoverflow.com/comment/140043895
has answer: http://stackoverflow.com/a/48528342
has answer: http://stackoverflow.com/a/48528262
downvote count: 1
has answer: http://stackoverflow.com/a/79409681
has comment: http://stackoverflow.com/comment/84088272
has comment: http://stackoverflow.com/comment/84071300

http://stackoverflow.com/q/48531445
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84101348
has answer: http://stackoverflow.com/a/48531692
tagged with: cisco
has title: Cisco AMP API python script
answer count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84059062
type: Question
has body: I'm trying to write a script to pull the events from our Cisco AMP environment using the cisco api and Python. below is what I started with but I'm getting a file not found error "FileNotFoundError: [Errno 2] No such file or directory: 'request.json'" import requests import json url = 'https://&lt;your_client_id&gt;:&lt;your_api_key&gt;@api.amp.sourcefire.com/v1/events' payload = open("request.json") headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'} response = requests.post(url, data=payload, headers=headers) print (json.dumps(response)) Thanks for any assistance.
has comment: http://stackoverflow.com/comment/84100567
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/84093441
score: 0
comment on: http://stackoverflow.com/q/48548414
type: Comment
has text: @PawełKordowski cpk was a variable used to keep django from confusing the two id keys
type: QuestionComment

http://stackoverflow.com/comment/85979729
comment on: http://stackoverflow.com/a/49473464
type: AnswerComment
has text: Can I add a note that in the docs it's written as `Celery 4.0 supports Django 1.8 and newer versions. Please use Celery 3.1 for versions older than Django 1.8.`? So 4.x should be able to work with django 1.10, if anything I would suggest upgrading django to a higher version :)
score: 0
type: Comment

http://stackoverflow.com/comment/84322114
comment on: http://stackoverflow.com/q/48620168
type: QuestionComment
has text: You'll need a custom filter class, see [docs](https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter) and a [sample tutorial](https://www.elements.nl/blog/2015/03/16/getting-the-most-out-of-django-admin-filters/)
score: 2
type: Comment

http://stackoverflow.com/comment/84285154
type: AnswerComment
comment on: http://stackoverflow.com/a/48639898
score: 0
type: Comment
has text: Thank you so much. I am kind of new to python. I will look into how those NAN rows and columns are left out in the plotting then.

http://stackoverflow.com/a/48640740
score: 1
downvote count: 0
has body: I'll try again! It looks like this module is only available for python 2. Perhaps your virtualenv is trying to use python3. If you open a python shell while in the virtual env, the version number should be visible at the top. If you don't want to use python3, you can run scripts in python 2 by typing python2 mongo_users.py
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48640442

http://stackoverflow.com/q/48621130
accepted answer: http://stackoverflow.com/a/48622705
has answer: http://stackoverflow.com/a/48622705
downvote count: 0
has title: cannot upload files to django rest framework using react js
has body: I'm using react Js to upload an image to django restframework. here I'm sending post request using fetch API. Eapp.jsx import React, { Component } from 'react'; class Eapp extends Component { constructor(props){ super(props); this.state = { profilePic: null, }; this.inpuElement = null; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e){ this.setState({profilePic: e.target.files[0]}); } handleSubmit(){ let formData = new FormData(); formData.append('profile_pic',this.state.profilePic); fetch('http://10.42.0.1:8000/auth/profile-pic/', { method: 'POST', headers: { Accept: 'application/json, text/plain, */*', 'content-type': 'multipart/form-data', }, body:formData, }).then(res => res.json()) .then((data) => { console.log(data); }) .catch(err => console.log(err)); } render(){ return( { this.inpuElement = input; }} accept=".jpg,.jpeg,.png" onChange={this.handleChange} /> submit ); } } export default Eapp; error msg Eapp.jsx:19 POST http://10.42.0.1:8000/auth/profile-pic/ 500 (Internal Server Error) handleSubmit @ Eapp.jsx:19 callCallback @ react-dom.development.js:542 invokeGuardedCallbackDev @ react-dom.development.js:581 invokeGuardedCallback @ react-dom.development.js:438 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452 executeDispatch @ react-dom.development.js:836 executeDispatchesInOrder @ react-dom.development.js:858 executeDispatchesAndRelease @ react-dom.development.js:956 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967 forEachAccumulated @ react-dom.development.js:935 processEventQueue @ react-dom.development.js:1112 runEventQueueInBatch @ react-dom.development.js:3607 handleTopLevel @ react-dom.development.js:3616 handleTopLevelImpl @ react-dom.development.js:3347 batchedUpdates @ react-dom.development.js:11082 batchedUpdates @ react-dom.development.js:2330 dispatchEvent @ react-dom.development.js:3421 example:1 Failed to load http://10.42.0.1:8000/auth/p…
possible better answer: http://stackoverflow.com/a/56946289
has comment: http://stackoverflow.com/comment/113938682
favorite count: 0
type: Question
upvote count: 4
tagged with: reactjs
has answer: http://stackoverflow.com/a/56946289
answer count: 2
tagged with: django
tagged with: python
score: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/84280004
has text: @martinbshp the `return ` statement will break the loop and returns with that value , So in your question when `n=25` for the first loop `n%i==0` that means `25%2==0` is wrong. So it will move to else part and will `return True` and break from the loop. Thats why you are getting `True` when n=25. For your second case when `n=10`, in the first loop that means `10%2==0` is true and `return False` there also it will break loop and returns. So problem is in your loop and you can try answer I given or give any count number and check with that and return prime or not .
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48618260

http://stackoverflow.com/comment/84094159
has text: There is a pending expression system revamp that may cause such usage to no longer behave as expected.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48545998

http://stackoverflow.com/comment/84025102
comment on: http://stackoverflow.com/q/48515437
score: 2
type: Comment
type: QuestionComment
has text: You mean `continue`?

http://stackoverflow.com/comment/84076316
type: QuestionComment
has text: @Archer Yes you are right as per user experience, but I am just saying about possibilities about of what he is asking in the question. I know this is not good approach
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48540319

syntax-error
tags question: http://stackoverflow.com/q/48530092
tags question: http://stackoverflow.com/q/48574420
type: Tag
tags question: http://stackoverflow.com/q/48507481
tag name: syntax-error

http://stackoverflow.com/a/48512140
answers question: http://stackoverflow.com/q/48511584
type: Answer
has comment: http://stackoverflow.com/comment/84019750
score: 3
has comment: http://stackoverflow.com/comment/84019708
has comment: http://stackoverflow.com/comment/84019496
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48511584
has body: Here is an approachh using scipy.optimize.linprog. Explanation: First note that if you write the solutiion as permutation matrix then the objective function is linear. If we can express the constraint that solutions must be permutations in terms of linear equations and inequalities we can hand over to a standard solver. As a matter of fact we can't but we can do the next best thing and allow the convex hull of all permutation matrices. Because the problem is linear this cannot introduce a better solution, so we are essentially done. Note if the solution is unique this should just find it. If there are multiple solutions it might in theory mix them (in a convex combination; in practice, it doesn't seem to but I'm not expert enough to completely rule it out). If you are only interested in the diagonal sum you can ignore this. import numpy as np from scipy.optimize import linprog def best_perm(A): n, n = A.shape res = linprog(-A.ravel(), A_eq=np.r_[np.kron(np.identity(n), np.ones((1, n))), np.kron(np.ones((1, n)), np.identity(n))], b_eq=np.ones((2*n,)), bounds=n*n*[(0, None)]) assert res.success return res.x.reshape(n, n).T import pandas as pd from io import StringIO df = pd.read_csv(StringIO(""" 0 1 2 3 4 5 6 7 8 9 Class1 0 0 0 0 0 0 1 0 0 0 Class2 0 0 2 0 0 0 0 0 0 0 Class3 6 0 10 0 0 0 0 0 4 0 Class4 0 4 0 0 0 2 0 0 0 0 Class5 4 0 0 5 0 0 2 0 0 2 Class6 0 0 0 0 0 0 0 2 0 0 Class7 2 0 0 0 0 0 0 0 1 0 Class8 0 0 0 0 3 0 0 0 0 0 Class9 0 0 0 2 0 0 0 0 0 0 Class10 0 0 0 0 0 0 0 0 1 0"""), index_col=0, delimiter='\s+') shuffle = best_perm(df.values) print(shuffle) print(df.values @ shuffle) Output: [[ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.] [ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.] [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]] [[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 2. 0.…
has comment: http://stackoverflow.com/comment/84346438
has comment: http://stackoverflow.com/comment/84348591
has comment: http://stackoverflow.com/comment/84020114
has comment: http://stackoverflow.com/comment/84019359

http://stackoverflow.com/q/48632817
possible better answer: http://stackoverflow.com/a/48632952
upvote count: 2
has title: Can somebody explain this example code?
has comment: http://stackoverflow.com/comment/84262864
tagged with: arrays
has comment: http://stackoverflow.com/comment/84262780
has comment: http://stackoverflow.com/comment/84262915
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84262962
tagged with: python-3.x
type: AnsweredQuestion
score: -2
has answer: http://stackoverflow.com/a/48632952
has comment: http://stackoverflow.com/comment/84262847
has comment: http://stackoverflow.com/comment/84262903
tagged with: python
accepted answer: http://stackoverflow.com/a/48633006
has comment: http://stackoverflow.com/comment/84262788
has answer: http://stackoverflow.com/a/48633006
has body: im making a chess game and am having difficulties understanding this code, can someone explain it to me please. def enumerate_moves(x, y): potential_moves = [] # If the piece at position (x,y) is a Knight if board[x][y] is "Knight": potential_moves.append([[x+2], [y+1]]) potential_moves.append([[x+2], [y-1]]) potential_moves.append([[x+1], [y+2]]) potential_moves.append([[x+1], [y-2]]) potential_moves.append([[x-2], [y-1]]) potential_moves.append([[x-2], [y+1]]) potential_moves.append([[x-1], [y+2]]) potential_moves.append([[x-1], [y-2]]) i understand the concept of the code but just dont understand how these ([x-1], [y-2]) are the possible Knight Moves on a 8 by 8 two dimensional array. Can someone please explain how these calculations are made. Thank you!
answer count: 2
downvote count: 4

http://stackoverflow.com/q/48568717
has body: I have built a huffman encoder in Python, but because I'm storing the bits (which represent the characters) as strings, the encoded text is larger than the original. How can I use actual bits to compress text properly?
has comment: http://stackoverflow.com/comment/84133865
tagged with: compression
answer count: 1
downvote count: 3
tagged with: huffman-code
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
tagged with: bit
upvote count: 1
tagged with: python
tagged with: encoder
has title: How to encode with actual bits in Python?
has answer: http://stackoverflow.com/a/48569124

http://stackoverflow.com/q/48591134
tagged with: python
has body: Apologies if this isn't a suitable question but I need some help. I am trying to use BeautifulSoup to read articles from websites. I have tried it on the BBC News website and it works okay. However when I use this website: http://dncapital.com/dn-capital-raises-new-e200m-fund/ it does not print the correct thing. What can I do? I have tried looking for other ways but it doesn't seem to work or it costs money. Here is my code: import bs4 as bs import urllib.request sauce = urllib.request.urlopen('http://dncapital.com/dn-capital-raises-new-e200m-fund/').read() soup = bs.BeautifulSoup(sauce,'lxml') source_stopwords="" for paragraph in soup.find_all('p'): source_stopwords=source_stopwords+paragraph.text print(source_stopwords) but it doesn't print out the right thing. This is what it prints out. Call us : London: +44 (0)20 7340 1600 ⎪ Menlo Park: +1 (0)650 561 9300 Please click on the button below to submit your press enquiry. Please fill in this form to subscribe to our mailing list. DN Capital (US) Inc. 2882 Sand Hill Road, Suite 210 Menlo Park CA 94025 +1 650 561 9300DN Capital (UK) LLP 2 Queen Anne's Gate Buildings Dartmouth Street London SW1H 9BP +44 (0)20 7340 1600 +44 (0)20 7340 1601
score: 0
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/60039504
has comment: http://stackoverflow.com/comment/84179682
type: UnansweredQuestion
has title: Using BeautifulSoup to read articles from websites not working
has comment: http://stackoverflow.com/comment/84185961
answer count: 1
has comment: http://stackoverflow.com/comment/84180108

generator
type: Tag
tags question: http://stackoverflow.com/q/48568062
tags question: http://stackoverflow.com/q/48584098
tags question: http://stackoverflow.com/q/48630189
tags question: http://stackoverflow.com/q/48492234
tag name: generator
tags question: http://stackoverflow.com/q/48615411
tags question: http://stackoverflow.com/q/48497230
tags question: http://stackoverflow.com/q/48594971
tags question: http://stackoverflow.com/q/48554289
tags question: http://stackoverflow.com/q/48628637

http://stackoverflow.com/comment/84028013
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48516776
has text: Possible duplicate of [indexing numpy array with logical operator](https://stackoverflow.com/questions/20974640/indexing-numpy-array-with-logical-operator)

http://stackoverflow.com/q/48588260
tagged with: python
has title: Merging PDFs using reportlab and PyPDF2 loses images and embedded fonts
tagged with: image
has body: I am trying to take an existing PDF stored on AWS, read it into my backend (Django 1.1, Python 2.7) and add text into the margin. My current code successfully takes in the PDF and adds text to the margin, but it corrupts the PDF: When opening in the browser: Removes pictures Occasionally adds characters between words Occasionally completely changes the character set of the PDF When opening in Adobe: Says "Cannot extract the embedded font 'whatever font name'. Some characters many not display or print correctly" Says "A drawing error occured" If there were pictures pre-edit, says "Insufficient data for an image" I have made my own PDF with/without predefined fonts and with/without images. The ones with predefined fonts and no images work as expected, but with images it throws "There was an error while reading a stream." when opening in Adobe, and just doesn't show the images in the browser. I have come to the conclusion that missing fonts is the reason for the problems with the characters, but I'm not sure why the images aren't showing. I don't have control over the contents of the PDFs I'm editing so I can't ensure they only use the predefined fonts, and they definitely will need to have images in them. Below is my code from reportlab.pdfgen import canvas from PyPDF2 import PdfFileWriter, PdfFileReader from StringIO import StringIO class DownloadMIR(APIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, format=None): data = request.data file_path = "some_path" temp_file_path = "some_other_path" # read your existing PDF if default_storage.exists(file_path): existing_pdf = PdfFileReader(default_storage.open(file_path, 'rb')) else: raise Http404("could not find pdf") packet = StringIO() # create a new PDF with Reportlab can = canvas.Canvas(packet) height, width = int(existing_pdf.getPage(0).mediaBox.getUpperRight_x()), int( existing_pdf.getPage(0).mediaBox.getUpperRight_y()) print("width:" + str(width) + " height: " + str(height)) can.set…
type: Question
has comment: http://stackoverflow.com/comment/84254797
accepted answer: http://stackoverflow.com/a/48725792
answer count: 1
type: AnsweredQuestion
score: 0
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/48725792

http://stackoverflow.com/comment/84058571
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48530970
has text: @ImportanceOfBeingErnest, the image shows 11 'lines' but they are not actaully lines, since each 'line' is a set of point (i.e each line is made up of 176501 points).
score: 0

http://stackoverflow.com/q/48518276
has comment: http://stackoverflow.com/comment/84031345
has title: how to integrate my simple python nlp script into my rails app
tagged with: data-science
has comment: http://stackoverflow.com/comment/84032775
favorite count: 0
type: AnsweredQuestion
has body: I wrote a python script which automatically categorizes set of articles. I want to integrate it into my rails app.Please let me know if anybody has the approach.Thanks in advance
tagged with: python
score: -1
tagged with: nlp
tagged with: svm
type: Question
upvote count: 0
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48519153
accepted answer: http://stackoverflow.com/a/48519153
tagged with: ruby-on-rails

http://stackoverflow.com/q/48607185
has title: My script seems to get stuck once N >> 1
has comment: http://stackoverflow.com/comment/84210790
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84211230
accepted answer: http://stackoverflow.com/a/48610102
has comment: http://stackoverflow.com/comment/84210806
has comment: http://stackoverflow.com/comment/84211863
has answer: http://stackoverflow.com/a/48610102
favorite count: 0
has comment: http://stackoverflow.com/comment/84212636
type: Question
has comment: http://stackoverflow.com/comment/84211211
score: -2
has comment: http://stackoverflow.com/comment/84212193
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/84217290
has comment: http://stackoverflow.com/comment/84211253
has comment: http://stackoverflow.com/comment/84210780
has comment: http://stackoverflow.com/comment/84286865
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84211930
has body: Edit : So I let the code run for 70 hours and it did not return. Thus I stick to my point, it does get stuck on something, fails silently and let the bash hanging. From the time increase compared to the relatively small jump between N1 and N2, it's not something a O(N) -> O(N²) can explain. (input going from N to 2N implies an execution time going from N² to 4N², so it should only take 4 time more. Not returning after hours for 2N while finishing in 15 minutes max for N means something fails) Accepted solution works very well until it reaches (instantly) a very clean memory overflow. $ py so_mysan.py 400000000 Traceback (most recent call last): File "so_mysan.py", line 36, in sys.exit(main(sys.argv[1:])) File "so_mysan.py", line 8, in main ordering = list(range(N)) MemoryError Thank you for your time. /edit import sys import numpy as np from random import randint def main(arguments): N = int(sys.argv[1]) # definissons notre ligne de maison : houses = [0]*N emptySlot = list(range(0,N)) # counter = 1 while (len(emptySlot)&gt;0): # on prend une maison vide possiblement habitable par un mysanthrope, au hasard. empt = randint(0, len(emptySlot)-1) houses[emptySlot[empt]] = 1 # on enlève cette maison de notre liste de possibilité # et éventuellement les maisons adjacentes si elles y étaient temp = emptySlot[empt] del emptySlot[empt] # on essaye d'enlever les autres si existes plus efficacement : if (0&lt;=empt and empt&lt;len(emptySlot) and emptySlot[empt] == temp+1): del emptySlot[empt] # comme on a viré l'index empt, ça décale. if (empt-1 &gt;= 0 and emptySlot[empt-1] == temp-1): del emptySlot[empt-1] # pour l'inférieur, cela ne change rien occupancyRate = sum(houses) / N print(occupancyRate) if __name__ == '__main__': sys.exit(main(sys.argv[1:])) I guess it's something to do with the array size but my resources monitoring does not show CPU or RAM going through the roof. It runs fine up to N = 4.10^6 I don't think multi threading is possible or worth since it's just one …
has comment: http://stackoverflow.com/comment/84211358
has comment: http://stackoverflow.com/comment/84211844

http://stackoverflow.com/q/48524468
score: 0
has comment: http://stackoverflow.com/comment/84043818
tagged with: django-views
has body: My urls.py is this and even though i have created the password-reset-done url from django.conf.urls import url from .import views from django.conf.urls import url from django.contrib.auth.views import login, logout, password_reset, password_reset_done, password_reset_confirm, password_reset_complete urlpatterns= [ url(r'^$',views.index, name= "index"), #127.0.0.1/polls url(r'^(?P&lt;question_id&gt;[0-9]+)/$', views.detail, name= "detail"), #127.0.0.1/polls/1 url(r'^(?P&lt;question_id&gt;[0-9]+)/results$', views.results, name="results"), #127.0.0.1/polls/1/results url(r'^(?P&lt;question_id&gt;[0-9]+)/vote$', views.vote, name="vote"), #127.0.0.1/polls/1/vote url(r'^login/$', login, {'template_name': 'polls/login.html'}), url(r'^logout/$', logout, {'template_name': 'polls/logout.html'}), url(r'^register/$', views.register, name= 'register'), url(r'^profile/$', views.view_profile, name= 'profile'), url(r'^edit_profile/$', views.edit_profile, name= 'edit_profile'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^reset-password/$', password_reset, name='reset_password'), url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'), ] I am getting the following error.
answer count: 1
tagged with: django
has title: How could i get over NoReverseMatch at /polls/reset-password/ error to continue in making password resetting?
has answer: http://stackoverflow.com/a/48524544
type: Question
type: UnansweredQuestion
tagged with: django-urls
tagged with: python

http://stackoverflow.com/comment/84015109
score: 4
has text: Errr, yeah, because you use `row = cur.fetchone()` and not `fetchall()`. You explicitly ask it to only return one value.
comment on: http://stackoverflow.com/q/48510066
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84218033
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48610772
has text: Is there a reason you're using `getopt` instead of [`argparse`](https://docs.python.org/3/library/argparse.html)? `argparse` is much simpler to use.
type: QuestionComment

http://stackoverflow.com/a/48637340
has body: This should work: import os path = os.getcwd()+"/assets/templates" list_of_files = {} for filename in os.listdir(path): list_of_files[filename] = "http://yourpath.com/"+filename
upvote count: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/48637088
answers question: http://stackoverflow.com/q/48637088
type: AcceptedAnswer
downvote count: 0
score: 6

http://stackoverflow.com/a/48536546
has body: You can indeed do this, but with a slightly different format string, called regular expressions. Here is how you do it: import re # this is how you write your "format" regex = r"(?P&lt;name&gt;\w+) (?P&lt;age&gt;\d+) (?P&lt;gender&gt;[MF])" test_str = "Alice 10 F" groups = re.match(regex, test_str) Now you can use groups to access all the components of the string: &gt;&gt;&gt; groups.group('name') 'Alice' &gt;&gt;&gt; groups.group('age') '10' &gt;&gt;&gt; groups.group('gender') 'F' Regex is a very cool thing. I suggest you learn more about it online.
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48536295
downvote count: 0
has comment: http://stackoverflow.com/comment/84069074
has comment: http://stackoverflow.com/comment/84068746
type: Answer
has comment: http://stackoverflow.com/comment/84068639

http://stackoverflow.com/a/48527425
accepted answer of: http://stackoverflow.com/q/48526441
type: Answer
answers question: http://stackoverflow.com/q/48526441
score: 8
downvote count: 0
has body: Input: a = pd.DataFrame({'first':[1,2,3],'second':['one','two','three']}) b = pd.DataFrame({'alice':['yes','no'],'bob':['no','yes']}) Create a dummy key and merge creating a cartesian product a.assign(key=1).merge(b.assign(key=1), on='key').drop('key',axis=1) Output: first second alice bob 0 1 one yes no 1 1 one no yes 2 2 two yes no 3 2 two no yes 4 3 three yes no 5 3 three no yes
type: AcceptedAnswer
upvote count: 8

http://stackoverflow.com/q/48631131
answer count: 1
has answer: http://stackoverflow.com/a/48631964
tagged with: scikit-learn
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84286739
has comment: http://stackoverflow.com/comment/84267426
tagged with: python
type: Question
tagged with: python-3.x
has title: Encoding lemmas for use in Affinity Propagation/Finding natural clusters in text data
has body: I have a dataframe that several columns of lemmatized text (multiple paragraphs worth of text per row - not categorical), plus some other int, datetime, and float columns. I'd like to use the text for Affinity Propagation, to find clusters within the data. sklearn.cluster.affinitypropagation doesn't work with text data though and returns: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-110-41dbca660b33&gt; in &lt;module&gt;() ----&gt; 1 f = clusterer.fit(TIP_with_rats_nlp) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\cluster\affinity_propagation_.py in fit(self, X, y) 289 similarities / affinities. 290 """ --&gt; 291 X = check_array(X, accept_sparse='csr') 292 if self.affinity == "precomputed": 293 self.affinity_matrix_ = X ~\AppData\Local\Continuum\anaconda3\lib\site-packages\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) 415 # make sure we actually converted to numeric: 416 if dtype_numeric and array.dtype.kind == "O": --&gt; 417 array = array.astype(np.float64) 418 if not allow_nd and array.ndim &gt;= 3: 419 raise ValueError("Found array with dim %d. %s expected &lt;= 2." ValueError: could not convert string to float: "main area improvement plan specifically have ahead time want work break unit daily learning target goal week ahead detailed weekly overview activity lesson align learning target make sure lesson opportunity student intellectually engage historical material.1 deadline planning 's week learn target write document 7 pm fill remain weekly overview template 2 plan google document share co teacher order feedback 3 weekly meeting mentor work create week learn target 4 observe structure classroom co teaching style observe rigor bring classroom step 1 -3 start 9/26/14 continue year step 4 start 9/29/14 work ob…
type: UnansweredQuestion

http://stackoverflow.com/comment/84043661
has text: thank you very much for that '\n' is the only problem
type: Comment
comment on: http://stackoverflow.com/q/48521184
type: QuestionComment
score: 0

http://stackoverflow.com/q/48568561
has comment: http://stackoverflow.com/comment/84140738
type: Question
score: 0
has body: I have a collection that is partitioned by an integer with a dozen or so unique values that are more-or-less evenly distributed. I recently migrated a Cosmos DB collection from non-partitioned to partitioned due to the size constraint. Since then, I have been having issues with querying the database. For starters, the queries in the Document Explorer in Azure are very inefficient unless I specify the specific partition key as part of the query. For the Python API, I must specify the specific key. If I do not, I get an error unless I specify these headers in the options field: {'enableCrossPartitionQuery':True, 'partitionKey':'[variable name]'} These have been passed to the QueryDocuments() function, as well as the _fetch_function() function (for continuation token support). I have also replaced True with 'True', 't', 'true', and arbitrary values. None of these actually changed the performance or behavior of their respective calls. No data is returned at all when specifying these specific headers in the Python API.
tagged with: azure
has comment: http://stackoverflow.com/comment/84139439
tagged with: python
has comment: http://stackoverflow.com/comment/84140686
has comment: http://stackoverflow.com/comment/84138577
answer count: 0
has title: How do you perform a cross-partition query in Cosmos DB using the Python API?
has comment: http://stackoverflow.com/comment/84139464
tagged with: database-partitioning
type: UnansweredQuestion
tagged with: azure-cosmosdb

http://stackoverflow.com/a/48625848
answers question: http://stackoverflow.com/q/48625747
has body: You have a code indentation issue. try this: def test_code(): print "test_code" def run(): try: a= ''' def test2(): print "test2" test_code() test2() ''' exec(a) except Exception as e: print e run() # test_code # test2
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/48573994
has comment: http://stackoverflow.com/comment/84146154
has comment: http://stackoverflow.com/comment/84145099
has body: If you can't notice any changes on your client or server with or without those last two statements, you should still call them anyway. The IMAP spec includes a handy diagram outlining the lifecycle of an IMAP connection (scroll one page up from that link): +----------------------+ |connection established| +----------------------+ || \/ +--------------------------------------+ | server greeting | +--------------------------------------+ || (1) || (2) || (3) \/ || || +-----------------+ || || |Not Authenticated| || || +-----------------+ || || || (7) || (4) || || || \/ \/ || || +----------------+ || || | Authenticated |<=++ || || +----------------+ || || || || (7) || (5) || (6) || || || \/ || || || || +--------+ || || || || |Selected|==++ || || || +--------+ || || || || (7) || \/ \/ \/ \/ +--------------------------------------+ | Logout | +--------------------------------------+ || \/ +-------------------------------+ |both sides close the connection| +-------------------------------+ (1) connection without pre-authentication (OK greeting) (2) pre-authenticated connection (PREAUTH greeting) (3) rejected connection (BYE greeting) (4) successful LOGIN or AUTHENTICATE command (5) successful SELECT or EXAMINE command (6) CLOSE command, or failed SELECT or EXAMINE command (7) LOGOUT command, server shutdown, or connection closed The spec goes into further details about how servers can try to behave when misbehaving clients talk to them but the safest thing to do is just follow the spec. If for some reason you were adamantly against manually finishing IMAP connections as opposed to just exiting your script, you'd have to check out the implementation of the IMAP server you were talking with to figure out exactly how it handles that situation (which I assume could be summed up as "gracefully" but it's still a bad idea to rely on that behavior).
has comment: http://stackoverflow.com/comment/84146459
has comment: http://stackoverflow.com/comment/84146167
answers question: http://stackoverflow.com/q/48571471
has comment: http://stackoverflow.com/comment/84163747
type: Answer
score: 6
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48571471
downvote count: 0
has comment: http://stackoverflow.com/comment/84145332
type: AcceptedAnswer

http://stackoverflow.com/comment/84047767
comment on: http://stackoverflow.com/a/48525198
score: 0
type: AnswerComment
type: Comment
has text: just to be on the same page, you pip uninstalled both azure-mgmt-datafactory and azure-mgmt and did pip install azure-mgmt again? just do a pip install azure-mgmt as recommended https://pypi.python.org/pypi/azure-mgmt and not azure-mgmt-resource

http://stackoverflow.com/comment/84225301
type: Comment
type: QuestionComment
has text: That's strange. Judging by the [source](https://github.com/pypa/setuptools/blob/master/pkg_resources/__init__.py), `get_distribution()` should never return `None`. An old version? Maybe [stepping through the code](https://stackoverflow.com/questions/31245083/how-can-pyspark-be-called-in-debug-mode) shows something.
comment on: http://stackoverflow.com/q/48612052
score: 0

http://stackoverflow.com/comment/84239080
comment on: http://stackoverflow.com/q/48619163
score: 0
type: QuestionComment
has text: Try https://gist.github.com/kixorz/3b172e2fc3ce35421ee9. The code is simple to adapt to Python
type: Comment

http://stackoverflow.com/q/48595858
linked to: http://stackoverflow.com/q/38950958
has answer: http://stackoverflow.com/a/48771959
has comment: http://stackoverflow.com/comment/84257862
answer count: 1
downvote count: 0
tagged with: rselenium
score: 4
has comment: http://stackoverflow.com/comment/84259217
favorite count: 0
accepted answer: http://stackoverflow.com/a/48771959
type: Question
has comment: http://stackoverflow.com/comment/84276334
tagged with: docker
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84268266
has body: I have a simple yaml file: seleniumhub: image: selenium/hub ports: - 4444:4444 firefoxnode: image: selenium/node-firefox-debug ports: - 4577 links: - seleniumhub:hub chromenode: image: selenium/node-chrome-debug ports: - 4578 links: - seleniumhub:hub that I have executed in docker: docker-compose up -d I have one hub and two nodes running. Now I would like to run two very simple selenium commands in parallel (written in RSelenium): remDr$open() remDr$navigate("http://www.r-project.org") remDr$screenshot(display = TRUE) I would like to know how can I run above selenium commands in Python or R, in parallel. I tried several ways but none works. For example in R: library(RSelenium) remDr &lt;- remoteDriver(remoteServerAddr = "192.168.99.100", port = 4444L) remDr$open() remDr$navigate("http://www.r-project.org") remDr$screenshot(display = TRUE) doesn't do anything. I have also tried to run two remoteDrivers, but that doesn't help ether: remDr &lt;- remoteDriver(remoteServerAddr = "192.168.99.100", port = 4577L) remDr$open() remDr$navigate("http://www.r-project.org") remDr$screenshot(display = TRUE)
tagged with: python
tagged with: selenium-grid
upvote count: 4
has title: Run yaml file for parallel selenium test from R or python

http://stackoverflow.com/q/48488827
type: UnansweredQuestion
answer count: 1
has title: Flask with AJAX - updating a HTML table
tagged with: javascript
tagged with: flask
downvote count: 1
favorite count: 0
type: Question
tagged with: ajax
has comment: http://stackoverflow.com/comment/83971067
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48489111
has body: Using Flask and AJAX I build a HTML table like this... app.py tableDict = buildTable() return render_template('page.html', tableDict = tableDict) page.html &lt;tbody&gt; {% for key, value in tableDict.iteritems() %} &lt;tr&gt; &lt;th&gt; {{ key }} &lt;/th&gt; &lt;td&gt; {{ value }} &lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; That works fine. I want to update this table using AJAX. I know how to update an element by it's ID tag with something like ajax.js $("#elementToUpdate").html(response.valueToUpdate); So I tried... app.py tableDict = buildTable() return jsonify(tableDict = tableDict) ajax.js $("#tableDict").html(response.tableDict); This doesn't work - my guess is because I'm not updating an ID tag at all...so I shouldn't be surprised about that. How can I get the dict that I pass to AJAX to update the table?
upvote count: 2

http://stackoverflow.com/q/48502998
has body: I have a binary file which I am trying to recreate by writing data to a new file. The data in it should be stored as 32-bit (4-byte) twos- complement binary integers or as ASCII characters. The first 4 bytes should represent the integer 0, then the next 4 should be the integer 4, the next 4 should be the integer 180. The next 4 bytes I need to pack 014500 which represents HourHourMinuteMinuteSecondSecond. When hexdumped, it should appear as: 0000000 0000 0000 0004 0000 00b4 0000 ccf8 0001 With the last two columns representing the packed version of the last 4 bytes. I cannot seem to replicate this. I've tried packing as a string and as an integer (removing the leading zero for the latter). I don't know what to do. Any guidance would be appreciated. I am on a 64 bit RHEL Linux box running python3.4. My code is: #!/usr/bin/python3.4 import struct fout = open('brian', 'wb') fout.write(struct.pack('I', 0)) fout.write(struct.pack('I', 4)) fout.write(struct.pack('I', 180)) fout.write(struct.pack('I', 14500)) # also tried: # fout.write(struct.pack('4s', b'014500'))
tagged with: pack
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84000146
has title: Python3.4 packing and format type with struct
favorite count: 0
type: Question
tagged with: struct
tagged with: python-3.x
tagged with: binary
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84000556
has comment: http://stackoverflow.com/comment/84001104
has comment: http://stackoverflow.com/comment/84000732
tagged with: python
has comment: http://stackoverflow.com/comment/83999886

http://stackoverflow.com/comment/84164027
type: Comment
score: 0
type: AnswerComment
has text: Thank you! I thought about using dictionary but have no idea how to implement it. That's better suits my needs. Thanks!!!
comment on: http://stackoverflow.com/a/48583422

http://stackoverflow.com/q/48527722
has answer: http://stackoverflow.com/a/48545859
type: AnsweredQuestion
score: 0
tagged with: pytorch
answer count: 1
has body: I want to find the index of the smallest tensor (by some key function) in a list li. So I did min and afterwards li.index(min_el). My MWE suggests that somehow tensors don't work with index. import torch li=[torch.ones(1,1), torch.zeros(2,2)] li.index(li[0]) 0 li.index(li[1]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File ".../local/lib/python2.7/site-packages/torch/tensor.py", line 330, in __eq__ return self.eq(other) RuntimeError: inconsistent tensor size at /b/wheel/pytorch-src/torch/lib/TH/generic/THTensorMath.c:2679 I can of course make my own index function that first checks for size and then element wise. E.g. def index(list, element): for i,el in enumerate(list): if el.size() == element.size(): diff = el - element if (1- diff.byte()).all(): return i return -1 I was just wondering, why doesn't index work? Is there maybe a smart way of doing this not by hand that I'm missing?
has title: How to find the index of a tensor in a list?
type: Question
has comment: http://stackoverflow.com/comment/84050899
accepted answer: http://stackoverflow.com/a/48545859
tagged with: python

http://stackoverflow.com/comment/84111293
comment on: http://stackoverflow.com/q/48557613
type: Comment
type: QuestionComment
has text: Do you understand what your intermediate arrays contain, and what the result contains?
score: 0

http://stackoverflow.com/q/48606686
type: Question
accepted answer: http://stackoverflow.com/a/48656064
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0
has body: I am curious about the right way to update the Patches glyph in bokeh. My minimal example is: p_blur = figure(x_range=(0, 300), y_range=(0, 300)) source = ColumnDataSource({'xs':[[100,200,300], [10,50,500,400]], 'ys':[[30,150,70], [10,500,50,50]]}) polygons = Patches(xs="xs", ys="ys",fill_color="#fb9a99") glyph = p_blur.add_glyph(source, polygons) nb = show(p_blur, notebook_handle=True) If I now want to update the glyph e.g. by source1 = ColumnDataSource({'xs':[[10,20,30], [10,50,50,40]], 'ys':[[30,15,70], [10,50,50,50]]}) glyph.data_source = source1 push_notebook( nb ) I don't see any change. However, if I do: p_blur.renderers.remove(glyph) glyph = p_blur.add_glyph(source1, polygons) push_notebook( nb ) The change is reflected. Seems though that the second way is too hacky. Is there more correct way to do this? Thanks!
tagged with: bokeh
tagged with: jupyter
has title: Updating bokeh patches in Jupiter notebook
has answer: http://stackoverflow.com/a/48656064

wav
tags question: http://stackoverflow.com/q/48637985
tag name: wav
type: Tag
tags question: http://stackoverflow.com/q/48598829

http://stackoverflow.com/comment/84145979
has text: You need to include the doPostBack arguments in the post (__EVENTTARGET and __EVENTARGUMENT). Mechanize would be a good choice if it were more reliable, I would probably go with requests.
comment on: http://stackoverflow.com/q/48567063
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48491623
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83976890
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50039603
has answer: http://stackoverflow.com/a/48491980
has title: Error installing kivy
score: 1
upvote count: 1
tagged with: kivy
has body: I am using pip install to install kivy on windows 10. I keep getting an error in the command prompt that states: (could not find a version that satisfies the requirement pywin32 (from versions: ) no matching distribution found for pywin32 (from pypiwin32) Do you have any ideas?
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/48508873
has comment: http://stackoverflow.com/comment/84012480
has comment: http://stackoverflow.com/comment/84013024
type: Question
has comment: http://stackoverflow.com/comment/100429289
has comment: http://stackoverflow.com/comment/84012990
has comment: http://stackoverflow.com/comment/84048560
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48508985
tagged with: matching
downvote count: 2
has body: I am working on a python program that, at one step, takes an input (string), and matches it to songs/artists in a users library. I'm having some difficulty, however, figuring out how to match when the input/library contains numbers/special characters. For example, take the group "All-4-One". In my library it might be listed exactly like that. I need to match this to ANY of the following inputs: all-4-one (of course) all 4 one (no dashes) all 4 1 (all numbers) all four one (all spelled out) all for one (phonetic spelling of "four") Or, really, any other combination that sounds the same. The reasoning for this is that the input comes from a speech recognition system, so the user speaking "4" could be recognized as "for", "four" or "4". I'd imagine that Alexa/Siri/Google all do things like this (since you can ask them to play songs/artists), but I want to implement this in Python. How can I do this?
tagged with: python
upvote count: 3
has title: Match strings based on sound/homophones in python?
score: 1
has comment: http://stackoverflow.com/comment/84012631
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84094119
has text: Can you share HTML sample for the same along with current and desired output?
comment on: http://stackoverflow.com/q/48548296
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48542418
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84387936
has comment: http://stackoverflow.com/comment/84400069
has comment: http://stackoverflow.com/comment/84079796
tagged with: import
type: Question
has answer: http://stackoverflow.com/a/49105522
tagged with: package
tagged with: python
has title: Unsuccessfully Running TensorFlow Package on Windows and Python
accepted answer: http://stackoverflow.com/a/49105522
has comment: http://stackoverflow.com/comment/84107303
has comment: http://stackoverflow.com/comment/84100034
has comment: http://stackoverflow.com/comment/84135312
has body: I have been working with Anaconda, Python 3.5 and Win 7. Having been obliged to work with TensorFlow, I installed and run it. For the first time it worked but for the second time, I got the error : "tensor flow module not found". I uninstalled and installed it again and got the same error. Switching to windows 10, python 2 or using another system have not been useful. Is there any other way to try (except using Linux)? Thanks a lot in advance.

http://stackoverflow.com/comment/84171650
type: Comment
type: QuestionComment
has text: Thanks for looking at this. I'm still trying to wrap my head around the pieces of sql-alchemy, but what exactly is base? I can see that the tables inherit from it, but what functionality does it add?
comment on: http://stackoverflow.com/q/48586840
score: 0

http://stackoverflow.com/comment/84105777
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48554628
has text: well thing doesnt seem changed even after following your advice...thanks anyways

http://stackoverflow.com/a/48574300
has comment: http://stackoverflow.com/comment/84163796
has comment: http://stackoverflow.com/comment/84161090
has comment: http://stackoverflow.com/comment/84161204
upvote count: 3
has comment: http://stackoverflow.com/comment/84179704
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84166276
has comment: http://stackoverflow.com/comment/84163753
answers question: http://stackoverflow.com/q/48573717
has comment: http://stackoverflow.com/comment/84167634
score: 3
accepted answer of: http://stackoverflow.com/q/48573717
has comment: http://stackoverflow.com/comment/84145420
type: Answer
has comment: http://stackoverflow.com/comment/84162564
has comment: http://stackoverflow.com/comment/84163979
has comment: http://stackoverflow.com/comment/84160638
has comment: http://stackoverflow.com/comment/84160422
has body: The goal of the delegates is to customize each item that is displayed in a QAbstractItemView, the other way to do it is by inserting a widget using the indexWidget method. The advantage of the delegates is that the memory consumption is minimal. It is advisable not to use them at the same time. The delegates have the following methods: paint(): is the method responsible for drawing the item that is normally displayed createEditor(): is the method is responsible for creating the editor. setEditorData(): get the value of the model and establish it in the editor. setModelData(): save the data obtained from the editor to the model. An example of that type of delegate is the following: from PySide2.QtWidgets import * from PySide2.QtGui import * from PySide2.QtCore import * class Delegate(QStyledItemDelegate): def createEditor(self, parent, option, index): dialog = QColorDialog(parent) return dialog def setEditorData(self, editor, index): color = index.data(Qt.BackgroundRole) editor.setCurrentColor(color) def setModelData(self, editor, model, index): color = editor.currentColor() model.setData(index, color, Qt.BackgroundRole) if __name__ == '__main__': import sys app = QApplication(sys.argv) model = QStandardItemModel(4, 4) for i in range(model.rowCount()): for j in range(model.columnCount()): color = QColor(qrand() % 256, qrand() % 256, qrand() % 256) it = QStandardItem("{}{}".format(i, j)) it.setData(color, Qt.BackgroundRole) model.setItem(i, j, it) w = QTableView() w.setModel(model) w.setItemDelegate(Delegate()) w.show() sys.exit(app.exec_()) Update: I have improved your code since it had unnecessary elements, the main error is that these Qt::BackgroundRole must return a QColor from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * import warnings class Model(QAbstractTableModel): def __init__(self, parent = None): QAbstractTableModel.__init__(self, parent) #data self.groups = [] #header self.header_labels = ['Color', 'Group', 'Done'] …

http://stackoverflow.com/comment/84023228
type: Comment
has text: I tried this and it works for how many 6's, 5's and 3's there are in the deck. for card in cards: print(deck.cards.count(card)) The result is: 6 5 3
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48514282

http://stackoverflow.com/q/48639486
has comment: http://stackoverflow.com/comment/84278682
has answer: http://stackoverflow.com/a/48648613
tagged with: python
has title: Programmatically changing Ebay pictures through Trading API
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: ebay-api
has comment: http://stackoverflow.com/comment/84278840
type: Question
has body: This question isn't specific to Python at all, given that I know all the same HTTP API calls are made regardless of what SDK is being used. I have a bunch of listings (hundreds) that I need to change programmatically. The need is just to change the Variation pictures of an item. Using the ReviseItem API has not been working as expected for me. Details: If I do a GetItem request for itemID 332121070278, I get the following response back: <?xml version="1.0" encoding="UTF-8"?> 2018-02-05T16:46:02.399Z Success 1035 E1035_INTL_API_18562923_R1 332121070278 Colour <VariationSpecificPictureSet> <VariationSpecificValue>Navy</VariationSpecificValue> https://s3-eu-west-1.amazonaws.com/images.linnlive.com/b3bb06dbe22847df07835760a144c5dd/3e11c104-311f-4faa-b308-e6d40f6a3c6a.jpg https://s3-eu-west-1.amazonaws.com/images.linnlive.com/b3bb06dbe22847df07835760a144c5dd/3e11c104-311f-4faa-b308-e6d40f6a3c6a.jpg </VariationSpecificPictureSet> <VariationSpecificPictureSet> <VariationSpecificValue>Olive</VariationSpecificValue> https://s3-eu-west-1.amazonaws.com/images.linnlive.com/b3bb06dbe22847df07835760a144c5dd/881a11fe-bb73-4d3a-a556-cdecae2ee723.jpg https://s3-eu-west-1.amazonaws.com/images.linnlive.com/b3bb06dbe22847df07835760a144c5dd/881a11fe-bb73-4d3a-a556-cdecae2ee723.jpg </VariationSpecificPictureSet> <VariationSpecificPictureSet> <VariationSpecificValue>Nearly Black</VariationSpecificValue> https://s3-eu-west-1.amazonaws.com/images.linnlive.com/b3bb06dbe22847df07835760a144c5dd/211f43f9-a4fd-40fd-9712-743e5ab328d0.jpg https://s3-eu-west-1.amazonaws.com/images.linnlive.com/b3bb06dbe22847df07835760a144c5dd/211f43f9-a4fd-40fd-9712-743e5ab328d0.jpg </VariationSpecificPictureSet> <VariationSpecificPictureSet> <VariationSpecificValue>Wine</VariationSpecificValue> https://s3-eu-west-1.amazonaws.com/images.linnlive.com/b3bb06dbe22847df07835760a144c5dd/27f7768e-3987-4ff4-9440-614c0853b0cb.jpg https://s3-eu-west-1.amazonaws.com/images.linnlive.com/b3bb06dbe22847df07835760a144c5dd/27f776…
accepted answer: http://stackoverflow.com/a/48648613

http://stackoverflow.com/comment/84188323
comment on: http://stackoverflow.com/q/48594888
has text: reduce batchsize to be about 128 or 64. Decrease the size of dense layer may be 512 or 384
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48632331
downvote count: 0
answers question: http://stackoverflow.com/q/48592296
has comment: http://stackoverflow.com/comment/85873254
has comment: http://stackoverflow.com/comment/85916208
score: 3
accepted answer of: http://stackoverflow.com/q/48592296
type: Answer
upvote count: 3
has body: I solved my problem by defining these flags in tensorflow model: my_tf_model.py. tf.app.flags.DEFINE_string('bind', '', 'Server address') tf.app.flags.DEFINE_integer('timeout', 30, 'Server timeout') And then changed my gunicorn command line to use double dash style command line: gunicorn --bind 0.0.0.0:5000 --timeout 30 wsgi:app But I think there should be some other way rather than this hack to resolve the globally-used flags.
type: AcceptedAnswer

http://stackoverflow.com/q/48507367
has comment: http://stackoverflow.com/comment/84009284
has comment: http://stackoverflow.com/comment/84009573
possible better answer: http://stackoverflow.com/a/48507801
score: 2
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/48507592
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48507592
has comment: http://stackoverflow.com/comment/84009335
has title: Send data between two python Scripts in continous succession
has comment: http://stackoverflow.com/comment/84009357
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48507801
has comment: http://stackoverflow.com/comment/84009961
tagged with: sockets
has comment: http://stackoverflow.com/comment/84009382
has comment: http://stackoverflow.com/comment/84009622
has body: I basically want to send data from one python file to the other, then have the other python file send some more data back to the first file, and then the first file send data again, and this goes on until I choose to stop sending data. server.py: import socket s = socket.socket() host = "127.0.0.1" port = 5409 s.bind((host, port)) s.listen(1) while True: c, addr = s.accept() print 'Got connection from', addr while True: message = raw_input("&gt;&gt;") s.sendall(message) try: print s.recv(1024) except: print "" client.py: import socket s = socket.socket() host = "127.0.0.1" port = 5409 s.connect((host, port)) while True: print s.recv(1024) message = raw_input("&gt;&gt;") s.send(message) I have been trying for a while and I have found nothing online other than a server and client that send data once between them and then close the connection. What can I do?
tagged with: python

http://stackoverflow.com/a/48609919
score: 1
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/48609356
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48609356
has body: It's simpler to just use pandas read_json to read the file into a data frame, read_json will automatically assign the apt datatype to each column, then use column selection to select 'name','price_usd' columns (of-course in this case there is only one row, but the same code can be used with multiple rows) i.e. import pandas as pd df = pd.read_json('https://api.coinmarketcap.com/v1/ticker/eos/') print(df'name','price_usd'.apply(lambda row:'{}: {:.0f}'.format(ro w['name'],row['price_usd']),axis=1)) using .0f in the format statement will display the integer part (rounded) of the price_usd value so the output will be. 0 EOS: 9 alternatively using the round function will round the float values i.e. In [34]: import pandas as pd ...: df = pd.read_json('https://api.coinmarketcap.com/v1/ticker/eos/') ...: print(df'name','price_usd'.apply(lambda row:'{}: {:}'.format(row['n ...: ame'],round(row['price_usd'],2)),axis=1)) ...: ...: 0 EOS: 8.99 dtype: object

http://stackoverflow.com/comment/84073289
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48538404
has text: It seems tf has been changed since the tutorial was created. Check https://www.tensorflow.org/versions/r1.0/programmers_guide/reading_data

http://stackoverflow.com/a/48516226
score: 0
type: Answer
has body: If this is not just a copy paste mistake, you are (probably) missing a " at the end of the _svc_description_
answers question: http://stackoverflow.com/q/48516078

http://stackoverflow.com/comment/84067966
type: Comment
comment on: http://stackoverflow.com/a/48536161
type: AnswerComment
has text: Yes, that error is now gone after exporting the env var. On running the script again, I get a new error. I have updated the question details to show that error. Please suggest.
score: 0

regex
tags question: http://stackoverflow.com/q/48513031
tags question: http://stackoverflow.com/q/48621161
tags question: http://stackoverflow.com/q/48542738
tags question: http://stackoverflow.com/q/48551790
tags question: http://stackoverflow.com/q/48616871
tags question: http://stackoverflow.com/q/48489107
tags question: http://stackoverflow.com/q/48607966
tags question: http://stackoverflow.com/q/48502217
tags question: http://stackoverflow.com/q/48632503
tags question: http://stackoverflow.com/q/48498379
tags question: http://stackoverflow.com/q/48549204
tags question: http://stackoverflow.com/q/48559569
tags question: http://stackoverflow.com/q/48551160
tags question: http://stackoverflow.com/q/48597958
tags question: http://stackoverflow.com/q/48534703
tags question: http://stackoverflow.com/q/48553196
tags question: http://stackoverflow.com/q/48534389
tags question: http://stackoverflow.com/q/48527267
tags question: http://stackoverflow.com/q/48567257
tags question: http://stackoverflow.com/q/48613653
tag name: regex
tags question: http://stackoverflow.com/q/48615190
tags question: http://stackoverflow.com/q/48605379
tags question: http://stackoverflow.com/q/48514897
tags question: http://stackoverflow.com/q/48561729
tags question: http://stackoverflow.com/q/48586146
tags question: http://stackoverflow.com/q/48612635
tags question: http://stackoverflow.com/q/48532943
tags question: http://stackoverflow.com/q/48535129
tags question: http://stackoverflow.com/q/48630019
tags question: http://stackoverflow.com/q/48627303
tags question: http://stackoverflow.com/q/48537236
tags question: http://stackoverflow.com/q/48602589
tags question: http://stackoverflow.com/q/48573424
tags question: http://stackoverflow.com/q/48602779
tags question: http://stackoverflow.com/q/48505891
tags question: http://stackoverflow.com/q/48504316
tags question: http://stackoverflow.com/q/48571554
tags question: http://stackoverflow.com/q/48640098
tags question: http://stackoverflow.com/q/48629606
tags question: http://stackoverflow.com/q/48493008
tags question: http://stackoverflow.com/q/48600143
tags question: http://stackoverflow.com/q/48524894
tags question: http://stackoverflow.com/q/48536295
tags question: http://stackoverflow.com/q/48615852
tags question: http://stackoverflow.com/q/48571463
tags question: http://stackoverflow.com/q/48587537
tags question: http://stackoverflow.com/q/48593142
tags question: http://stackoverflow.com/q/48522744
tags question: http://stackoverflow.com/q/48610983
tags question: http://stackoverflow.com/q/48550856
tags question: http://stackoverflow.com/q/48553106
tags question: http://stackoverflow.com/q/48610288
tags question: http://stackoverflow.com/q/48603593
tags question: http://stackoverflow.com/q/48579865
tags question: http://stackoverflow.com/q/48640490
tags question: http://stackoverflow.com/q/48534348
tags question: http://stackoverflow.com/q/48498641
tags question: http://stackoverflow.com/q/48508068
tags question: http://stackoverflow.com/q/48510641
tags question: http://stackoverflow.com/q/48611167
tags question: http://stackoverflow.com/q/48516799
tags question: http://stackoverflow.com/q/48519461
tags question: http://stackoverflow.com/q/48488712
tags question: http://stackoverflow.com/q/48559745
tags question: http://stackoverflow.com/q/48604325
tags question: http://stackoverflow.com/q/48489530
tags question: http://stackoverflow.com/q/48588490
tags question: http://stackoverflow.com/q/48603602
tags question: http://stackoverflow.com/q/48621173
tags question: http://stackoverflow.com/q/48629258
tags question: http://stackoverflow.com/q/48600219
tags question: http://stackoverflow.com/q/48600481
tags question: http://stackoverflow.com/q/48501159
tags question: http://stackoverflow.com/q/48491875
type: Tag
tags question: http://stackoverflow.com/q/48581588
tags question: http://stackoverflow.com/q/48585330
tags question: http://stackoverflow.com/q/48530091
tags question: http://stackoverflow.com/q/48579680

http://stackoverflow.com/comment/84232231
score: 0
type: AnswerComment
has text: @aja It is the same.
comment on: http://stackoverflow.com/a/48617820
type: Comment

http://stackoverflow.com/a/48512238
has body: int('',2), or any other base, raises ValueError. You omitted the rest of the stack trace (bad idea), but there must be a bintoDec(0) call, possibly with the 0 being the value of some other variable.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48512194

http://stackoverflow.com/q/48500092
has title: Django Migration is not apply new migrations
has comment: http://stackoverflow.com/comment/83996564
tagged with: python
type: Question
linked to: http://stackoverflow.com/q/25958708
has answer: http://stackoverflow.com/a/48513833
has body: I tried to make new migrations but show me error. I am using django1.9 and python 2.7 .Is any solution for this so i can create new migration.How can I do the migration? django.db.utils.IntegrityError: could not create unique index "appointments_userappointments_advance_c37857a7_uniq" DETAIL: Key (advance, status)=(5000, 3) is duplicated. Here is my model: class UserAppointments(models.Model): """ Represent an Appointment entity """ STATUS = ( ("1", 'Scheduled'), ("2", 'Active'), ("3", 'Completed'), ("4", 'Cancelled') ) customer = models.ForeignKey(Customer, null=True, blank=True) staff_user = models.ForeignKey(StaffUser, null=True, blank=True, related_name='staff_user') service = models.ForeignKey(Service, null=True, blank=True) advance = models.IntegerField(default=0, null=True, blank=True) date_time = models.DateTimeField(auto_now_add=True) creation_date = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(StaffUser, null=True, blank=True, related_name='created_by') update_date = models.DateTimeField(auto_now=True, null=True, blank=True) updated_by = models.ForeignKey(StaffUser, null=True, blank=True, related_name='updated_by') status = models.CharField(max_length=1, default=1, choices=STATUS) class Meta: verbose_name_plural = 'Appointments' ordering = ['date_time'] def __unicode__(self): return self.date_time.strftime("%Y-%m-%d %H:%M:%S") and my migration file: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('appointments', '0009_auto_20180114_1838'), ] operations = [ migrations.AlterModelOptions( name='userappointments', options={'ordering': ['advance'], 'verbose_name_plural': 'Appointments'}, ), migrations.AlterUniqueTogether( name='userappointments', unique_together=set([('advance', 'status')]), ), ]
type: UnansweredQuestion
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/83994038
has comment: http://stackoverflow.com/comment/83994252
has comment: http://stackoverflow.com/comment/83994188
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/83993700
comment on: http://stackoverflow.com/a/48498570
score: 0
type: AnswerComment
has text: Do you happen to know how to display dates as `Jan 01, 2001` instead of `2001-01-01`?
type: Comment

http://stackoverflow.com/a/48561936
upvote count: 12
downvote count: 0
has body: Insert is a smart choice, you can use list comprehensions (slicing) as well. Depending on which side of an uneven items list you want to insert you might want to use lst = [1, 2, 3, 4, 7, 8, 9] midpoint = len(lst)//2 # for 7 items, after the 3th lst = lst[0:midpoint] + [5] + lst[midpoint:] print (lst) # =&gt; [1, 2, 3, 5, 4, 7, 8, 9] or lst = [1, 2, 3, 4, 7, 8, 9] midpoint = len(lst)//2+1 # for 7 items, after the 4th lst = lst[0:midpoint] + [5] + lst[midpoint:] print (lst) # =&gt; [1, 2, 3, 4, 5, 7, 8, 9]
type: Answer
answers question: http://stackoverflow.com/q/48561673
score: 12

http://stackoverflow.com/comment/84173864
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48588250
has text: Revised question with code, posted.
type: Comment

http://stackoverflow.com/a/48493360
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83980071
downvote count: 0
has body: You don't compute the same thing. The first two commands only compute one row/column out of the entire array. a[0, :].sum().shape # sums just the first row only () The second two commands, sum the entire contents of the 2D array, but along a certain axis. That way, you don't get a single result (as in the first two commands), but an 1D array of sums. a.sum(axis=0).shape # computes the row-wise sum for each column (5000,) In summary, the two sets of commands do different things. a array([[1, 6, 9, 1, 6], [5, 6, 9, 1, 3], [5, 0, 3, 5, 7], [2, 8, 3, 8, 6], [3, 4, 8, 5, 0]]) a[0, :] array([1, 6, 9, 1, 6]) a[0, :].sum() 23 a.sum(axis=0) array([16, 24, 32, 20, 22])
answers question: http://stackoverflow.com/q/48493343

http://stackoverflow.com/comment/84007871
type: QuestionComment
comment on: http://stackoverflow.com/q/48506707
type: Comment
has text: These are just values in the df. I just read them from an excel sheet.
score: 0

http://stackoverflow.com/comment/84142680
type: QuestionComment
type: Comment
score: 0
has text: https://stackoverflow.com/questions/20309456/call-a-function-from-another-file-in-python
comment on: http://stackoverflow.com/q/48572629

multithreading
tags question: http://stackoverflow.com/q/48504348
tags question: http://stackoverflow.com/q/48503499
tags question: http://stackoverflow.com/q/48569867
tags question: http://stackoverflow.com/q/48514640
tags question: http://stackoverflow.com/q/48539989
tags question: http://stackoverflow.com/q/48636568
tags question: http://stackoverflow.com/q/48603741
tags question: http://stackoverflow.com/q/48511429
type: Tag
tags question: http://stackoverflow.com/q/48614055
tags question: http://stackoverflow.com/q/48528247
tags question: http://stackoverflow.com/q/48551440
tags question: http://stackoverflow.com/q/48611337
tags question: http://stackoverflow.com/q/48513703
tags question: http://stackoverflow.com/q/48596046
tags question: http://stackoverflow.com/q/48596294
tags question: http://stackoverflow.com/q/48635007
tags question: http://stackoverflow.com/q/48522725
tags question: http://stackoverflow.com/q/48517984
tags question: http://stackoverflow.com/q/48516832
tags question: http://stackoverflow.com/q/48551679
tags question: http://stackoverflow.com/q/48621025
tags question: http://stackoverflow.com/q/48527702
tags question: http://stackoverflow.com/q/48608845
tags question: http://stackoverflow.com/q/48514410
tags question: http://stackoverflow.com/q/48630476
tags question: http://stackoverflow.com/q/48626785
tags question: http://stackoverflow.com/q/48496634
tags question: http://stackoverflow.com/q/48642337
tags question: http://stackoverflow.com/q/48510355
tags question: http://stackoverflow.com/q/48598589
tags question: http://stackoverflow.com/q/48584712
tags question: http://stackoverflow.com/q/48575815
tags question: http://stackoverflow.com/q/48552149
tags question: http://stackoverflow.com/q/48495288
tags question: http://stackoverflow.com/q/48531469
tags question: http://stackoverflow.com/q/48594411
tags question: http://stackoverflow.com/q/48618709
tags question: http://stackoverflow.com/q/48595660
tags question: http://stackoverflow.com/q/48492459
tags question: http://stackoverflow.com/q/48585318
tag name: multithreading
tags question: http://stackoverflow.com/q/48632225
tags question: http://stackoverflow.com/q/48643123
tags question: http://stackoverflow.com/q/48622638

http://stackoverflow.com/q/48571652
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48571797
tagged with: pandas
answer count: 1
type: Question
has title: Python: pandas dataframe comparison of rows with the same value in one column
accepted answer: http://stackoverflow.com/a/48571797
has body: I have a dataframe which looks like: id name num_1 num_2 1 A 12 14 1 A 15 2 B 10 9 3 C 19 18 3 C 16 My desired output would be: id name num_1 num_2 1 A 12 14 1 A 15 Basically I want rows with the same id where num_1 of the second row is greater than num_2 of the first row. Dataframe is sorted by id and num_1. There might be ids where I only have one row for them and should be excluded from the final dataframe. I know I can iterate through the dataframes to get what I am looking for but am wondering if there is a better way of doing this. I have also tried to use shif to make it work but it gives me the incorrect results: id name num_1 num_2 1 A 15 2 B 10 9 3 C 19 18 Thanks

http://stackoverflow.com/q/48632878
type: Question
has title: QGraphicsPixmapItem.setScale set pixel boundaries at inconsistant positions
has comment: http://stackoverflow.com/comment/84405881
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84263179
tagged with: qt
tagged with: c++
has comment: http://stackoverflow.com/comment/84391317
answer count: 0
tagged with: pyqt
score: 1
has comment: http://stackoverflow.com/comment/84263061
downvote count: 0
upvote count: 1
has body: I want to zoom on an image using QGraphicsPixmapItem.setScale. However the scaling starts being very shaky at high magnification levels, i.e. when only a few pixels fill the window. I observe the same phenomenon in PyQt 4.8.7 and 5.6.0, on Windows 10 as well as Ubuntu 16.10. EDIT: tested on the more recent PyQt 5.10, with the same outcome. EDIT: tested in plain C++ Qt as well, see below. Here is an example where the scaling factor being controlled by the mouse wheel. import numpy as np try: from PyQt5.QtCore import Qt, QRectF from PyQt5.QtGui import QImage, QPixmap from PyQt5.QtWidgets import QApplication, QGraphicsScene, QGraphicsView, QMainWindow qt_ver = 5 except: from PyQt4.QtCore import Qt, QRectF from PyQt4.QtGui import QImage, QPixmap from PyQt4.QtGui import QApplication, QGraphicsScene, QGraphicsView, QMainWindow qt_ver = 4 app = QApplication([]) class MyGraphicsView(QGraphicsView): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.scene = QGraphicsScene(QRectF()) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setScene(self.scene) im = np.random.randint(255, size=(100, 100, 3), dtype=np.uint8) qim = QImage(im, 100, 100, QImage.Format_RGB888) pix = QPixmap.fromImage(qim) self.pixi = self.scene.addPixmap(pix) self.pixi.setOffset(-50, -50) self.zoom = 0 def wheelEvent(self, event): if qt_ver == 5: delta = event.angleDelta().y() else: delta = event.delta() if delta &gt; 0: self.zoom += 1 elif delta &lt; 0: self.zoom -= 1 self.pixi.setScale(np.exp(self.zoom * 0.1)) window = QMainWindow() window.setGeometry(100, 100, 900, 900) view = MyGraphicsView(window) window.setCentralWidget(view) window.show() app.exec() It looks like scaling is suffering from rounding issues. Am I doing something wrong? Same behavior in C++, this is not a PyQt/python issue. I am wondering if that could be due to a discretization effect due to the poor precision of float32? That could be hard to f…
favorite count: 0

http://stackoverflow.com/a/48570001
has comment: http://stackoverflow.com/comment/84136939
answers question: http://stackoverflow.com/q/48569243
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: No part of your grammar allows parentheses in the input, which is why pyparsing stops parsing once it encounters a parenthesis. You can allow parentheses around conditions with a small tweak to your definition of logic: cond_chain_with_parentheses = pp.Forward() cond_chain = cond + pp.Optional(joint + cond_chain_with_parentheses) cond_chain_with_parentheses &lt;&lt;= cond_chain | '(' + cond_chain + ')' logic = cond_chain_with_parentheses + pp.StringEnd() Here, I've used a forward declaration of cond_chain_with_parentheses, which allows me to use it in the grammar definition even though it's not defined yet. I've also added StringEnd so that an exception is thrown if not the entire input can be parsed. This grammar can parse all of your inputs correctly: &gt;&gt;&gt; logic.parseString("b &gt; 2 and (a == 3 or d &gt; 2 or c &lt; 1)") Condition: [6, '&gt;', 2] Condition: [3, '==', 3] Condition: [4, '&gt;', 2] Condition: [2, '&lt;', 1] ([True, 'and', '(', True, 'or', True, 'or', False, ')'], {'condition': [True, True, True, False]})
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48569243

http://stackoverflow.com/comment/109007772
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48526687
score: 0
has text: A widely used, successful, Pythonic web framework is Django. I write code like Django's source every day I'm at work. I look at Django's source about as much as I look at its documentation. I am not fired for writing unreadable "look how clever I am" code such as what appears in the OP. It follows that there may be some connection between that, and the lack of a "continuation-based web framework" competitor to Django.

http://stackoverflow.com/q/48604184
has answer: http://stackoverflow.com/a/51598297
type: Question
has comment: http://stackoverflow.com/comment/84205310
answer count: 2
tagged with: exponential
tagged with: python-ggplot
tagged with: forecasting
downvote count: 0
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/51598297
has answer: http://stackoverflow.com/a/48684063
favorite count: 0
accepted answer: http://stackoverflow.com/a/48684063
has title: Python Simple Exponential Smoothing
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84306295
score: 1
has body: I downloaded a TESLA stock from www.nasdaq.com; and after I downloaded the CSV file I realized that I need convert the CSV by using Microsoft Excel 2016. I use the Data Tab; and click Text to Columns. The header is clear now, they are: date, close, volume, open, high, low. Please see the csv file here. LinK: https://drive.google.com/open?id=1cirQi47U4uumvA14g6vOmgsXbV-YvS4l Preview (The CSV data is from 02/02/2017 until 02/02/2018): 1. date | close | volume | open | high | low | 2. 02/02/2018 | 343.75 | 3696157 | 348.44 | 351.95 | 340.51| 3. 01/02/2018 | 349.25 | 4187440 | 351.00 | 359.66 | 348.63| The challenge for me is to create a data pointout of each month as close to the first of the month as possible. I filter in the excel file and this is the data what I get. - date | close - 01/02/2018 | 349.25 - 02/01/2018 | 320.53 - 01/12/2017 | 306.53 - 01/11/2017 | 321.08 - 02/10/2017 | 341.53 - 01/09/2017 | 355.40 - 01/08/2017 | 319.57 - 03/07/2017 | 352.62 - 01/06/2017 | 340.37 - 01/05/2017 | 322.83 - 03/04/2017 | 298.52 - 01/03/2017 | 250.02 - 02/02/2017 | 251.55 If I create a Data Point, it becomes like this which is need to create a graph. To display the graph of the original data and the “smoothed data” with simple exponential smoothing or sometimes it is called single exponential smoothing. This is more about Time Series Forecasting which uses python-ggplot. - x | y - 01/02/2018 | 349.25 - 02/01/2018 | 320.53 - 01/12/2017 | 306.53 - 01/11/2017 | 321.08 - 02/10/2017 | 341.53 - 01/09/2017 | 355.40 - 01/08/2017 | 319.57 - 03/07/2017 | 352.62 - 01/06/2017 | 340.37 - 01/05/2017 | 322.83 - 03/04/2017 | 298.52 - 01/03/2017 | 250.02 - 02/02/2017 | 251.55 The python program which I wrote is: # -*- coding: utf-8 -*- """ Created on Sat Feb 3 13:20:28 2018 @author: johannesbambang """ import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates my_data = pd.read_csv('C:\TESLA Exponential Smoothing\TSLA.csv',dayfirst=True,index_col=0) my_data.plot() p…

http://stackoverflow.com/comment/121868230
comment on: http://stackoverflow.com/a/68956894
score: 0
type: AnswerComment
has text: This has already been mentioned in [Soorena's answer](https://stackoverflow.com/a/51678318/2227743).
type: Comment

http://stackoverflow.com/q/48645166
tagged with: python
tagged with: mysql
has comment: http://stackoverflow.com/comment/84290868
has body: I have been refactoring some code to use SQLALchemy but have been using Flask framework so have been using the extension Flask-SQLAlchemy. I run a query on my model that has two inner join and where clauses on it. This can be seen below; rows = Master.query.join( Company, Master.company == Company.company_id ).join( Countries, Master.country_id == Countries.country_id ).filter( ((Master.relevant == 1) | (Master.relevant == 0)), ((Master.displayed == 0) | (Master.displayed == 1)), Master.sent == 0, Master.date &gt;= '2017-12-31 23:59:59' ).with_entities( Master.id, Countries.country_name, Company.company_name, Master.date, Master.info, Master.link ).order_by(Master.date.desc()) However as I want to populate flask-wtforms I have created the form class; class BusinessOps(FlaskForm): id = TextField('id', [Required()]) company = TextField('company', [Required()]) country = TextField('country', [Required()]) date = TextField('date', [Required()]) info = TextField('info', [Required()]) link = TextField('link', [Required()]) then in my view I have the following; @app.route('/business-ops', methods=['GET', 'POST']) @login_required def buisness_opportunities(): rows = Master.query.join( Company, Master.company == Company.company_id ).join( Countries, Master.country_id == Countries.country_id ).filter( ((Master.relevant == 1) | (Master.relevant == 0)), ((Master.displayed == 0) | (Master.displayed == 1)), Master.sent == 0, Master.date &gt;= '2017-12-31 23:59:59' ).with_entities( Master.id, Countries.country_name, Company.company_name, Master.date, Master.info, Master.link, # Master.relevant, # Master.displayed, # Master.sent ).order_by(Master.date.desc()) print(type(rows)) form = BusinessOps(obj=rows) print(form.data) #returns dict with null values for keys return render_template('business-ops.html', form=form) Originally when I run this code together, I received no output, so I tested by printing form.data and saw it returned me an empty value dictionary. So I then printed the…
linked to: http://stackoverflow.com/q/23712986
has comment: http://stackoverflow.com/comment/84290313
answer count: 0
tagged with: flask-wtforms
type: UnansweredQuestion
tagged with: flask
tagged with: flask-sqlalchemy
has title: How to pass Flask-SQLAlchemy base query class to Flask-wtforms
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84290456

http://stackoverflow.com/q/48560527
accepted answer: http://stackoverflow.com/a/48560714
downvote count: 1
has comment: http://stackoverflow.com/comment/84116836
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48560714
score: 0
has title: List as python dict element (adding and updating)
possible better answer: http://stackoverflow.com/a/48560804
has answer: http://stackoverflow.com/a/48560804
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84116760
answer count: 2
upvote count: 1
tagged with: python
tagged with: dictionary
has body: I get totally confused with this task. Here's the problem: I need to check all ip belongs to certain domains and then put into a dict a domains with shared one IP. So here's the code I wrote: def check_ip(domain): ip = socket.gethostbyname(domain) return ip def worker_function(input_queue, output_queue): global list_unvalid, list_valid, ips_domains while True: try: data = input_queue.get_nowait() except queue.Empty: break parts = re.findall('http(s)*://(.+?)/(.+)$', data) domain = parts[0][1] print("checking " + domain) try: ip = check_ip(domain) with mylock: ips_domains[ip].append(domain) #output_queue.put_nowait(data) except Exception as e: print('Exception ' + str(e)) input_queue.task_done() But instead I've got an exception "Exception 'ip here'" every time. I think something wrong with the syntax, that appends values to the dict. What am I doing wrong? Thank you.

http://stackoverflow.com/a/48574931
has comment: http://stackoverflow.com/comment/84149567
has body: For Bash 4: #!/bin/bash declare -A astr while IFS=, read -r col1 col2 do if [ "$col1" != "SKU" ] &amp;&amp; [ "$col1" != "" ] then (( astr[$col1] += col2 )) fi done &lt; 2asg.csv echo "SKU,QTY" for i in "${!astr[@]}" do echo "$i,${astr[$i]}" done | sort -t : -k 2n https://github.com/tigertv/stackoverflow-answers
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/84149660
answers question: http://stackoverflow.com/q/48574132

http://stackoverflow.com/q/48568462
downvote count: 1
has title: Can not connect to JupyterHub(using Python 3) - Errormessage: [Errno 8] nodename nor servname provided, or not known
score: 0
has answer: http://stackoverflow.com/a/74838589
has answer: http://stackoverflow.com/a/48597180
tagged with: python
tagged with: jupyter
tagged with: macos
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
upvote count: 1
tagged with: pip
has body: Unable to connect to JupyterHub after installation I just installed JupyterHub and a new installation on pip3. My OS is MacOS Sierra. It seems a bit weird that it tried to connect to Malins-Macbook-Air. When I type $HOSTNAME in the terminal I get an empty string out, while when I type hostname it gives me Malins-Macbook-Air.local. When I try to connect to jupyterHub, I get the following error: ⋊&gt; ~/S/I/inf5860_oblig1 on master ⨯ jupyterhub 17:44:39 [I 2018-02-01 17:44:42.484 JupyterHub app:834] Loading cookie_secret from /Users/malinaandahl/Skole/INF5860/inf5860_oblig1/jupyterhub_cookie_secret [W 2018-02-01 17:44:42.518 JupyterHub app:955] No admin users, admin interface will be unavailable. [W 2018-02-01 17:44:42.519 JupyterHub app:956] Add any administrative users to `c.Authenticator.admin_users` in config. [I 2018-02-01 17:44:42.519 JupyterHub app:983] Not using whitelist. Any authenticated user will be allowed. [I 2018-02-01 17:44:42.566 JupyterHub app:1528] Hub API listening on http://127.0.0.1:8081/hub/ [W 2018-02-01 17:44:42.568 JupyterHub proxy:415] Generating CONFIGPROXY_AUTH_TOKEN. Restarting the Hub will require restarting the proxy. Set CONFIGPROXY_AUTH_TOKEN env or JupyterHub.proxy_auth_token config to avoid this message. [W 2018-02-01 17:44:42.569 JupyterHub proxy:456] Running JupyterHub without SSL. I hope there is SSL termination happening somewhere else... [I 2018-02-01 17:44:42.569 JupyterHub proxy:458] Starting proxy @ http://*:8000/ 17:44:42.771 - info: [ConfigProxy] Proxying http://*:8000 to (no default) 17:44:42.779 - info: [ConfigProxy] Proxy API at http://127.0.0.1:8001/api/routes [E 2018-02-01 17:44:47.582 JupyterHub utils:47] Unexpected error connecting to Malins-MacBook-Air.local:8000 [Errno 8] nodename nor servname provided, or not known [E 2018-02-01 17:44:52.590 JupyterHub utils:47] Unexpected error connecting to Malins-MacBook-Air.local:8000 [Errno 8] nodename nor servname provided, or not known [E 2018-02-01 17:44:57.597 JupyterHub…

http://stackoverflow.com/comment/84202072
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48593103
has text: `sudo type` doesn't necessarily work, as `type` is a shell builtin as opposed to an external executable (and `sudo` directly invokes executables rather than going through in the common case) -- that's why I advised using it specifically for the non-`sudo` test.
score: 0

http://stackoverflow.com/q/48594354
tagged with: pyyaml
has answer: http://stackoverflow.com/a/48599499
has comment: http://stackoverflow.com/comment/84195254
type: Question
has comment: http://stackoverflow.com/comment/84195210
tagged with: python
tagged with: ubuntu
has title: How to pip install compiled libraries like PyYAML without root access on ubuntu
has comment: http://stackoverflow.com/comment/84189333
has comment: http://stackoverflow.com/comment/84200889
type: AnsweredQuestion
score: 0
has body: I am having a terribly difficult time getting the Python module PyYAML to install / compile. I am working in a constrained linux environment (Ubuntu 14.04, I do not have root). I don't think the issue is unique to PyYAML beyond the fact that it is the first library I've needed that requires gcc extensions to build. I have managed to apt-get the following packages in a user folder because I cannot write to root owned folders but could try others if that makes more sense. python2.7-dev python3-dev I've modified a few environment variables that have allowed me to get a partially operational python environment. The apt-get target install is ${DEPS_DIR}/apt: export PYTHONHOME="${DEPS_DIR}/apt/usr" export PYTHONIOENCODING=utf8 export CPATH="${DEPS_DIR}/apt/usr/include/python2.7:${DEPS_DIR}/apt/usr/include" export PATH="${DEPS_DIR}/apt/usr/local/bin" I suspect I'm missing one or more variables or have paths in the wrong order to make this work properly. Most searches on SO for the issue I'm seeing take for granted you can just sudo install. This is the specific error I'm seeing when trying to pip install PyYAML: In file included from ext/_yaml.h:2:0, from ext/_yaml.c:271: /usr/include/yaml.h:633:1: note: expected ‘yaml_char_t *’ but argument is of type ‘char *’ yaml_mapping_start_event_initialize(yaml_event_t *event, ^ x86_64-linux-gnu-gcc: internal compiler error: Killed (program cc1) Please submit a full bug report, with preprocessed source if appropriate. See for instructions. error: command 'x86_64-linux-gnu-gcc' failed with exit status 4 I am using pip -V 9.0.1 and python -V is 2.7.6. I tried to get virtualenv and wrapper installed at one point but didn't seem to really get it working like I can on my laptop.
answer count: 1
tagged with: pip
accepted answer: http://stackoverflow.com/a/48599499

http://stackoverflow.com/q/48610405
answer count: 1
has answer: http://stackoverflow.com/a/70797866
has title: ambari cluster + get status of component/services by tool / python script
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84220769
has comment: http://stackoverflow.com/comment/84224644
type: Question
has body: we have few Hadoop machines , and we use the API in our bash script to get the status of the components or services in the Hadoop cluster from Ambari API I searched in google but without help , but I am almost sure that somewhere there is a tool or python script that already exists , that can capture the component status or services status in the cluster and maybe some other useful options, I will appreciate to get help about this tool / script example: one of our tasks is to get the status of all components/services in the cluster ( prefer not to use each individual API for each component , we prefer one API that will show the status of all the components in the cluster )
tagged with: hadoop
tagged with: ambari
has comment: http://stackoverflow.com/comment/84221245
type: UnansweredQuestion

http://stackoverflow.com/q/48631661
downvote count: 0
accepted answer: http://stackoverflow.com/a/48631736
has title: groupby - selecting only certain groups
has answer: http://stackoverflow.com/a/48631847
has answer: http://stackoverflow.com/a/48631736
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48631765
tagged with: python
linked to: http://stackoverflow.com/q/41821430
score: 2
type: AnsweredQuestion
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
upvote count: 2
has body: I have the below DataFrame, I want to select the Services where there are less than 2 'Healthy' instances of that service. In this case I want the Series (EmailService, UserService, NotificationService) CPU Service Memory Status IP 10.22.11.150 13 StorageService 55 Healthy 10.22.11.90 23 StorageService 19 Healthy 10.22.11.91 10 EmailService 44 Healthy 10.22.11.92 69 UserService 1 Healthy 10.22.11.93 63 NotificationService 81 Healthy 10.22.11.93 87 NotificationService 98 Unhealthy I think I need this grouping, grouped = servers_df.groupby('Service') but not sure how to count the Status column and then get the result based on that.
has answer: http://stackoverflow.com/a/48631765

http://stackoverflow.com/a/48638734
downvote count: 0
answers question: http://stackoverflow.com/q/48638618
has body: You would need nanosecond precision to encode that value - note that you don't have .038002, you have 0.0380002 (extra digit). This is 38000us (rounded), or 38000200ns.
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/84273851
has comment: http://stackoverflow.com/comment/84273812

http://stackoverflow.com/comment/84123342
has text: well have an issue in this for example if i have a for loop like for i in tuple if i filter the user value from the tuple the main tuple where it is currently looping is not modified it still loops through all elements when i remove i want the loop to be modified so that iterations is reduced
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48562597

http://stackoverflow.com/comment/84154798
comment on: http://stackoverflow.com/q/48561631
has text: **get full-duplex rs485 converter !(only 3$(USD))** I'm sure you can't do the read-write schedule. don't waste your time !
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84094302
has text: Whats the desired output from this?
type: QuestionComment
comment on: http://stackoverflow.com/q/48549204
type: Comment
score: 4

http://stackoverflow.com/comment/84050258
type: AnswerComment
has text: @killerbees The one i provided is only a ImageField in a model, you can do the same for another model if you want! It will work in the admin
type: Comment
comment on: http://stackoverflow.com/a/48526277
score: 0

http://stackoverflow.com/q/48496422
tagged with: django
tagged with: python
has body: I have one Django application that has a model Patient which has all the information about the patient and it's blood sample. I wish to have another application that have some fields of the Patient model and I want both the applications to communicate using some sort of web services so the changes made in the first application are reflected in the second . The two applications are running on different servers and have different databases. I'm a novice in Django, please share any resources anyone has. If my question is not clear enough, please let me know with a comment. Thank you
has comment: http://stackoverflow.com/comment/83986880
answer count: 1
has comment: http://stackoverflow.com/comment/83985887
has answer: http://stackoverflow.com/a/48496707
has title: Communication between two Django applications
downvote count: 1
score: -1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83985984
tagged with: rest
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83985834

http://stackoverflow.com/q/48614856
has answer: http://stackoverflow.com/a/48616705
answer count: 2
has body: I tried to use webdriver to login to two websites, A and B. But when I use the same way "find_element_by_css_selector", B was not working while A was working. I turned the javascript off, and find B's login section disappeared. A's html: Login Code of A is working well: submit=driver.find_element_by_css_selector(".width-35.pull-right.btn.btn-sm.btn-primary").click() B's html: Login Code of B is not working: submit=driver.find_element_by_css_selector("a.login-btn > span.btn-text").click() Error says: ElementNotVisibleException: Message: element not visible I posted another question before, Python: find_element_by_css_selector, and someone suggested me to use "find_elements_by_link_text" and it works, but it only works with that one. I would still like to know how to solve this problem. Thanks! Updated: Link=WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='login-btn'][@class='login-btn']"))).click() Error: TimeoutException: Message:
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84226777
possible better answer: http://stackoverflow.com/a/48616705
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84226925
has answer: http://stackoverflow.com/a/48614936
has title: Python: Webdriver is not working with css_selector
downvote count: 0
tagged with: selenium
score: 1
has comment: http://stackoverflow.com/comment/84226845
tagged with: webdriver
linked to: http://stackoverflow.com/q/48578336
accepted answer: http://stackoverflow.com/a/48614936
favorite count: 0
type: Question

http://stackoverflow.com/q/48569525
has comment: http://stackoverflow.com/comment/84137292
type: AnsweredQuestion
has body: I was wondering whether it was possible to aggregate JSON data into new values in python. For example a single JSON value looks like this: {"time": {"Friday": {"20:00": 2, "19:00": 1, "22:00": 10, "21:00": 5, "23:00": 14, "0:00": 2, "18:00": 2}, "Thursday": {"23:00": 1, "0:00": 1, "19:00": 1, "18:00": 1, "16:00": 2, "22:00": 2}, "Wednesday": {"17:00": 2, "23:00": 3, "16:00": 1, "22:00": 1, "19:00": 1, "21:00": 1}, "Sunday": {"16:00": 2, "17:00": 2, "19:00": 1, "22:00": 4, "21:00": 4, "0:00": 3, "1:00": 2}, "Saturday": {"21:00": 4, "20:00": 3, "23:00": 10, "22:00": 7, "18:00": 1, "15:00": 2, "16:00": 1, "17:00": 1, "0:00": 8, "1:00": 1}, "Tuesday": {"19:00": 1, "17:00": 1, "1:00": 2, "21:00": 1, "23:00": 3}, "Monday": {"18:00": 2, "23:00": 1, "22:00": 2}} I want to aggregate it such that it is in four categories based on the times it is open. The four categories are: 6am - 12 noon : morning 12 noon - 5 pm: afternoon 5 pm - 11 pm: evening 11 pm - 6 am: night For example: If this is the current value: “Friday”:{“20:00”: 5,“21:00”: 10} Then the output should be: "Friday": {"morning": 0, "afternoon": 0, "evening": 15, "night": 0} Thus the output should be in the form "Day": {"morning": count, "afternoon": count, "evening": count, "night":count} For all of the hundreds of JSON values. My thinking was that I could create 4 bins representing each of the time zones. I would then use two for loops to go through each days values. If the value is in the range of the bucket I would add it to the count. I would then store the day in a dictionary with the values being a dictionary as well. The inner dictionary would consist of the four time zones with the count as the value. I would then return this for the day and restart for each day. Here's what I have so far, still need to implement the aggregate function. import json from datetime import datetime def cleanStr4SQL(s): return s.replace("'","`").replace("\n"," ") def parseCheckinData(): #write code to parse yelp_checkin.JSON wit…
tagged with: sql
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: file
has answer: http://stackoverflow.com/a/48570743
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84137510
has comment: http://stackoverflow.com/comment/84135524
upvote count: 0
accepted answer: http://stackoverflow.com/a/48570743
tagged with: database
has title: Aggregating JSON values in Python
tagged with: python
score: -1

http://stackoverflow.com/q/48545076
has comment: http://stackoverflow.com/comment/84100979
duplicate of: http://stackoverflow.com/q/49343637
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84100752
has answer: http://stackoverflow.com/a/48545159
score: 6
upvote count: 6
tagged with: python
has comment: http://stackoverflow.com/comment/84099590
has comment: http://stackoverflow.com/comment/84100043
duplicate of: http://stackoverflow.com/q/51737122
has body: I have a (large) dataframe. How can I select specific columns by position? e.g. columns 1..3, 5, 6 Rather than just drop column4, I am trying to do it in this way because there are a ton of rows in my dataset and I want to select by position: df=df[df.columns[0:2,4:5]] but that gives IndexError: too many indices for array DF input Col1 Col2 Col3 Col4 Col5 Col6 1 apple tomato pear banana banana 1 apple grape nan banana banana 1 apple nan banana banana banana 1 apple tomato banana banana banana 1 apple tomato banana banana banana 1 apple tomato banana banana banana 1 avacado tomato banana banana banana 1 toast tomato banana banana banana 1 grape tomato egg banana banana DF output - desired Col1 Col2 Col3 Col5 Col6 1 apple tomato banana banana 1 apple grape banana banana 1 apple nan banana banana 1 apple tomato banana banana 1 apple tomato banana banana 1 apple tomato banana banana 1 avacado tomato banana banana 1 toast tomato banana banana 1 grape tomato banana banana
tagged with: indices
has answer: http://stackoverflow.com/a/48545390
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/40698043
has answer: http://stackoverflow.com/a/48545378
has title: Selecting multiple dataframe columns by position in pandas
tagged with: select
has answer: http://stackoverflow.com/a/48545207
has answer: http://stackoverflow.com/a/48545981
duplicate of: http://stackoverflow.com/q/40698043
favorite count: 0
type: Question

http://stackoverflow.com/comment/84076472
score: 0
comment on: http://stackoverflow.com/q/48540319
type: Comment
type: QuestionComment
has text: @user123892 That's a complete page. If you have one for every link then simply change which link has the active class in each page.

http://stackoverflow.com/comment/84219198
type: Comment
has text: Well pandas has [an entire suite of vectorized string methods](https://pandas.pydata.org/pandas-docs/stable/text.html). Iterable elements just preclude some Pandas functionality. That said it may be right for your use case.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48611234

http://stackoverflow.com/comment/84638458
score: 0
type: Comment
has text: yay!I could do that by using + variable + thing.
type: QuestionComment
comment on: http://stackoverflow.com/q/48613887

nltk
tags question: http://stackoverflow.com/q/48610480
tags question: http://stackoverflow.com/q/48535287
tags question: http://stackoverflow.com/q/48553196
tags question: http://stackoverflow.com/q/48643395
tags question: http://stackoverflow.com/q/48527267
tags question: http://stackoverflow.com/q/48506461
tags question: http://stackoverflow.com/q/48620621
tag name: nltk
tags question: http://stackoverflow.com/q/48607339
tags question: http://stackoverflow.com/q/48545440
tags question: http://stackoverflow.com/q/48619305
tags question: http://stackoverflow.com/q/48532723
tags question: http://stackoverflow.com/q/48508714
tags question: http://stackoverflow.com/q/48630248
tags question: http://stackoverflow.com/q/48566534
tags question: http://stackoverflow.com/q/48606331
tags question: http://stackoverflow.com/q/48627450
tags question: http://stackoverflow.com/q/48526850
tags question: http://stackoverflow.com/q/48585330
type: Tag
tags question: http://stackoverflow.com/q/48521208
tags question: http://stackoverflow.com/q/48628870
tags question: http://stackoverflow.com/q/48492129
tags question: http://stackoverflow.com/q/48611576

http://stackoverflow.com/q/48588316
upvote count: 1
has body: I am building a back end in python via the python flask application from IBM Cloud/Bluemix. I have heard/read a lot about people complaining regarding that Flasks built in server isn’t good for production. But how do I know if the application uses the Flask built in server or if IBM sets something else? Is there a simple way to see this in the code?
downvote count: 1
tagged with: backend
accepted answer: http://stackoverflow.com/a/48588635
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48588635
linked to: http://stackoverflow.com/q/22192519
tagged with: ibm-cloud
linked to: http://stackoverflow.com/q/12269537
tagged with: python
has comment: http://stackoverflow.com/comment/84173986
tagged with: flask
has title: Am I using Python Flasks built in server?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84174156
has comment: http://stackoverflow.com/comment/84173800
answer count: 1
has comment: http://stackoverflow.com/comment/84176998

http://stackoverflow.com/comment/84193077
score: 0
type: Comment
type: AnswerComment
has text: I edited my answer using your logic. It seems to be working. Is there a way to filter it directly? I am not sure whether first is reliable here. I want to filter the results only for the "one" values. What if the "two" is the first?
comment on: http://stackoverflow.com/a/48597281

http://stackoverflow.com/comment/83972605
has text: no, i don't think it's that- I was given the equation which needed to be integrated, and there shouldn't be a minus sign
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48489114

http://stackoverflow.com/comment/84177538
type: AnswerComment
comment on: http://stackoverflow.com/a/48589494
score: 0
type: Comment
has text: @user5834454 It's hard to say without seeing your updated code, but consider this: if your `data` doesn't contain `key` in any of its dictionaries...what will `find_deep_value` return? What will the rest of the code do after that? Without seeing the updated code, I would suspect that's part of the problem.

http://stackoverflow.com/comment/84176504
comment on: http://stackoverflow.com/q/48588919
score: 0
type: Comment
type: QuestionComment
has text: `/Users/myname` is your personal home directory, which is distinct from the system-wide installation belonging to `root` or some similar system account in `/usr/local/bin`. No other user has access to your files, and you should basically be able to remove everything in your home directory without affecting any system-wide functionality. (I don't particularly recommend doing that; definitely don't!)

http://stackoverflow.com/comment/84064802
has text: Sorry. I am getting a little confused. Should I remove this question and ask a new one? I saw it to be marked duplicate, but because someone answered it and I continued this stuff.
score: 0
comment on: http://stackoverflow.com/q/48495799
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48633951
has comment: http://stackoverflow.com/comment/84265073
has answer: http://stackoverflow.com/a/48634055
has title: Why does chained assignment work this way?
accepted answer: http://stackoverflow.com/a/48634055
has comment: http://stackoverflow.com/comment/84264999
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/7601823
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48634041
answer count: 2
has body: I found the assignment a = a[1:] = [2] in an article. I tried it in python3 and python2; it all works, but I don't understand how it works. = here is not like in C; C processes = by right to left. How does python process the = operator?
duplicate of: http://stackoverflow.com/q/32127908
tagged with: python
downvote count: 1
score: 15
upvote count: 16
type: AnsweredQuestion
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/48634041
has comment: http://stackoverflow.com/comment/84265036

http://stackoverflow.com/a/48540908
score: 2
has comment: http://stackoverflow.com/comment/84108316
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48536058
has comment: http://stackoverflow.com/comment/84108154
has body: regex_right_join could be handy in this case. library(fuzzyjoin) library(dplyr) df1 %&gt;% mutate(name = as.character(name)) %&gt;% regex_right_join(df2 %&gt;% mutate(Testcomponents = as.character(Testcomponents)), by = c(name = "Testcomponents"), ignore_case = T) %&gt;% select(Testcomponents, lonic_code) Output is: Testcomponents lonic_code 1 creatinine 27816-8-O 2 blood 33914-3 3 potassium &lt;NA&gt; Sample data: df1 &lt;- structure(list(name = structure(1:4, .Label = c("(CKMB)Creatinine Kinase Muscle &amp; Brain", "24 Hours Urine for Sodium", "Antistreptolysin O Titer", "Blood group O" ), class = "factor"), lonic_code = structure(c(3L, 2L, 1L, 4L ), .Label = c("1869-7", "27816-8-B", "27816-8-O", "33914-3"), class = "factor")), .Names = c("name", "lonic_code"), row.names = c(NA, -4L), class = "data.frame") df2 &lt;- structure(list(Testcomponents = structure(c(2L, 1L, 3L), .Label = c("blood", "creatinine", "potassium"), class = "factor")), .Names = "Testcomponents", row.names = c(NA, -3L), class = "data.frame")
type: Answer
has comment: http://stackoverflow.com/comment/84110506
has comment: http://stackoverflow.com/comment/84110868
answers question: http://stackoverflow.com/q/48536058

http://stackoverflow.com/comment/84255683
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48629253
has text: I'm asking if you're sure that jupyter and VS are talking to the same python interpreter

http://stackoverflow.com/a/48598185
upvote count: 2
type: Answer
has body: Quoting the documentation of configparser.ConfigParser.add_section: add_section(section) Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48598112

http://stackoverflow.com/comment/84286705
comment on: http://stackoverflow.com/q/48643406
has text: Triple quotes in Bash don't exist last time I checked. If the variable is defined in Python, it's still passed unescaped into Bash
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/84121691
score: 2
type: AnswerComment
has text: In the particular case when we're splitting by 0, we could use bool: `[list(g) for k,g in groupby(l, bool) if k]`, as done [long ago](https://stackoverflow.com/a/19391679/487339)..
comment on: http://stackoverflow.com/a/48562980
type: Comment

http://stackoverflow.com/a/48522627
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48522526
has body: If you want to convert a float into a str just use this code my_string = str(my_var) You could try something like that : if isinstance(x, float): x = int(x) sku1_b.append(str(x)) That should get rid of the '.0' you get when converting the float into a string only when needed (when x is a actually a float).
answers question: http://stackoverflow.com/q/48522526
has comment: http://stackoverflow.com/comment/84046875
type: Answer

http://stackoverflow.com/comment/84139881
score: 0
comment on: http://stackoverflow.com/q/48571304
has text: @CodeLikeBeaker I did......
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84317089
type: Comment
type: AnswerComment
has text: since the child process basically has no code to run it will always terminate before 5 seconds are passed, but depending on your os and cpu it could be possible for the signal to arrive **before** you start the sleep, but i wouldn't count on that
score: 1
comment on: http://stackoverflow.com/a/48639552

http://stackoverflow.com/comment/84183370
has text: Possible duplicate of [cx\_Freeze ModuleNotFoundError: No module named 'codecs'](https://stackoverflow.com/questions/47738236/cx-freeze-modulenotfounderror-no-module-named-codecs)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48589991
score: 3

http://stackoverflow.com/q/48602330
favorite count: 0
has answer: http://stackoverflow.com/a/48602360
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48602388
has title: Correlation Matrix labels in Python
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48602388
has comment: http://stackoverflow.com/comment/84201880
tagged with: python
score: 4
type: Question
upvote count: 4
answer count: 2
has body: I'm using Python3. The top of my matrix is a problem, all the labels are overlapping so you can't read them. How do I fix this? Here is my code: import matplotlib.pyplot as plt import pandas import numpy budget_adj revenue_adj mov_data = ['popularity', 'budget', 'revenue', 'runtime', 'vote_average', 'release_year'] #data = pd.read_csv(url, names=names) correlations = db.corr() # plot correlation matrix fig = plt.figure() ax = fig.add_subplot(111) subplotsize=[8.,8.] figuresize=[10.,10.] left = 0.5*(1.-subplotsize[0]/figuresize[0]) right = 1.-left bottom = 0.5*(1.-subplotsize[1]/figuresize[1]) top = 1.-bottom fig.subplots_adjust(left=left,right=right,bottom=bottom,top=top) cax = ax.matshow(correlations, vmin=-1, vmax=1) fig.colorbar(cax) ticks = numpy.arange(0,5,1) ax.set_xticks(ticks) ax.set_yticks(ticks) ax.set_xticklabels(mov_data) ax.set_yticklabels(mov_data) plt.show() An here is what it looks like:
downvote count: 0
accepted answer: http://stackoverflow.com/a/48602360
tagged with: plot

http://stackoverflow.com/comment/84130138
type: QuestionComment
has text: No idea what are you trying to achieve, but it looks like [XY problem](http://xyproblem.info/).
score: 0
comment on: http://stackoverflow.com/q/48566905
type: Comment

http://stackoverflow.com/comment/84021952
has text: This is like RoadRunner's original answer. It is an O(n^2) solution, so very expensive if the lists are long.
comment on: http://stackoverflow.com/a/48513629
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48631746
downvote count: 0
answer count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: linux
type: UnansweredQuestion
tagged with: django
has title: Init django server with start-stop-daemon like a service
tagged with: python
has body: I'm trying to init a virtualenv and runserver command of django project on Ubuntu 16 Linux I create a file on /etc/init.d/initfile with the commands to start and stop service: do_start() { echo -n "Starting " $NAME " ..." if [ -f $PIDFILE ] then echo "\n-&gt; Service " $NAME " is running." else start-stop-daemon --start --background --quiet --name $NAME --pidfile $PIDFILE --make-pidfile --exec $DAEMON echo "\n-&gt; Service " $NAME " started..." fi } and the $DAEMON is a file with: VIRTUALENV_DIR=/home/user/python/DjangoProjects/newEnv1 SITE_DIR=/home/user/python/DjangoProjects/newEnv1/sampleSite source $VIRTUALENV_DIR/bin/activate python $SITE_DIR/manage.py runserver 0:8080 but when I check the process with ps -fu root is generated 3 pid id: 22875, 22878 and 22880 Image with multiple pid ids the problem is, when I execute the stop command only stopped the pid id that include in $PIDFILE but the other is running yet so the server still running. Can you help me please ? thanks

http://stackoverflow.com/a/49126828
has body: The location of the sandbox module got moved into the runtime module. from google.appengine.tools.devappserver2.python import runtime runtime.sandbox._WHITE_LIST_C_MODULES += ['_ssl', '_socket']
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48539511
has comment: http://stackoverflow.com/comment/85264290
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/48571324
type: Answer
has body: Because you are using the -i option. Try it without that and you won't get a stack trace. $ python ptest.py $ python -i ptest.py Traceback (most recent call last): File "ptest.py", line 3, in &lt;module&gt; sys.exit(0) SystemExit: 0
score: 0
answers question: http://stackoverflow.com/q/48571212

http://stackoverflow.com/q/48541671
type: Question
has answer: http://stackoverflow.com/a/73660061
answer count: 2
has answer: http://stackoverflow.com/a/48542879
has title: XGBRegressor score method returning strange values
tagged with: scikit-learn
tagged with: xgboost
possible better answer: http://stackoverflow.com/a/73660061
type: AnsweredQuestion
upvote count: 3
score: 3
accepted answer: http://stackoverflow.com/a/48542879
downvote count: 0
has body: I've tried to use XGBRegressor's score method from the Python API and It's returning a result of 0.917. I am expecting this to be the r2 score of the regression. However, trying r2_score from sklearn on the same package, it returns a different value (0.903) xgbr.score(x_test, y_test) # Returns 0.917 y_pred = xgbr.predict(x_test) r2_score(y_pred, y_test) # Returns 0.903 What's going on? I couldn't find any documentation on XGBoost's score method. I'm using v0.7
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/84197514
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48591267
has text: You still need to post the full traceback otherwise we cannot help you.
type: Comment

http://stackoverflow.com/q/48540267
has body: total_trans_today = Addfuel.objects\ .filter(date_created__year=datetime.today().date().year, date_created__month=datetime.today().date().month, date_created__day=datetime.today().date().day) In above queryset, it gives data for today or day wise, how do i edit it to get data for month or month wise. Please help
accepted answer: http://stackoverflow.com/a/48540437
type: Question
has title: to edit queryset in python django
has comment: http://stackoverflow.com/comment/84075607
tagged with: python
has comment: http://stackoverflow.com/comment/84075680
has answer: http://stackoverflow.com/a/48540437
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: django

http://stackoverflow.com/comment/84008894
comment on: http://stackoverflow.com/a/48504095
has text: Like a web-service, for instance. You provide access to services (functions, methods) inside a module. This module can be accessed via a REST API, using for example a top-down approach as OpenApi specification (https://en.wikipedia.org/wiki/OpenAPI_Specification ).
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84234259
has text: What if I do not want to create another venv
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48617680
type: Comment

http://stackoverflow.com/comment/84212262
has text: Shouldn't `BinarySearchTreeNode` have an `__init__` method?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48607975
type: QuestionComment

http://stackoverflow.com/q/48612316
answer count: 2
tagged with: django-queryset
score: 2
upvote count: 2
tagged with: sql
has answer: http://stackoverflow.com/a/48612967
has body: I have two models: Forum: pk (ID) Thread: pk (ID), last_activity (datetime), forum (foreign key) I want to retrieve all the latest threads, group them by forum and in addition to that get at least the ID of each latest thread. Here's what I tried: Thread.objects.values( 'forum' ).annotate( latest=Max('last_activity') ).order_by() Here's what it produces: &lt;QuerySet [ {'forum': 1, 'latest': datetime.datetime(...)}, {'forum': 2, 'latest': datetime.datetime(...)}, {'forum': 3, 'latest': datetime.datetime(...)}, {'forum': 4, 'latest': datetime.datetime(...)}, {'forum': 5, 'latest': datetime.datetime(...)}, {'forum': 6, 'latest': datetime.datetime(...)} ]&gt; And what it should produce additionally for each entry in the queryset is the ID of the thread that has the greatest value of latest. Here's a sample entry: {'forum': 6, 'latest': datetime.datetime(...), thread_id: 60} Here's the raw query it produces: SELECT "forumapp_thread"."forum_id", MAX("forumapp_thread"."last_activity") AS "latest" FROM "forumapp_thread" GROUP BY "forumapp_thread"."forum_id" ORDER BY "forumapp_thread"."forum_id" ASC Here's the query I want: SELECT "forumapp_thread"."forum_id", "forumapp_thread"."id", MAX("forumapp_thread"."last_activity") AS "latest" FROM "forumapp_thread" GROUP BY "forumapp_thread"."forum_id" ORDER BY "forumapp_thread"."forum_id" ASC
has title: Django get ID of Max after GROUP BY
downvote count: 0
tagged with: django
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48616407
tagged with: python

http://stackoverflow.com/comment/100720064
comment on: http://stackoverflow.com/a/49426867
score: 0
type: AnswerComment
has text: I thought that setting `__name__ = '__main__'` from the Python prompt before running the script also solved it for me. However, on further exploration, it did not. Flask could start, but it could not find the templates folder unless I ran it with PyCharm's "Run" option with "Run with Python console" turned off in the run configurations.
type: Comment

http://stackoverflow.com/comment/84121948
has text: @Aniketpatel in provided example `profile` is model's field. To add writable field to ModelSerializer you need to specify source which is model's field or property.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48562720
type: Comment

http://stackoverflow.com/q/48530293
has answer: http://stackoverflow.com/a/48675615
accepted answer: http://stackoverflow.com/a/48675615
has comment: http://stackoverflow.com/comment/84197587
type: Question
tagged with: google-app-engine
tagged with: python
tagged with: firebase
type: AnsweredQuestion
score: 0
tagged with: firebase-authentication
has body: Firebase-auth.js (3.5.2) Appengine Python Google Cloud Endpoints My login process works great most of the time, but occasionally, a duplicate user account is created. They are timestamped milliseconds apart. I have attempted to put checks in the JS to prevent the duplicates, but I'm still occasionally seeing duplicates. I opened a support ticket with firebase. They instructed me to post the question here instead. The clientConnect endpoint is where the user is created if it does not already exist. Is there a better way to do this? // We are getting duplicate user registrations sometimes because of the way firebase spams refreshes on the page. // Trying to isolate so only one request happens at a time. var checkAuthenticationInProgress = false; firebase.auth().onAuthStateChanged(function(user) { console.log('app.js - onAuthStateChanged') if (user) { console.log('onAuthStateChanged - user found') user.getToken().then(function(idToken) { userIdToken = idToken; $http.defaults.headers.common['X-UETOPIA-Auth'] = 'Bearer ' + userIdToken; checkEndpointsAuthentication(); }}} checkEndpointsAuthentication = function() { if (userIdToken) { if (!checkAuthenticationInProgress) { checkAuthenticationInProgress = true; endpoints.post('users', 'clientConnect', {}) .then(function(response) { // DONE! console.log(response); if (response.refresh_token) { console.log('Firebase Unauth - REFRESHING'); console.log(firebase.auth()); } setTimeout(resetCheckAuthenticationInProgress(), 2000); }, function() { // ERROR! console.log('error'); setTimeout(resetCheckAuthenticationInProgress(), 2000); }); } else { console.log('already checking auth - retrying'); setTimeout(checkEndpointsAuthentication(), 2000); } } else { console.log('no userIdToken found - skipping'); } }; // I think it is being reset too quickly in some cases. resetCheckAuthenticationInProgress = function() { checkAuthenticationInProgress = false; }
has comment: http://stackoverflow.com/comment/84063152
has comment: http://stackoverflow.com/comment/84258421
answer count: 1
has comment: http://stackoverflow.com/comment/84225989
has title: Firebase, Angularfire, Cloud Endpoints - New user registration occasionally results in a duplicate user

http://stackoverflow.com/q/48580625
has answer: http://stackoverflow.com/a/48582927
upvote count: 1
tagged with: math
downvote count: 1
favorite count: 0
type: Question
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/48582927
has comment: http://stackoverflow.com/comment/84159389
answer count: 1
has comment: http://stackoverflow.com/comment/84158070
tagged with: python
has comment: http://stackoverflow.com/comment/84163558
has comment: http://stackoverflow.com/comment/84158823
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84158150
has body: I have a list of line segments represented as x and y coordinates and I'm trying to find groups of lines such that all angles within the group are within 20 degrees. But my problem is that math.degrees(math.atan2(-0.1,-1)) (=-174.29) and math.degrees(math.atan2(0.1,-1)) (=174.29) should make two points in the same group, but the difference in face value is greater than 20. I wonder if my code should do what I want and avoids the 180/-180 problem: import math endpoints = [((2, 11), (2, 8)), ((11, 3), (2, 5)), ((13, 7), (9, 12)), ((5, 5), (15, 12)), ((15, 4), (8, 1)), ((15, 14), (14, 3)), ((2, 4), (6, 5)), ((1, 13), (13, 11)), ((8, 11), (12, 15)), ((12, 4), (7, 1))] def find_angle(p1,p2): x1 = p1[0] y1 = p1[1] x2 = p2[0] y2 = p2[1] dx = max(x2-x1,x1-x2) if dx == x2-x1: dy = y2-y1 else: dy = y1-y2 return math.degrees(math.atan2(dy,dx)) endpointsbyangle = sorted([(find_angle(p1,p2), (p1,p2)) for p1, p2 in endpoints], key=lambda x: x[0]) prev = -190 group = [] allgroups = [] for (theta, (p1, p2)) in endpointsbyangle: if prev == -190: group.append((p1,p2)) prev = theta else: if abs(prev - theta) &lt; 20: group.append((p1,p2)) else: allgroups.append(group) group = [(p1,p2)] prev = theta print dict(enumerate(allgroups)) Any thought appreciated.
score: 0
has title: Finding clusters of line segments in a list

amazon-web-services
tags question: http://stackoverflow.com/q/48548135
tags question: http://stackoverflow.com/q/48509732
tags question: http://stackoverflow.com/q/48608576
tags question: http://stackoverflow.com/q/48516175
tags question: http://stackoverflow.com/q/48539564
tags question: http://stackoverflow.com/q/48639401
tags question: http://stackoverflow.com/q/48525455
tags question: http://stackoverflow.com/q/48514897
tags question: http://stackoverflow.com/q/48641292
tags question: http://stackoverflow.com/q/48551038
tags question: http://stackoverflow.com/q/48636108
tags question: http://stackoverflow.com/q/48521255
tags question: http://stackoverflow.com/q/48611906
tags question: http://stackoverflow.com/q/48508631
tags question: http://stackoverflow.com/q/48571995
tags question: http://stackoverflow.com/q/48517407
tags question: http://stackoverflow.com/q/48491839
tags question: http://stackoverflow.com/q/48615296
tags question: http://stackoverflow.com/q/48608570
tags question: http://stackoverflow.com/q/48541074
type: Tag
tags question: http://stackoverflow.com/q/48638730
tags question: http://stackoverflow.com/q/48512301
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/48506113
tags question: http://stackoverflow.com/q/48619163
tags question: http://stackoverflow.com/q/48632576
tags question: http://stackoverflow.com/q/48640323
tags question: http://stackoverflow.com/q/48526499
tags question: http://stackoverflow.com/q/48635649
tags question: http://stackoverflow.com/q/48554902
tags question: http://stackoverflow.com/q/48601038

http://stackoverflow.com/comment/84197165
type: Comment
type: QuestionComment
has text: Manipulating HTML with regular expressions is usually not a good idea. Google zalgo chtulhu html.
comment on: http://stackoverflow.com/q/48600219
score: 1

http://stackoverflow.com/a/48532271
accepted answer of: http://stackoverflow.com/q/48513139
has comment: http://stackoverflow.com/comment/89389827
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/48513139
type: Answer
downvote count: 0
has body: Fixed, turns out my Flask session was the issue, it was not persisting because the secret key was being randomly generated every time it was launched. I changed the secret key to a static variable and it worked perfectly.
type: AcceptedAnswer

http://stackoverflow.com/q/48604179
answer count: 2
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
has title: verify a list in a list match values of another list in python
has body: I have a list of lists (with tens of thousands of sub-lists). In time more lists are added to the big list, by users. As a mock example I have something similar: my_list_grouped_by_0 = [['X00001', 1123477, 1.25, 'Yes', 'No', 11.53, 3.23, 0.25], ['X00002', 1125251, 0.22, 'Yes', 'No', 22.83, 3.6, 0.5], ['X00003', 1125433, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15], ['X00004', 1231254, 1.3, 'Yes', 'No', 21.83, 3.6, 0.5], ['X00008', 2520250, 54.02, 'Yes', 'No', 1.83, 3.8, 0.01], ['X00005', 3202020, 966.33, 'Yes', 'No', 1.8, 3.8, 0.36], ['X00006', 3215204, 1.36, 'Yes', 'No', 1.86, 3.65, 0.15], ['X00007', 4561230, 6.33, 'Yes', 'No', 1.83, 66.22, 0.1], ['X00009', 5721365, 1.25, 'No', 'No', 11.53, 3.23, 0.25], ['X00010', 8520025, 6.33, 'Yes', 'No', 1.83, 66.22, 0.1], ['X00012', 8520123, 966.33, 'Yes', 'No', 1.8, 3.8, 0.36], ['X00011', 9536122, 54.01, 'Yes', 'No', 1.83, 3.8, 0.01], ['X00015', 1212021, 0.333, 'No', 'No', 1.83, 3.8, 0.01], ['X00013', 9654123, 4.1, 'No', 'No', 1.83, 3.8, 0.01], ['X00014', 2021230, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15], ['X00017', 3322123, 1.23, 'Yes', 'Yes', 1.88, 1.25, 1.12], ['X00016', 9531450, 23.15, 'Yes', 'Yes', 1.83, 3.25, 0.12], ['X00020', 3625252, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15], ['X00018', 1205203, 1.87, 'Yes', 'No', 1.88, 1.25, 1.12], ['X00019', 1124521, 0.25, 'No', 'No', 2.1, 0.6, 0.03], ['X00021', 8952631, 0.25, 'No', 'No', 2.4, 0.6, 0.03], ['X00022', 1123458, 0.33, 'Yes', 'Yes', 10.38, 41.11, 0.5], ['X00023', 3236254, 3, 'No', 'Yes', 10.38, 41.11, 0.5], ['X00024', 1205323, 1.87, 'Yes', 'No', 1.88, 1.25, 1.12]] users will add new lists such as: ['X00099', 1212021, 0.333, 'No', 'No', 1.83, 3.8, 0.01] If the values at index 2,3,4,5,6,7 match with one of the lists in the existing list of list, I want the value at index 0 (in this case X00099) to be overwritten by the value that was in the original list of lists (in this case 'X00015', since values match). In case the new list doesn't match any of the existing list, I want to add next X00…
has answer: http://stackoverflow.com/a/48604292
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48604301
tagged with: python
score: -1
tagged with: list

http://stackoverflow.com/a/48625435
has comment: http://stackoverflow.com/comment/84251575
has comment: http://stackoverflow.com/comment/84258872
has body: Use this code to receive the data: while True: data = self.SOCKET.recv(512) if (len(data) &lt; 1): break print(data.decode()) self.SOCKET.close() # close the socket connection This should work. I cannot be more specific since I don't know the context of your program. Don't copy paste the code, but adjust accordingly. Get back with a feedback if it doesn't work.
answers question: http://stackoverflow.com/q/48625102
score: 3
has comment: http://stackoverflow.com/comment/84254846
type: Answer
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/84021232
type: AnswerComment
has text: Hah. Thanks @Alex! Debugging this thing has been driving me crazy for the past week! Might be related to https://github.com/pandas-dev/pandas/issues/13129 ?
comment on: http://stackoverflow.com/a/48512231
score: 0
type: Comment

http://stackoverflow.com/comment/84264291
type: AnswerComment
score: 0
has text: Hasibur, Did it help?? You understood??
comment on: http://stackoverflow.com/a/48625254
type: Comment

http://stackoverflow.com/a/57856749
answers question: http://stackoverflow.com/q/48574997
type: Answer
has body: Hi I'm faced similar issue. It' looks like port is right. Im my case I was able to get list of dirs, but couldn't write any data. Issue was in my vpn which blocks some of the ports, and read and write uses different one.
score: 0

http://stackoverflow.com/q/48620997
tagged with: set
has comment: http://stackoverflow.com/comment/84238933
has comment: http://stackoverflow.com/comment/84239166
type: Question
has body: I have three sets containing unique elements. I want to add a condition such that if an element is not present in set_out and frozen, then it have to be present in set_general for the downstream process to happen. I am only showing the relevant part of the actual code. I am stuck with writing this condition. Suggestions will be heavily appreciated. Eg: set_out = set([2,4,8,3,5]), frozen = set([2,5,12,15]), set_general = set([2,4,8,3,5,12,15,20,25]). What i want is if an element is not found in set_out and frozen, then that specific element have to be present in set_general for boolean initially to be True. def flipper(set_out,frozen,set_general): initially = False for_symmetric_diff = set_out.symmetric_difference_update(frozen) for i in for_symmetric_diff: if for_symmetric_diff not in set_general: initially = False return False else: initially = True return True
has title: Checking whether elements found in a set is found in another set
tagged with: function
type: UnansweredQuestion
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48621353
score: 0

http://stackoverflow.com/comment/84199716
comment on: http://stackoverflow.com/q/48601441
has text: Is the number of same IDs guaranteed to be 2? Or can tehre also be a row `1 "c" 6`?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/84287980
type: AnswerComment
has text: You are correct sir. That you very much. Python is not my native language, I appreciate your help.
comment on: http://stackoverflow.com/a/48645371
score: 0
type: Comment

http://stackoverflow.com/q/48502428
tagged with: python
has body: I have a csv-file (containing +1000 lines and \t is used as delimiter) that I want to load into Python as a list. Here are the first few lines of the file: "col1" "col2" "col3" "col4" "col5" "col6" 1 "01-01-2017 00:00:00" "02-02-2017 00:00:00" "str1" "str3" "str4 åå here comes a few newline characters " 2 "01-01-2017 00:00:00" "02-02-2017 00:00:00" "str2" "str3" "str5 åasg here comes more newlines " As you can see, the strings tend to contain many newline-characters. Is there a way to strip the strings for all newline characters and then make a list containing all rows? My attempt: Based on this thread here is my attempt: import csv with open('test.dat') as csvDataFile: csvReader = csv.reader(csvDataFile, delimiter="\t") for i in csvReader: print(list(map(str.strip,i))) However, this doesn't strip anything.
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83998379
has comment: http://stackoverflow.com/comment/83998226
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48503488
linked to: http://stackoverflow.com/q/3849509
has title: Load csv in Python and strip newline-characters
type: Question
tagged with: numpy
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48502590

http://stackoverflow.com/q/48592144
favorite count: 0
tagged with: python-3.x
has title: My scraper throws an error instead of continuing on
type: Question
downvote count: 0
tagged with: web-scraping
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/48595921
tagged with: selenium-webdriver
type: AnsweredQuestion
upvote count: 3
score: 3
accepted answer: http://stackoverflow.com/a/48595921
tagged with: selenium
has body: I've created a scraper in python in combination with selenium to collect some information from a site. However, the problem I'm facing is after collecting a single lead the scraper throws an error element is not attached to the page document. Considering the below codes: There are 20 names where the for loop rolls and the scraper is supposed to click each of them. After clicking on the first name it waits in the new page for the document to be available. On that page there is a show more button at the top right corner where it clicks to unwrap the hidden information. (it still stays on the second page, just a new information becomes visible). As soon as the information shows up the scraper collects that successfully. Then it is supposed to get back to the starting page where the loop starts and go for the next name to click. But, instead of clicking on the next name it throws the below error (on the line link.click()). I tried to get rid of the stale element error by using wait.until(EC.staleness_of(item)) but it doesn't work. for link in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"div.presence-entity__image"))): link.click() #error thrown here wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"button[data-control-name='contact_see_more']"))).click() item = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,".pv-contact-info__ci-container a[href^='mailto:']"))) print(item.get_attribute("href")) driver.execute_script("window.history.go(-1)") wait.until(EC.staleness_of(item)) Error I'm having: line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document I tried to depict the picture of what is happening. Any help on this will be highly appreciated.

http://stackoverflow.com/comment/84244478
has text: @F1sher yes that's what you get when the command failed, __as documented__. You did not specify what the output should be when `which` cannot find `jupyter` so I did not add any error handling code. Now it's your job to handle the case as you see fit.
comment on: http://stackoverflow.com/a/48623073
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48589399
tagged with: conda
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
tagged with: pip
has body: I am transitioning from R and would like to use ggplot in the yhat Rodeo IDE. I have tried installing ggplot for python 3.6.3 (Anaconda 5.0.1 64-bit) in a number of ways. When trying to install any kind of ggplot via conda i get this: "UnsatisfiableError: The following specifications were found to be in conflict: -ggplot -zict" I am aware that ggplot does not work with the most recent version of python, so i tried installing an older version and received the same error. I then thought to try pip, and ensured that pip was installed and up to date via conda. In rodeo when i try to use "! pip install ggplot" i get the "pip.exe has stopped working" error. Same for easy_install, etc. Any ideas? It seems that i can't install it in any way.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84176096
tagged with: ggplot2
has title: Installing ggplot in python 3.6.3
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48620666

http://stackoverflow.com/q/48521560
upvote count: 2
accepted answer: http://stackoverflow.com/a/48521611
has answer: http://stackoverflow.com/a/48521611
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84037643
tagged with: pandas
answer count: 1
downvote count: 0
has title: How do I create many filtered dataframes using a for loop in Python and Pandas?
favorite count: 0
type: Question
has body: I find myself having to create dataframes which are filters of a larger dataframe quite often and I was wondering whether there is a way to program Python to do this for me? For example, the dataset I'm working on now is app version data, looks like: user_id | session_id | timestamp | time_seconds | app_version 001 | 123 | 2014-01-01| 251 | v1 002 | 845 | 2014-01-01| 514 | v1 003 | 741 | 2014-01-02| 141 | v1 003 | 477 | 2014-01-03| 221 | v2 004 | 121 | 2014-01-03| 120 | v2 005 | 921 | 2014-01-04| 60 | v3 ... I need to separate out the different app versions so each version has its own dataframe, and currently I'm doing it like this: v1 = all_data[all_data['app_version'] == 'v1'] v2 = all_data[all_data['app_version'] == 'v2'] v3 = all_data[all_data['app_version'] == 'v3'] This seems very repetitive, is there a for loop I can write to do this for me?

http://stackoverflow.com/comment/84122042
comment on: http://stackoverflow.com/q/48556919
has text: With the title fixed and the clarifications here in the comments, I don't think this is unclear any longer, and I have retracted my vote to close as unclear. Thanks for the ping.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84194143
type: AnswerComment
has text: Of course `a, b = reduce(lambda a, b: (a[0] + b[0], a[1] + b[1]), d)` works with directly iterating and storing rather than relying on unpacking, but hardly the greatest readability...
score: 1
comment on: http://stackoverflow.com/a/48598297
type: Comment

http://stackoverflow.com/q/48589360
tagged with: python
tagged with: flask
type: AnsweredQuestion
score: 0
tagged with: mod-wsgi
has title: 404 Requested URL Not Found ( flask app on apache)
has body: I deployed my flask web application on apache web server via mod_wsgi on windows server. I have used WSGIScriptAlias directive. When I try to run the url, I am able to view only the index/first page. When trying to hit post methods, I am unable to navigate to other url routes I have given in flask. It displays:- Not Found The requested URL /login was not found on this server. I have also not configured virtual host in my httpd.conf file. I have used only the alias code as below: &lt;Directory "C:/Users/mypath/flask_phase2"&gt; Require all granted &lt;/Directory&gt; WSGIScriptAlias /flasktest "C:/Users/mypath/flask_phase2/landingpage.wsgi" Alias "/static/" "C:/Users/mypath/flask_phase2/static/" &lt;Directory "C:/Users/mypath/flask_phase2/static/"&gt; Require all granted &lt;/Directory&gt; And my landingpage.wsgi code is as below: import sys sys.path.insert(0,"C:/Users/mypath/flask_phase2") from landingpage import app as application Can someone suggest me with a solution to this problem with this approach or is it necessary to configure virtualhost to make apache server to display all html,static pages as given in the post url method routes in the flask application? Thanks. Appreciate your help.
type: Question
tagged with: apache2.4
accepted answer: http://stackoverflow.com/a/48589439
tagged with: wsgi
has answer: http://stackoverflow.com/a/48589439
answer count: 1

http://stackoverflow.com/q/48535395
favorite count: 0
tagged with: pyspark
tagged with: python
score: -1
has title: pyspark values are missing
type: Question
has body: spark_df = sqlContext.read .format("com.databricks.spark.csv") .option("header", "true") .option("inferSchema", "true") .load(storage_location + filename) I have a normal csv file with multiple columns which contains space. while converting it into pyspark datframe missing values is taken as empty string.and converted it as string column not as int column because age is int column.I want NA,null,empty space as missing values and not converted as string column
tagged with: apache-spark-sql
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48537891
answer count: 1
downvote count: 1

http://stackoverflow.com/q/48623078
answer count: 1
accepted answer: http://stackoverflow.com/a/48623176
has title: Assign index value by bool vector get confusing result
has answer: http://stackoverflow.com/a/48623176
type: AnsweredQuestion
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: Here is the dataframe: import pandas as pd df = pd.DataFrame({'a':[2,5,6,1,2,7,2,0,2,4]}) I want to replace the elements that are larger than 3, so I do this: df['a'][df['a']&gt;3] = [9,99,999,9999] I got the wrong result: a 0 2 1 99 2 999 3 1 4 2 5 99 6 2 7 0 8 2 9 99 The result that I want is this: a 0 2 1 9 2 99 3 1 4 2 5 999 6 2 7 0 8 2 9 9999 However, when the replacement is strings, the result seems right: df['a'][df['a']&gt;3] = ['a','b','c','d'] a 0 2 1 a 2 b 3 1 4 2 5 c 6 2 7 0 8 2 9 d Why this happens and how can I make it right? Thanks!
type: Question
tagged with: boolean
score: 0

http://stackoverflow.com/a/48593613
score: 5
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48592882
has body: Probably because of the wrong syntax here: language: python python: - "3.6" Fix it this way: language: python python: - "3.6"
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48592882
has comment: http://stackoverflow.com/comment/84203266
type: Answer
has comment: http://stackoverflow.com/comment/93288109

http://stackoverflow.com/comment/84037186
type: Comment
type: QuestionComment
has text: By running this code what result you are expecting ?
comment on: http://stackoverflow.com/q/48521293
score: 0

http://stackoverflow.com/comment/84238779
has text: @jp_data_analysis you are right.
score: 0
comment on: http://stackoverflow.com/q/48621161
type: Comment
type: QuestionComment

wxwidgets
tags question: http://stackoverflow.com/q/48628650
tag name: wxwidgets
tags question: http://stackoverflow.com/q/48531006
type: Tag
tags question: http://stackoverflow.com/q/48518575
tags question: http://stackoverflow.com/q/48525743

http://stackoverflow.com/comment/84284056
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48643601
score: 1
has text: What does this mean? How would you identify a user's browser by *sending* a request? And where is your code?

http://stackoverflow.com/q/48568090
has body: I have installed Git on my system and the git command is working fine in the command prompt. I also updated my path varaibles to reflect the address of git bin and cmd. Now, I want to use the following command to install Theano library using Anaconda Prompt - pip install git+git://github.com/Theano/Theano.git The error I am getting is - Error [WinError 2] The system cannot find the file specified while executing command git clone -q git://github.com/fchollet/keras.git C:\Users\Kritika\AppData\Local\Temp\pip-vp5qj204-build Cannot find command 'git' I googled and found a lot of things but nothing seems to work for me. Can anybody help me here?
has title: Git not recognised on Anaconda Prompt
tagged with: anaconda
tagged with: theano
tagged with: python
accepted answer: http://stackoverflow.com/a/48569844
has answer: http://stackoverflow.com/a/48569844
possible better answer: http://stackoverflow.com/a/61508765
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/61508765
score: 0
upvote count: 1
downvote count: 1
tagged with: git
favorite count: 0
type: Question

http://stackoverflow.com/comment/84003363
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48504062
has text: Thank you for the quick feedback. I am asking the question writer to clarify on whether T= True and F = False or if T & F are variables that can take on True/False themselves. Thanks again for helping me think about this one.
type: Comment

http://stackoverflow.com/comment/84024526
score: 0
has text: possible duplicate of https://stackoverflow.com/questions/8371887/making-all-possible-combinations-of-a-list-in-python
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48515039

http://stackoverflow.com/q/48564743
has comment: http://stackoverflow.com/comment/84125683
tagged with: do-while
has comment: http://stackoverflow.com/comment/84125478
has title: How to use the values in a list in 'for' function
has comment: http://stackoverflow.com/comment/84125503
has comment: http://stackoverflow.com/comment/84125377
has comment: http://stackoverflow.com/comment/84135265
tagged with: python
has comment: http://stackoverflow.com/comment/84125572
score: 0
tagged with: list
tagged with: for-loop
answer count: 0
type: UnansweredQuestion
has body: I built variances from 'q1' to 'q76'. Now, I want to use these variances to calculate the percentage of “YES” response for all the variables. I coded as below: lc = pd.DataFrame(pd.read_sas("c:\\Downloads\ps2_hedonic.sas7bdat", format='SAS7BDAT')) Var = ['q'+str(z) for z in range(1,77)] yes = 0 no = 0 VS = lc[Var] for i in VS: if i == 1: yes += 1 else: no += 1 yes/(yes+no) however, I just got 0 from my code. I guess that maybe I should use 'while' function, but I don't know how to do. Here is the output of VS enter image description here
has comment: http://stackoverflow.com/comment/84125842
tagged with: variance
type: Question

http://stackoverflow.com/comment/84175826
type: Comment
comment on: http://stackoverflow.com/q/48589349
score: 0
type: QuestionComment
has text: Do you by any chance use Spyder/Anaconda/Canopy?

http://stackoverflow.com/q/48509902
tagged with: python-3.x
tagged with: kivy-language
has comment: http://stackoverflow.com/comment/134342722
has comment: http://stackoverflow.com/comment/84043792
tagged with: python
has comment: http://stackoverflow.com/comment/84018698
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48591403
has title: update ListProperty variable after for loop kivy
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: kivy
accepted answer: http://stackoverflow.com/a/48591403
favorite count: 0
type: Question
has body: I am using a for loop to cycle the months of the year and then append them to a list rather than manually type out each month. The variable self.mylist updates mylist perfectly fine. When for i in range(1,13): is run it updates self.mylist perfectly fine. But because self.mylist isn't called again it doesn't update mylist after the for loop. Or so i believe is my issue. I think this method is necessary because ListProperty cannot be appended to but can be assigned to? So my question is after the for loop is run how can i update mylist again with self.mylist The kv file includes only the relevant part of the problem. Which functions as intended, to grab a value from the list and display it with text: .py file class Telldate(AnchorLayout): todayday= ObjectProperty('') mylist=ListProperty(['','','','','','','']) print(mylist) def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.todayday=strftime('%A') self.mylist= ['this', 'does','work', 'but'] print(self.mylist) for i in range(1,13): self.mylist.append(calendar.month_name[i]) print(self.mylist) class PlannerApp(App): # def updater(self): # Clock.schedule_interval(self.monthcyclewithglobal, 0.5) def build(self): return Telldate() if __name__ == '__main__': PlannerApp().run() .kv file &lt;Telldate&gt;: --------- ----- -- text:root.mylist[3] Things I've tried but don't seem to work. so I could define another function and use a return statement. def monthcycle(self): self.mylist= ['this', 'does','work', 'but'] print(self.mylist) for i in range(1,13): self.mylist.append(calendar.month_name[i]) print(self.mylist) return self.mylist Or I could use global variables which doesn't seem to encouraged def monthcyclewithglobal(): global mylist mylist= ['this', 'does','work', 'but'] print(mylist) for i in range(1,13): mylist.append(calendar.month_name[i]) print(mylist) monthcyclewithglobal() #I am aware this bit is probably terrible code Hard coding the months in works fine. But I would like automation. Like s…

http://stackoverflow.com/q/48590091
score: 0
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/48590954
has comment: http://stackoverflow.com/comment/84182355
possible better answer: http://stackoverflow.com/a/48590941
type: Question
accepted answer: http://stackoverflow.com/a/48590954
has body: I wrote a small program with Tkinter and user asked me to add a function in which user could able to delete a particular line. My question is how to delete a particular line of text in Tkinter? My code: import tkinter as tk class MainApplication(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.parent.state('zoomed') self.Scrol = tk.Scrollbar(self.parent) self.Text = tk.Text(self.parent, height=50, width=100) self.Scrol.pack(side="right") self.Text.pack() self.Scrol.config(command=self.Text.yview) self.Text.config(yscrollcommand=self.Scrol.set) self.Text.tag_configure('red', foreground='red', underline=1) self.count = 0 self.Text.insert('end', "{} test test test".format(str(self.count)) + "\n", 'red') self.B = tk.Button(self.parent, text="add text", command=self.addText) self.B.pack() self.Text.bind("&lt;Double-Button-1&gt;", self.deleteLine) def deleteLine(self, event): self.Text.delete(1.0, 2.0) def addText(self): self.count += 1 self.Text.insert('end', "{} test test test".format(str(self.count)) + "\n", 'red') root = tk.Tk() app = MainApplication(root) root.mainloop() Now my code only deletes the first line every time when I click on any line. I would like to delete that line which I click on.
has title: Removing a particular line in Text
tagged with: python
has answer: http://stackoverflow.com/a/48590941
type: AnsweredQuestion

http://stackoverflow.com/comment/84260348
comment on: http://stackoverflow.com/a/48627522
has text: pyinstaller program.spec --windowed
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52467429
type: Answer
score: 15
has comment: http://stackoverflow.com/comment/115902388
has body: Using the https://visualstudio.microsoft.com/visual-cpp-build-tools/ installer only and selecting only four specific components helped solve the error.
upvote count: 15
answers question: http://stackoverflow.com/q/48541801
downvote count: 0

http://stackoverflow.com/a/48490327
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/83973821
upvote count: 4
has body: use vectorized np.clip() instead of f - this way you can set both lower (a_min) and upper (a_max) boundaries in one step: y = np.clip(x, a_min=0, a_max=None) or try to vectorize your scalar funcion: In [146]: x = np.linspace(-1000, 1000, 10**6) In [147]: x.shape Out[147]: (1000000,) In [148]: vf = np.vectorize(f) In [149]: %timeit [f(i) for i in x] 1.46 s ± 5.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [150]: %timeit vf(x) 1.03 s ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
has comment: http://stackoverflow.com/comment/83973600
downvote count: 0
answers question: http://stackoverflow.com/q/48490297
has comment: http://stackoverflow.com/comment/83973682
has comment: http://stackoverflow.com/comment/83973579

http://stackoverflow.com/comment/83981169
type: QuestionComment
has text: thanks a lot. I will try the suggestions
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48493722

http://stackoverflow.com/q/48511036
score: 4
has title: Is there a way to interactively turn off the legend in a python `Bokeh` plot
linked to: http://stackoverflow.com/q/39141308
type: Question
upvote count: 4
has body: Hide legend in bokeh plot So I understand who to programmatically turn off the legend in a Bokeh plot, however I was wondering if there is a way to do this interactively? Sometimes I have a number of items in a plot legend, and the legend takes up lot of space or real estate. I was wondering if there is a way to click on the legend to hide it, or some such option? I know I can affect the legend visibility through the code: myPlot.legend.visible = False However I would to be able to turn the legend on and off as I wish.
has answer: http://stackoverflow.com/a/48514249
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48566192
favorite count: 0
tagged with: plot
answer count: 3
has answer: http://stackoverflow.com/a/63391858
tagged with: legend
tagged with: python
tagged with: bokeh

http://stackoverflow.com/q/48550553
tagged with: python
tagged with: dictionary
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48551041
has answer: http://stackoverflow.com/a/48551256
has comment: http://stackoverflow.com/comment/84097258
has title: Converting a list of dicts to wiki-format
has comment: http://stackoverflow.com/comment/84097161
tagged with: confluence
type: Question
has comment: http://stackoverflow.com/comment/84097253
has answer: http://stackoverflow.com/a/48551031
has body: I have a list of dicts that looks like this (might look like this, I really have no idea upfront what data they contain): data = [ {'k1': 'v1-a', 'k2': 'v2-a', 'k3': 'v3-a'}, {'k1': 'v1-b', 'k3': 'v3-b'}, {'k1': 'v1-c', 'k2': 'v2-c', 'k3': 'v3-c'}, {'k1': 'v1-d', 'k2': 'v2-d', 'k3': 'v3-d'} ] The goal is to make it into a string that looks like this: ||k1||k2||k3|| |v1-a|v2-a|v3-a| |v1-b||v3-b| |v1-c|v2-c|v3-c| |v1-d|v2-d|v3-d| This is for the confluence wiki format. The problem in itself is not that complicated, but the solution I come up with is so ugly that I almost don't want to use it. What I got currently is this: from pandas import DataFrame // data = ... df = DataFrame.from_dict(data).fillna('') body = '||{header}||\n{data}'.format( header='||'.join(df.columns.values.tolist()), data='\n'.join(['|{}|'.format('|'.join(i)) for i in df.values.tolist()]) ) Which isn't just ugly, it depends on pandas, which is huge (I don't want to depend on this library just for this)! The solution above would work without pandas if there was a good way of getting the list of headers, and list of list of values from the dict. But python 2 does't guaranty dict order, so I can't count on .values() giving me the correct info. Is there anything in itertools or collections I've been missing out of?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84097313

http://stackoverflow.com/comment/83986419
comment on: http://stackoverflow.com/q/48496662
score: 0
type: Comment
type: QuestionComment
has text: What do you mean by 'It doesn't work'? Can you share with us some code and the error is giving to you?

http://stackoverflow.com/a/48513833
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48500092
has body: It looks like the problem here is that this is a unique together index. So you have at least 2 rows in your database that share the same values for the fields. Thus because the uniqueness guarantee has been violated it cannot great the composite unique index. You may wish to consider using regular composite indexes. Please see these docs for examples: django indexes

http://stackoverflow.com/comment/108325242
score: 0
has text: Thanks for your hard work on this :) This is definitely beyond my skill level. It still doesn't appear to be working. I am getting the same behaviour as before?
type: Comment
comment on: http://stackoverflow.com/a/61198797
type: AnswerComment

http://stackoverflow.com/comment/95914631
type: Comment
type: AnswerComment
has text: I don't think that would work as the multiple calls to `gscv.fit` would clobber the fit from the last dataset. I want each of the calls to `fit` with different datasets to be appended.
score: 0
comment on: http://stackoverflow.com/a/53926120

http://stackoverflow.com/comment/84114184
has text: But this approach requires that the camera image for the 'perspective' view is intrinsically calibrated.
comment on: http://stackoverflow.com/a/48547680
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89677495
type: Comment
comment on: http://stackoverflow.com/q/48637788
type: QuestionComment
score: 0
has text: Did you find any solution? I currently have this issue.

http://stackoverflow.com/comment/84158629
has text: @georgexsh I'm using the same version of Flask-Marshmallow, but I don't get an error when doing `http -f POST localhost:5000 name=tim`. I do get that error if I specify an `id` in the request (`http -f POST localhost:5000 id=42 name=eric`), but I get that error even if I do `ma.init_app(app)` at the end! It looks like I have to init both the flask-sqlalchemy `db` *and* the flask-marshmallow `ma` before I can define any schemas? How am I supposed to avoid declaring everything in `__init__.py`? Should I put `app = Flask("myapp")` in myapp/app.py, then `from myapp.app import app` everywhere else?
score: 0
comment on: http://stackoverflow.com/q/48542822
type: QuestionComment
type: Comment

jupyter
tags question: http://stackoverflow.com/q/48645213
tags question: http://stackoverflow.com/q/48567851
type: Tag
tags question: http://stackoverflow.com/q/48568886
tags question: http://stackoverflow.com/q/48568462
tags question: http://stackoverflow.com/q/48626974
tags question: http://stackoverflow.com/q/48572970
tags question: http://stackoverflow.com/q/48528127
tags question: http://stackoverflow.com/q/48573150
tags question: http://stackoverflow.com/q/48606686
tags question: http://stackoverflow.com/q/48505862
tags question: http://stackoverflow.com/q/48614996
tags question: http://stackoverflow.com/q/48560138
tag name: jupyter

http://stackoverflow.com/comment/84099664
score: 0
type: Comment
type: QuestionComment
has text: @bigreddot You're right, the issue is resolved by using the `'canvas'` backend. But the much greater scrolling performance when plotting half a million points means I'll tolerate this visual glitch and keep using `'webgl'` (`'svg'` choked on it completely). Thanks for identifying the source of the bug though. If you make this an answer, I'll accept it.
comment on: http://stackoverflow.com/q/48533046

http://stackoverflow.com/q/48614648
has body: So I'm building various even-odd checkers. Standard method using python - x%2 == 0 as a boolean. Fine. However, I've read that a different way of checking is to grab the binary string representing the number, then simply check the last digit of the string. If the last digit is 0, it's even, if it's 1, it's odd. For example: 00001011 = 11 Last digit is 1 11 is odd 00001110 = 14 Last digit is 0 14 is even. It would amuse me to no end to be able to build even/odd checkers that use the binary string instead of a %2 check. The only thing I can't figure out, and my google-fu is failing me - how to grab and handle the string? Threads for reference: Compare the last binary digit to 1 in MIPS assembly gives an assembly answer. All of the other threads deal with getting the last digit of a normal number, IE last digit of 12345 is 5, and ignore the "How to read it in binary"
has comment: http://stackoverflow.com/comment/84226403
downvote count: 1
favorite count: 0
type: Question
has title: How to check what the last binary digit of a variable is?
tagged with: binary
duplicate of: http://stackoverflow.com/q/21837208
linked to: http://stackoverflow.com/q/699866
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48614732
duplicate of: http://stackoverflow.com/q/699866
has answer: http://stackoverflow.com/a/48614732
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/13772552
score: 0
linked to: http://stackoverflow.com/q/21837208
answer count: 1

http://stackoverflow.com/comment/84095215
type: AnswerComment
has text: Tks to you Jezrael
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48489784

http://stackoverflow.com/q/48571259
has comment: http://stackoverflow.com/comment/84139549
has comment: http://stackoverflow.com/comment/84147871
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
type: Question
has title: Keras shape not working
has answer: http://stackoverflow.com/a/48575495
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84139250
score: 2
has comment: http://stackoverflow.com/comment/84139190
upvote count: 2
has body: I have been trying to make a auto encoder and i have been having some issues. So i am loading a 32x32 grayscale image into the network and it keeps giving me this error. Using TensorFlow backend. (32, 32, 1) 253.0 Traceback (most recent call last): File "test.py", line 32, in &lt;module&gt; model.fit(out,out, batch_size=16, epochs=10) File "C:\Users\nathanmoosh\Anaconda3_2\lib\site-packages\keras\models.py", line 965, in fit validation_steps=validation_steps) File "C:\Users\nathanmoosh\Anaconda3_2\lib\site-packages\keras\engine\training.py", line 1593, in fit batch_size=batch_size) File "C:\Users\nathanmoosh\Anaconda3_2\lib\site-packages\keras\engine\training.py", line 1426, in _standardize_user_data exception_prefix='input') File "C:\Users\nathanmoosh\Anaconda3_2\lib\site-packages\keras\engine\training.py", line 110, in _standardize_input_data 'with shape ' + str(data_shape)) ValueError: Error when checking input: expected dense_1_input to have 4 dimensions, but got array with shape (32, 32, 1) And this is my code. from keras.models import Sequential from keras.layers import Dense, Activation,Dropout,Flatten from keras.preprocessing import image import numpy img = image.load_img("imgs/test3.jpg", target_size=(32, 32), grayscale = True) x = image.img_to_array(img) out = numpy.array(x) print(out.shape) print(out[0][0][0]) model = Sequential() model.add(Dense(1025, activation='relu', input_shape=(32,32,3))) model.add(Activation('relu')) model.add(Dense(512, activation='relu')) model.add(Activation('relu')) model.add(Dense(128, activation='relu')) model.add(Activation('relu')) model.add(Dense(64, activation='relu')) model.add(Activation('relu')) model.add(Dense(128, activation='relu')) model.add(Activation('relu')) model.add(Dense(512, activation='relu')) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1024, activation='relu')) model.add(Activation('relu')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) model.…

http://stackoverflow.com/q/48493726
tagged with: pandas
score: 2
answer count: 1
downvote count: 0
has title: how can i get a column of multilevel index after pivot_table in pandas?
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has body: dataframe: df = pd.DataFrame({ 'date': [1,1,2,2,3,4,4], 'id': [1,1,1,2,2,2,3], 'item': [200,201,200,333,334,334,444], 'buy': [1,1,2,5,4,0,1] }) df = df'date','id','item','buy' date id item buy 0 1 1 200 1 1 1 1 201 1 2 2 1 200 2 3 2 2 333 5 4 3 2 334 4 5 4 2 334 0 6 4 3 444 1 method1: df2 = df.pivot_table(index=['id','item'], columns=['date'], aggfunc='sum', fill_value=0).reset_index() id item buy date 1 2 3 4 0 1 200 1 2 0 0 1 1 201 1 0 0 0 2 2 333 0 5 0 0 3 2 334 0 0 4 0 4 3 444 0 0 0 1 how can i get a column '1' or '2' or '3' or '4' of 'buy' column? my trial is rename name of columns like this. df2.columns = ["".join((str(i),str(j))) for i,j in df2.columns] id item buy1 buy2 buy3 buy4 0 1 200 1 2 0 0 1 1 201 1 0 0 0 2 2 333 0 5 0 0 3 2 334 0 0 4 0 4 3 444 0 0 0 1 and df2['buy1'], df2.buy2... that what i want here is my question. how can i get a column of multilevel index after pivot_table in pandas? directly on multilevel structure without rename... method 2: df2 = df.groupby(['id','item','date']).buy.sum().unstack(fill_value=0).reset_index() df2.columns.names=[''] id item 1 2 3 4 0 1 200 1 2 0 0 1 1 201 1 0 0 0 2 2 333 0 5 0 0 3 2 334 0 0 4 0 4 3 444 0 0 0 1 if using groupby &amp; unstack like method 2, i can avoid multilevel index problem, though but i still wanna know a method get a column of multilevel index after pivot_table.
accepted answer: http://stackoverflow.com/a/48493762
has answer: http://stackoverflow.com/a/48493762
type: AnsweredQuestion

http://stackoverflow.com/comment/83978493
has text: What isn't working about it? Describe the expected behavior and what actually happens, along with any error messages including the full traceback.
comment on: http://stackoverflow.com/q/48492650
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48641625
tagged with: encryption
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/132836840
has comment: http://stackoverflow.com/comment/132842788
linked to: http://stackoverflow.com/q/44672524
has comment: http://stackoverflow.com/comment/132819161
tagged with: in-memory
has comment: http://stackoverflow.com/comment/84280229
has comment: http://stackoverflow.com/comment/132846585
has answer: http://stackoverflow.com/a/75283410
answer count: 1
score: 24
tagged with: mmap
has title: Path to in-memory-file without dumping in tmp
tagged with: data-protection
upvote count: 24
favorite count: 0
type: Question
has body: Is there a way in python to get the path to the in-memory file, so it'll behave as a normal file for methods which needs file path? My objective is to protect the file, so avoiding dumping into /tmp. Trying to read an encrypted file -> decrypt a file into memory -> use its path for other interfaces. mmap does not provide path or filename. Or any alternative solution for this problem ?
has comment: http://stackoverflow.com/comment/84279816
type: UnansweredQuestion

http://stackoverflow.com/q/48603340
has title: Python 3.5 For loop Set return method
has comment: http://stackoverflow.com/comment/84219951
has comment: http://stackoverflow.com/comment/84203406
upvote count: 2
type: UnansweredQuestion
answer count: 1
tagged with: python
score: 1
downvote count: 1
tagged with: set-comprehension
has comment: http://stackoverflow.com/comment/84203394
has answer: http://stackoverflow.com/a/48603420
has comment: http://stackoverflow.com/comment/84203391
tagged with: loops
has body: I do not understand what these lines are doing. S = {-4 , 4 ,-3 , 3, -2 , 2, -1, 1, 0}; {x for x in S if x >= 0} I know S is a set. I know we are looping through set S but what I don't understand is what is the "x" doing before the for loop? And when I use the print in the function I get error saying: NameError: name 'x' is not defined
favorite count: 0
type: Question

http://stackoverflow.com/comment/84159540
type: Comment
has text: The OP also asked how many IDs were in the list.
type: AnswerComment
comment on: http://stackoverflow.com/a/48581621
score: 1

http://stackoverflow.com/q/48611156
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48611726
type: Question
has body: fig, ax = plt.subplots(1, 2, subplot_kw=dict(projection='polar')) ax[0].set_theta_zero_location("N") ax[0].set_theta_direction(-1) cax = ax[0].contourf(theta, r, values_2d,100) cb = fig.colorbar(cax) cb.set_label("Distance") dax = ax[1].contourf(theta, r, d_values_2d,2) db = fig.colorbar(dax) db.set_label("Gradient") plt.tight_layout(pad=0.4, w_pad=0.5) plt.show() The above figure has two plots on it. I can't find a way to make the colorbar sit with each respective figure, though. Also, they're different sizes, why?
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/48611726
has title: Correctly aligning polar plots in Python with matplotlib
type: AnsweredQuestion

http://stackoverflow.com/q/48622775
has title: Row wise calculations(Python)
tagged with: python
has comment: http://stackoverflow.com/comment/84241933
accepted answer: http://stackoverflow.com/a/48622841
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/48623196
has body: Trying to run the following code to create a new column 'Median Rank': N=data2.Rank.count() for i in data2.Rank: data2['Median_Rank']=i-0.3/(N+0.4) But I'm getting a constant value of 0.99802. Even though my rank column is as follows: data2.Rank.head() Out[464]: 4131 1.0 4173 3.0 4172 3.0 4132 3.0 5335 10.0 4171 10.0 4159 10.0 5079 10.0 4115 10.0 4179 10.0 4180 10.0 4147 10.0 4181 10.0 4175 10.0 4170 10.0 4116 24.0 4129 24.0 4156 24.0 4153 24.0 4160 24.0 5358 24.0 4152 24.0 Somebody please point out the errors in my code.
tagged with: pandas
has answer: http://stackoverflow.com/a/48623196
has answer: http://stackoverflow.com/a/48622841
type: Question
answer count: 2

http://stackoverflow.com/q/48548098
tagged with: python
has body: I have a method inside a Django Model class for a Task, that must return the risk situation of such, based on the comparison of expected start and finish dates with today, but I get an error when I try to compare start_date and finish_date models.DateField with date.today() this is the code of the method: def get_todo_situation(self): if self.finish_date == None: return 'unassigned' elif date.today() &lt; self.start_date: return 'warning' elif date.today() &lt; self.finish_date: return 'danger' else: return 'normal' and this is the error I get: File "/home/hugolvc/Code/TaskManagerProject/TaskManager/TaskManagerApp/models.py", line 63, in get_todo_situation elif date.today() &lt; self.start_date: TypeError: '&lt;' not supported between instances of 'datetime.date' and 'NoneType' I have seen examples where this works, but I think I am failing to grasp something.
score: 0
has comment: http://stackoverflow.com/comment/84092134
tagged with: django-models
has comment: http://stackoverflow.com/comment/84104540
has title: Comparison between DateField and date.today()
type: Question
has comment: http://stackoverflow.com/comment/84092337
answer count: 0
has comment: http://stackoverflow.com/comment/84096786
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/84172819
has text: You can, but preferrably said column should be unique. On the other hand core `Table`s can reflect tables and views without keys, so you could consider that.
comment on: http://stackoverflow.com/q/48563367
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84043780
comment on: http://stackoverflow.com/a/48524020
has text: if you switch median and row, then it works perefctly fine, thanks
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84185479
has text: Ah, sorry for any confusion.. It was kind of hard to be general with my examples but put into words what I wanted. Maybe some context to the data would have helped. X is int value to represent countries, y is years, and z are gdp values of x country at y year
comment on: http://stackoverflow.com/q/48594050
score: 0
type: Comment
type: QuestionComment

enumeration
tag name: enumeration
type: Tag
tags question: http://stackoverflow.com/q/48631810

http://stackoverflow.com/q/48609148
type: AnsweredQuestion
upvote count: 3
score: 3
accepted answer: http://stackoverflow.com/a/48609149
tagged with: python
tagged with: facebook-login
has answer: http://stackoverflow.com/a/48609149
has title: Handle Facebook Deauthorize Callback in Python
linked to: http://stackoverflow.com/q/6102311
favorite count: 0
type: Question
has body: I am building a Django Application that makes use of the Facebook Login using django-allauth. I would like to know when an user removes my corresponding Facebook App, and Facebook provides such functionality in the form of a deauthorize callback. There are also some instructions on how to parse the request using PHP in the documentation. However, translating this into Python doesn't seem to be as easy as I thought, as I am getting 'Padding Errors' when decoding the posted base64-encoded string, which seems very odd to me.
answer count: 1
downvote count: 0
tagged with: django

http://stackoverflow.com/q/48640652
tagged with: python
has answer: http://stackoverflow.com/a/52787726
type: Question
favorite count: 0
tagged with: flask-wtforms
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: Flask-WTF set time limit on CSRF token
upvote count: 7
tagged with: flask
has body: I'm currently using Flask-WTF v0.13.1, i have a few forms on my website, all created including the CSRF token. For some reasons i have to set a different expiration on each form, so far i could set manually the time_limit value upon creating the csrf token. I would like to update to the v0.14, according to the changelog time_limit is gone and there is no reference in the docs on how to change it anymore. Looking in the source code i saw that the form has a csrf_time_limit meta parameter. I tried to set that parameter on my form: from flask_wtf import FlaskForm class myForm(FlaskForm): class Meta: csrf_time_limit = 7200 content = TextAreaField('content') Although debugging the csrf.py module i see that the validate_csrf_token of _FlaskFormCSRF is actually never called. The method validate_csrf is called within the method protect() instead, in this case the meta parameter is never considered. I don't understand if this is a bug of the package or if i'm missing something. UPDATE: Example code: app.py from flask import Flask, render_template, request from flask_wtf.csrf import CSRFProtect from flask_wtf import FlaskForm from wtforms import IntegerField csrf = CSRFProtect() app = Flask(__name__) app.config.update(dict( SECRET_KEY="super secret key" )) csrf.init_app(app) class MyForm(FlaskForm): class Meta: csrf_time_limit = 1 id = IntegerField('id') @app.route("/", methods=['GET', 'POST']) def test_form_csrf(): if request.method == 'POST': myForm = MyForm(request.form) print(myForm.id.data) return render_template('test_form.html', myForm= MyForm()) templates/test_form.html &lt;form method="post" action="/"&gt; &lt;input type="hidden" name="csrf_token" value="{{ csrf_token() }}" /&gt; {{ myForm.id }} &lt;input type="submit" value="test" /&gt; &lt;/form&gt; requirements.txt click==6.7 Flask==0.12.2 Flask-WTF==0.14.2 itsdangerous==0.24 Jinja2==2.10 MarkupSafe==1.0 Werkzeug==0.14.1 WTForms==2.1 project structure app.py templates | --- test_form.html To run the code, FLASK_AP…
score: 7
tagged with: csrf

http://stackoverflow.com/q/48501263
has comment: http://stackoverflow.com/comment/83995720
duplicate of: http://stackoverflow.com/q/6434482
has title: Does Python support function overloading with multiple signatures with different number of positional arguments?
tagged with: python
has comment: http://stackoverflow.com/comment/83995740
has body: Python doesn't seem to support function overloading: &gt;&gt;&gt; def overload(x,y): ... return x*y ... &gt;&gt;&gt; def overload(x,y,z): ... return x*y*z ... &gt;&gt;&gt; overload(1,2) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: overload() takes exactly 3 arguments (2 given) &gt;&gt;&gt; overload(1,2,3) 6 &gt;&gt;&gt; Is it just for a specific version of python or python never supports function overloading?
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/10202938
upvote count: 1
type: UnansweredQuestion
score: 1
duplicate of: http://stackoverflow.com/q/10202938
linked to: http://stackoverflow.com/q/6434482
favorite count: 0
type: Question
tagged with: overloading
has comment: http://stackoverflow.com/comment/84727540

http://stackoverflow.com/comment/84140998
type: Comment
has text: @Matt.St: yes, but here we do not know what version of Python we use. Furthermore within two years support for Python-2.x will stop. https://pythonclock.org/
type: AnswerComment
comment on: http://stackoverflow.com/a/48571793
score: 1

http://stackoverflow.com/q/48574790
has comment: http://stackoverflow.com/comment/84146265
tagged with: jinja2
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
has answer: http://stackoverflow.com/a/60969303
has body: I am using Python 3.6 and Python flask to create a website. I am having a problem with the HTML template inheritance. Parent File: &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta name="viewport" content="width=device-width" /&gt; &lt;meta name="description" content="QuizBowl Practice Tool" /&gt; &lt;meta name="keywoards" content="Altamont, Scholars Bowl, Learn, Enliten,Practice Tool" /&gt; &lt;meta name="author" content="Henry the Dinosaur" /&gt; &lt;title&gt;Enliten | Welcome&lt;/title&gt; &lt;!-- Create a static/styles/base.css?q=1280549787 folder next to template --&gt; &lt;link rel="stylesheet" href="static/styles/base.css?q=1280549787" /&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; {% block script %} {% endblock %} &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;div class="container"&gt; &lt;div id="Logo"&gt; &lt;h1&gt;Enliten&lt;/h1&gt; &lt;/div&gt; &lt;nav&gt; &lt;!-- Links to Login and Practice and stuff--&gt; &lt;ul&gt; &lt;li class="current"&gt;&lt;a href="/"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="current"&gt;&lt;a href="Question"&gt;Question Room&lt;/a&gt;&lt;/li&gt; &lt;li class="current"&gt;&lt;a href="Practice"&gt;Practice&lt;/a&gt;&lt;/li&gt; &lt;li class="current"&gt;&lt;a href="Profile"&gt;Profile&lt;/a&gt;&lt;/li&gt; &lt;li class="current"&gt;&lt;a href="Login"&gt;Login&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/header&gt; {% block content %} {% endblock %} &lt;footer&gt; &lt;p&gt;I will eat you if you try to copy this. Copyright &amp;copy; 2018&lt;/p&gt; &lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; Child : {% extends 'test.html'%} The current issue is the parent HTML code will display the HTML code with the appropriate CSS without issue. However, the Child file creates a white bar on the top of the browser. I tried changing the CSS file, however, I later realized it wasn't an issue because the whitespace still exists …
score: 0
has comment: http://stackoverflow.com/comment/84146378
answer count: 1
has title: Python Flask generate whitespaces when when using template inheritance

http://stackoverflow.com/comment/84766944
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48638592
has text: I faced a similar issue and got out of it by upgrading dependencies

http://stackoverflow.com/comment/84058788
has text: I tried that, and still it just brings me to a 404 error.
type: AnswerComment
comment on: http://stackoverflow.com/a/48531455
type: Comment
score: 0

http://stackoverflow.com/q/48505116
tagged with: openpyxl
answer count: 1
has comment: http://stackoverflow.com/comment/84004531
has comment: http://stackoverflow.com/comment/84004252
tagged with: excel
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56138059
accepted answer: http://stackoverflow.com/a/56138059
has comment: http://stackoverflow.com/comment/84004246
has title: How to add header/footer in chartsheet using Openpyxl
has comment: http://stackoverflow.com/comment/84004376
tagged with: python
type: Question
has body: I tried to add a footer and a header to the chartsheet I made, but when I check the print settings its not there. There's no errors that pop-up either. from openpyxl import Workbook from openpyxl.chart import ScatterChart, Reference, Series wb = Workbook() cs = wb.create_chartsheet() cs.oddHeader.text = "Header" cs.oddFooter.text = "Footer" wb.save("test.xlsx")
score: 0
has comment: http://stackoverflow.com/comment/84004485

http://stackoverflow.com/comment/84145619
type: QuestionComment
has text: Are you looking at the number of digits, or the number of characters when truncating to seven? does `-0.12345678` get truncated to `-0.123456`, `-0.1234567`, or `-0.1234`?
score: 0
comment on: http://stackoverflow.com/q/48574375
type: Comment

http://stackoverflow.com/comment/93922618
has text: Possible duplicate of [How do i edit the favicon in the Browsable API in Django REST framework?](https://stackoverflow.com/questions/46842938/how-do-i-edit-the-favicon-in-the-browsable-api-in-django-rest-framework)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48604710
type: Comment

http://stackoverflow.com/comment/116712837
has text: Trial and error. But I think it must be computable.
type: Comment
comment on: http://stackoverflow.com/a/48626991
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84130478
score: 0
comment on: http://stackoverflow.com/q/48552133
type: Comment
type: QuestionComment
has text: @WarrenWeckesser oh okay. Just for my understanding why doesn't scipy include GPL or LGPL?

http://stackoverflow.com/comment/84000136
type: Comment
type: QuestionComment
has text: Thanks for your comment. Yes, I thought about cropping the images or taking images of lower resolution or/and taking grayscale images. But then I lose pretty valuable information. So I am not sure that this is the best idea. (Also I wonder if I can even run a simple neural network in my laptop as this requires lots of images)
score: 0
comment on: http://stackoverflow.com/q/48502667

http://stackoverflow.com/comment/125496966
type: AnswerComment
comment on: http://stackoverflow.com/a/50808998
has text: This seems to misinterpret the line `k = (N>key_length ? N : key_length);` as implying that *"Anything after the Nth element is never looped over, and therefore effectively discarded. In this case is N is 624 [...], so no more than `625 * 32 = 20,000` input bytes are used."* But that line assigns to k the **maximum** (not minimum) of N and key_length, where key_length is the number of 32-bit chunks from the input -- and this is limited only by available memory.
score: 3
type: Comment

http://stackoverflow.com/comment/84029468
comment on: http://stackoverflow.com/q/48517318
type: Comment
has text: Can you show your settings file ?
type: QuestionComment
score: 0

http://stackoverflow.com/a/48573093
has body: Use itertools: import itertools [x for x in queries.split(',') if len(list(itertools.takewhile(lambda i: i not in x, keywords))) != len(keywords)] Sorry for ugly indenting. The above code stops checking the rest of the keywords once one match is detected.
type: Answer
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/48572674
downvote count: 1

http://stackoverflow.com/q/48638633
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84318982
score: 11
has comment: http://stackoverflow.com/comment/84273787
has comment: http://stackoverflow.com/comment/84273874
has comment: http://stackoverflow.com/comment/84275920
has comment: http://stackoverflow.com/comment/84275139
linked to: http://stackoverflow.com/q/291978
favorite count: 0
type: Question
tagged with: scope
has answer: http://stackoverflow.com/a/48638904
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84274214
has comment: http://stackoverflow.com/comment/84274413
has comment: http://stackoverflow.com/comment/84274888
has comment: http://stackoverflow.com/comment/84274828
has comment: http://stackoverflow.com/comment/84274826
tagged with: python
has comment: http://stackoverflow.com/comment/84274202
has title: Why the difference in handling unbound locals in functions versus classes?
linked to: http://stackoverflow.com/q/5690888
linked to: http://stackoverflow.com/q/13905741
has comment: http://stackoverflow.com/comment/84274108
tagged with: class
has comment: http://stackoverflow.com/comment/84275309
tagged with: attributes
upvote count: 11
has comment: http://stackoverflow.com/comment/84274272
has comment: http://stackoverflow.com/comment/84274735
has body: When referencing global variables, one can see that functions and classes handle this differently. The first is fine and the second causes an error: x = 10 class Foo(): x = x + 1 a = foo() Vs: x = 10 def faa(): x = x + 1 faa() In the Python execution model, this is described as: A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. But why? The only other hint I have come across is this bit: The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. 4 A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. Which still offers no explanation why this should have the consequence that unbound locals are looked up in the global namespace. Both links are from this answer which does not adress the why in more details though.
tagged with: function
linked to: http://stackoverflow.com/q/31614464

http://stackoverflow.com/q/48531530
upvote count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/48531574
has answer: http://stackoverflow.com/a/48531574
favorite count: 0
has answer: http://stackoverflow.com/a/48531703
linked to: http://stackoverflow.com/q/48531843
has answer: http://stackoverflow.com/a/48533301
type: Question
score: 3
has answer: http://stackoverflow.com/a/48532025
has answer: http://stackoverflow.com/a/48532187
tagged with: python
answer count: 6
possible better answer: http://stackoverflow.com/a/48531734
has title: pandas drop where two columns match nested list values
has answer: http://stackoverflow.com/a/48531734
type: AnsweredQuestion
has body: I have a dataframe where I need to drop if any of the combinations in my nested list are met. Here's the sample dataframe: df = pd.DataFrame([['A','Green',10],['A','Red',20],['B','Blue',5],['B','Red',15],['C','Orange',25]],columns = ['Letter','Color','Value']) print df Letter Color Value 0 A Green 10 1 A Red 20 2 B Blue 5 3 B Red 15 4 C Orange 25 I have a list of letter/color combinations that I need to remove from the dataframe: dropList = [['A','Green'],['B','Red']] How can I drop from the dataframe where the letter/color combinations are in any of the nested lists? Approaches I can do if necessary, but want to avoid: Write a .apply function Any form of brute force iteration Convert the dropList to a df and merge #df_out = code here to drop if letter/color combo appears in my droplist print df_out Letter Color Value 0 A Red 20 1 B Blue 5 2 C Orange 25 I imagine there is some simple one/two line solution that I just can't see...Thanks!
tagged with: pandas

http://stackoverflow.com/comment/83987462
type: QuestionComment
comment on: http://stackoverflow.com/q/48497230
has text: `print(next(test))`
type: Comment
score: 0

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/48537856
type: Tag
tags question: http://stackoverflow.com/q/48593640

http://stackoverflow.com/a/48641912
upvote count: 69
has comment: http://stackoverflow.com/comment/84281211
has comment: http://stackoverflow.com/comment/84281073
downvote count: 0
has comment: http://stackoverflow.com/comment/84280696
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48641632
has comment: http://stackoverflow.com/comment/84281159
has comment: http://stackoverflow.com/comment/84281253
answers question: http://stackoverflow.com/q/48641632
has comment: http://stackoverflow.com/comment/84281706
has body: import pandas as pd input_file = "C:\\....\\consumer_complaints.csv" dataset = pd.read_csv(input_file) df = pd.DataFrame(dataset) cols = [1,2,3,4] df = df[df.columns[cols]] Here specify your column numbers which you want to select. In dataframe, column start from index = 0 cols = [] You can select column by name wise also. Just use following line df = df"Column Name","Column Name2"
score: 69
has comment: http://stackoverflow.com/comment/84281122
type: Answer

http://stackoverflow.com/comment/84269679
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48555290
has text: can you check whether `R` is successful in communicating with python by `reticulate::py_module_available("tensorflow")` ? If it returns `FALSE` then may be you need to configure python and tensorflow paths in R. Also, look into `reticulate::py_config()` output
type: Comment

scikit-image
tags question: http://stackoverflow.com/q/48491712
tags question: http://stackoverflow.com/q/48520006
tags question: http://stackoverflow.com/q/48491217
tags question: http://stackoverflow.com/q/48620073
tags question: http://stackoverflow.com/q/48547230
type: Tag
tag name: scikit-image
tags question: http://stackoverflow.com/q/48567671
tags question: http://stackoverflow.com/q/48617874
tags question: http://stackoverflow.com/q/48604845

http://stackoverflow.com/comment/84102136
has text: Please provide [mcve] for the specific question you're asking, as opposed to your current code.
comment on: http://stackoverflow.com/q/48551702
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48556205
tagged with: inheritance
favorite count: 0
has title: Derived class with differing interface
has answer: http://stackoverflow.com/a/48556290
type: AnsweredQuestion
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84108455
accepted answer: http://stackoverflow.com/a/48556290
has comment: http://stackoverflow.com/comment/84108515
possible better answer: http://stackoverflow.com/a/48557044
type: Question
has comment: http://stackoverflow.com/comment/84108434
has answer: http://stackoverflow.com/a/48557044
answer count: 2
has body: The following code: class Cache: def __init__(self): self._cache = [] def store(self, data): self._cache.append(data) def stats(self): print('We are caching {} elements'.format(len(self._cache))) class LegoCache(Cache): def store(self, weight, color): Cache.store(self, (weight, color)) has a problem in that the store method does not implement the interface of the base class. How can this code be improved? I have the following ideas: do not derive from Cache, just make use of it. rename the store method in the base class to store_base Are there other alternatives? EDIT The base class must also support this other use case: class ZombieCache(Cache): def store(self, dead_since, humans_eaten, can_be_saved=False): Cache.store(self, dict( dead_since=dead_since, humans_eaten=humans_eaten, can_be_saved=can_be_saved))
downvote count: 0
has comment: http://stackoverflow.com/comment/84108571
has comment: http://stackoverflow.com/comment/84108552
tagged with: adapter
upvote count: 1

http://stackoverflow.com/q/48515039
type: AnsweredQuestion
upvote count: 3
tagged with: list
has answer: http://stackoverflow.com/a/48515383
downvote count: 1
possible better answer: http://stackoverflow.com/a/48515431
linked to: http://stackoverflow.com/q/10394358
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84024526
accepted answer: http://stackoverflow.com/a/48515324
linked to: http://stackoverflow.com/q/8371887
tagged with: nested-lists
has answer: http://stackoverflow.com/a/55082607
answer count: 5
has body: Let say I have a nested list of string lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]] I want to generate all possible combination from the nested list to something like this: new_lst = [['a', 'b', 'd'], ['a', 'b', 'e', 'f'], ['a', 'c', 'd'], ['a', 'c', 'e', 'f']] I have found some question that may related to my question. how to produce a nested list from two lists in python However, my question is more complicated issue.
has answer: http://stackoverflow.com/a/48515431
tagged with: python
has comment: http://stackoverflow.com/comment/84025573
has answer: http://stackoverflow.com/a/55082806
has comment: http://stackoverflow.com/comment/84024584
has title: How to apply itertools.product to a nested list in Python
has comment: http://stackoverflow.com/comment/84024469
score: 2
has answer: http://stackoverflow.com/a/48515324

http://stackoverflow.com/a/48553481
score: 0
has comment: http://stackoverflow.com/comment/84132940
type: Answer
answers question: http://stackoverflow.com/q/48553336
has body: Yes, 3 cameras should be sufficient to locate an object in 3D space. If we know the (X,Y,Z) coordinates of each camera and the angle to the object from each camera, we can construct 3 lines each going thru a camera and towards the object. All 3 will only cross in one place - which is at the object.

http://stackoverflow.com/q/48582496
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48583301
has body: I want to execute python script in PHP but it does not work, the python script is not running. But when I directly execute the python script using cmd, the script work. Below is my PHP code. &lt;?php exec('python C:\wamp64\www\dashbot\mergeCSV.py',$output,$return); if(!$return) { echo "success!"; } else { echo "failed!"; } ?&gt;
favorite count: 0
has comment: http://stackoverflow.com/comment/84161623
type: Question
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: php
has title: php to execute python script failed
has comment: http://stackoverflow.com/comment/84161602
has comment: http://stackoverflow.com/comment/84161509
has comment: http://stackoverflow.com/comment/84161548
has comment: http://stackoverflow.com/comment/84161403
downvote count: 2

http://stackoverflow.com/comment/84283072
type: Comment
type: AnswerComment
has text: I am using the command line to start the application and using a config file to set the parameters. Therefore debugging as you suggested is not straight forward. Also, str() command doesn't work. It seems like a problem of how to read the config.ini file which I still haven't found.
comment on: http://stackoverflow.com/a/48642361
score: 0

http://stackoverflow.com/a/48582361
type: AcceptedAnswer
downvote count: 1
has body: Other answers already adressed why this fails, here is a convenient solution that sets a default for if the key is not already present, such that your appending does not fail. The way I read it, you want a dictionary with lists of other dictionaries as values. Imagining a situation such as somedict = {} somevar = 0 somevar_name = str(somevar) key1 = "oh" value1 = 1 You can do somedict.setdefault(somevar_name,[]).append({key1,value1}) This will evaluate to {'0': [{'oh', 1}]} In other words, change lines of this sort somedict[some_variables_name] += [{ 'somekey': somevalue }] Into: somedict.setdefault(some_variables_name,[]).append({'somekey':somevalue}) I hope this answers your question.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/84228720
score: 4
accepted answer of: http://stackoverflow.com/q/48581767
answers question: http://stackoverflow.com/q/48581767

http://stackoverflow.com/a/51104463
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48503499
type: Answer
answers question: http://stackoverflow.com/q/48503499
has body: UPDATE Just in case anyone in the future has the same issue as I did, below is my updated code that works. from flask import Flask, render_template, request import subprocess import tests from threading import Thread app = Flask(__name__) def async_slow_function(test, argue): if argue != None: thr = Thread(target=test, args=[argue]) else: thr = Thread(target=test) thr.start() return thr @app.route('/strobe') def strobe(): async_slow_function(tests.strobe, None) return render_template('testing.html') @app.route('/fade') def fade(): async_slow_function(tests.fade, None) return render_template('testing.html') if __name__ == '__main__': app.run(threaded=True, host='0.0.0.0') It had something to do with me returning the index() function. Instead I just rendered my testing template.
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/48537606
has answer: http://stackoverflow.com/a/48537762
possible better answer: http://stackoverflow.com/a/65762761
has answer: http://stackoverflow.com/a/48538007
has comment: http://stackoverflow.com/comment/116272287
has answer: http://stackoverflow.com/a/65762761
tagged with: python
score: -3
answer count: 4
downvote count: 6
type: AnsweredQuestion
tagged with: tkinter
upvote count: 3
has title: _tkinter.TclError: bad listbox index "": must be active, anchor, end, @x,y, or a number
has body: from tkinter import * window_main = Tk() def window_open(): def chgColor(event): lst["bg"] = lst.get(lst.curselection()) window_public = Tk() window_public.title("New Page") lbl = Label(window_public, text = "Today is a good day and I'm a gooie!") lbl.grid(padx = 20, pady = 10) var = StringVar() lst = Listbox(window_public, height = 5, width = 10, listvariable = var) lst.grid(padx = 50, pady = 20) list = ["red", "blue", "yellow", "pink", "green", "white", "black"] var.set(tuple(list)) lst.bind("&lt;&lt;ListboxSelect&gt;&gt;", chgColor) window_public.mainloop() window_main.title("Main") window_main_btn = Button(window_main, text = "To New Page", command = window_open) window_main_btn.grid(padx = 50, pady = 20) window_main.mainloop() Error: Traceback (most recent call last): File "C:\ComputerSoftware\python3.6\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:/Users/Shawn/PycharmProjects/gammaC@meL/gamma1.py", line 7, in chgColor lst["bg"] = lst.get(lst.curselection()) File "C:\ComputerSoftware\python3.6\lib\tkinter\__init__.py", line 2792, in get return self.tk.call(self._w, 'get', first) _tkinter.TclError: bad listbox index "": must be active, anchor, end, @x,y, or a number I'm a beginner in python and got stuck with a problem. When I click on the button I go to a new page. Then when I click on listbox I get a traceback. I can't understand the traceback's meaning and can't fix it. But I found out that when I delete codes about window_main, it runs.
has comment: http://stackoverflow.com/comment/84102924
has answer: http://stackoverflow.com/a/74044923
accepted answer: http://stackoverflow.com/a/48537762
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/48557273
type: AnsweredQuestion
score: 0
has body: I am beginning to learn python. My background in programming languages is with MatLab and Mathematica; I'm a math person with zero knowledge in computer science. However, my currently most difficult hurdle is trying to figure the "big picture" as to the interface of jupyter notebook. I have an anaconda navigator installed which includes packages like Rstudio, jupyterlab and glueviz. I run either one of these packages via the anaconda navigator. In attempting some tutorials, I am asked to run a csv file via import pandas as pd. Upon googling, panda appears to be a package. 1) I am unsure if it has already been installed. How do I check if it has been installed. 2) If it hasn't been installed, how do I install it? I have tried pasting the command line conda install -c conda-forge pandas on the mac terminal but nothing happens. Help would be appreciated. Feel free to explain as though I'm an idiot.
has comment: http://stackoverflow.com/comment/84110547
answer count: 1
accepted answer: http://stackoverflow.com/a/48557540
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/48557540
has comment: http://stackoverflow.com/comment/84112092
tagged with: python
has comment: http://stackoverflow.com/comment/84110417
tagged with: jupyter-notebook
tagged with: python-3.x
has title: understanding jupyter notebook interface
has comment: http://stackoverflow.com/comment/84110527

http://stackoverflow.com/comment/84298861
type: AnswerComment
has text: Just for sport, is there a way to perform the same task with transform, np.where or iterrows...?
type: Comment
comment on: http://stackoverflow.com/a/48550836
score: 0

http://stackoverflow.com/comment/84221227
comment on: http://stackoverflow.com/a/48611718
has text: @revo I think I got it. Does the engine evaluate the negative (`!`) only after exiting the atomic part, instead of before? That is `not(match())` instead of `match(not())`?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48603448
has title: Not full Import multiple csv files into pandas and concatenate into one DataFrame
has comment: http://stackoverflow.com/comment/84204341
answer count: 2
tagged with: concatenation
has answer: http://stackoverflow.com/a/75002899
has body: Please help me to find solution for the problem with importing data from multiple csv files to one DataFrame in python. Code is: import pandas as pd import os import glob path = r'my_full_path' os.chdir(path) results = pd.DataFrame() for counter, current_file in enumerate(glob.glob("*.csv")): namedf = pd.read_csv(current_file, header=None, sep=",", delim_whitespace=True) results = pd.concat([results, namedf], join='outer') results.to_csv('Result.csv', index=None, header=None, sep=",") The problem is that some part of data are moving to the rows instead of new columns as required. What is wrong in my code? P.S.: I found questions about importing multiple csv-files to DataFrame, for example here: Import multiple csv files into pandas and concatenate into one DataFrame, but solution doesn't solve my issue:-(
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84205368
has answer: http://stackoverflow.com/a/48622457
score: 0
tagged with: glob
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/20906474
tagged with: python
type: Question

http://stackoverflow.com/q/48589725
has title: Extracting text inbetween HTML tags
type: UnansweredQuestion
tagged with: python
score: -1
has body: I have this string: In December 2011, Norway's largest online sex shop hemmelig.com was hacked by a collective calling themselves "Team Appunity". The attack exposed over 28,000 usernames and email addresses along with nicknames, gender, year of birth and unsalted MD5 password hashes. (don't ask) Inside of that string sits an HREF link to the site itself, what I need to do is extract the information between the tags . So the end result should look like this: In December 2011, Norway's largest online sex shop hemmelig.com was hacked by a collective calling themselves "Team Appunity". The attack exposed over 28,000 usernames and email addresses along with nicknames, gender, year of birth and unsalted MD5 password hashes. What I've been able to do so far is match the whole tag using a regular expression and replacing it with nothing: def get_unlinked_description(descrip): html_tag_regex = re.compile(r"<.+>", re.I) return html_tag_regex.sub("", descrip) However the output of this, as you would expect, removes the whole string: In December 2011, Norway's largest online sex shop hemmelig.com was . The attack exposed over 28,000 usernames and email addresses along with nicknames, gender, year of birth and unsalted MD5 password hashes How can I successfully extract the information between the tags, along with removing the tags, without removing the full string? .
tagged with: python-2.7
upvote count: 0
linked to: http://stackoverflow.com/q/13268365
answer count: 1
has answer: http://stackoverflow.com/a/48589907
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/13268365

http://stackoverflow.com/q/48554234
has comment: http://stackoverflow.com/comment/84104858
favorite count: 0
has comment: http://stackoverflow.com/comment/84104845
type: Question
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -3
has body: I am trying to make a calculator with python. I will like to print x square correctly, but mine still print this: x2. How can I print it with 2 on top of x with python if possible. Thank you!
has answer: http://stackoverflow.com/a/48554947
has comment: http://stackoverflow.com/comment/84105516
answer count: 1
downvote count: 3
has title: I am trying to print x square with python, I do not want 'x2'

http://stackoverflow.com/q/48593640
tagged with: pyqt
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: python pyqt QPainter widgets don't show up in layout
favorite count: 0
accepted answer: http://stackoverflow.com/a/48593770
type: Question
has answer: http://stackoverflow.com/a/48593770
tagged with: pyqt4
tagged with: python
tagged with: qpainter
has body: I am new to python3 pyqt GUI development. I am trying to make a simple GUI which has various widgets spaced nicely in a compound layout structure of a QVBoxLayout which contains many QHBoxLayouts. When building the layouts, I use the addStretch() method to space out the widgets but the circles which are painted do not show up in the GUI display. However if I comment out all of the addStretch() function calls then the GUI displays all the desired widgets (however the spacing is not good looking). Where are the circles going? Please help! Code where circle widgets do not show up. #!/usr/bin/python3 import sys from PyQt4 import QtCore, QtGui class DrawCircle(QtGui.QWidget): def __init__(self, color, parent=None): QtGui.QWidget.__init__(self, parent) self.color = color def setColor(self,color): self.color = color def paintEvent(self,event): self.paint = QtGui.QPainter() self.paint.begin(self) self.paint.setRenderHint(QtGui.QPainter.Antialiasing) radx = 30 rady = radx if self.color == 'red': self.paint.setPen(QtCore.Qt.red) self.paint.setBrush(QtCore.Qt.red) elif self.color == 'green': self.paint.setPen(QtCore.Qt.green) self.paint.setBrush(QtCore.Qt.green) k = int(radx * 1.5) center = QtCore.QPoint(k,k) self.paint.drawEllipse(center,radx,rady) self.paint.end() class Window(QtGui.QMainWindow, QtGui.QGraphicsView): def __init__(self): super(Window,self).__init__() # GUI Setup self.myWid = QtGui.QWidget() # Establish a Vertical Box Layout # The layout will be a vertical box layout comprised of horizontal # box layouts self.vbox_fullDisplay = QtGui.QVBoxLayout() # Add a Zero-width spacer-item before the area where the # text label will appear self.vbox_fullDisplay.addStretch(1) ############################### # Build horizontal box layout # ############################### self.hbox_top = QtGui.QHBoxLayout() # The text should be centered on the screen so zero-width # spacer items will be added to the left and right of the label self.hbox_top.addStretch(1) self.top_text_label …
type: AnsweredQuestion
tagged with: qwidget

url
tags question: http://stackoverflow.com/q/48548414
tags question: http://stackoverflow.com/q/48533397
tags question: http://stackoverflow.com/q/48554190
tags question: http://stackoverflow.com/q/48631408
tag name: url
tags question: http://stackoverflow.com/q/48597577
tags question: http://stackoverflow.com/q/48527429
tags question: http://stackoverflow.com/q/48587537
tags question: http://stackoverflow.com/q/48577186
tags question: http://stackoverflow.com/q/48492265
type: Tag
tags question: http://stackoverflow.com/q/48591575

http://stackoverflow.com/comment/84316981
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48644779
type: Comment
has text: @NathanVērzemnieks, I will update my answer. My test was for small strings, as per OP.

http://stackoverflow.com/q/48523344
has comment: http://stackoverflow.com/comment/84063760
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84077800
has comment: http://stackoverflow.com/comment/84063891
score: 1
has comment: http://stackoverflow.com/comment/84270395
answer count: 1
downvote count: 1
has title: Get Parent of Gtk Submenu
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84054907
has comment: http://stackoverflow.com/comment/123499082
has comment: http://stackoverflow.com/comment/84053525
has body: Calling get_parent() on a Gtk submenu (item) does not yield its parent menu but rather the object it extends from. Is it possible to identify the parent menu? I need it for a much more complex menu structure than the one below MCVE, in order to toggle the RadioMenuItem checkboxes of the above-lying menuitems. menu = Gtk.Menu() menu_item = Gtk.MenuItem('blah', 'blah') menu_item.set_submenu(create_submenu()) menu.append(menu_item) def create_submenu(): submenu = Gtk.Menu() submenu_item = Gtk.MenuItem('blah', 'blah') submenu.connect('activate', do_something) submenu.append(submenu_item) return submenu def do_something(widget): widget.get_parent().set_label('this is not the parent menu') # &lt;--- refers to Gtk.Window, not our menu above
has answer: http://stackoverflow.com/a/69874880
accepted answer: http://stackoverflow.com/a/69874880
tagged with: python
has comment: http://stackoverflow.com/comment/84056161
tagged with: gtk
has comment: http://stackoverflow.com/comment/84041592
has comment: http://stackoverflow.com/comment/84055925

http://stackoverflow.com/q/48621173
tagged with: regex
has comment: http://stackoverflow.com/comment/84238883
answer count: 4
type: Question
has body: This is my Dataframe: entityId delta_approved_clockout (ID: 10) 247333605 0.0 (ID: 20) 36738870 0.0 (ID: 40) 4668036427 0.0 (ID: 50) 1918647972 0.0 (ID: 60) 4323165902 44125.0 (ID: 80) 145512255 0.0 Assigned (ID: 30) 42050340 0.0 Assigned (ID: 40) 130880371376 0.0 Assigning (ID: 30) 1095844753 0.0 Cancelled (ID: 40) 937280 0.0 Cancelled (ID: 80) 16857720813 0.0 Planned (ID: 20) 9060392597 0.0 Planning (ID: 10) 108484297031 0.0 Processed (ID: 70) 133289880880 0.0 Revoked (ID: 50) 2411903072 0.0 Writing (ID: 50) 146408550024 0.0 Written (ID: 60) 139458227923 1018230.0 I want the result to only print the exact regex match for '(ID: 10)', using this line my input includes 'Planning (ID: 10)', which is not the exact match I need. These are the summed results: entityId delta_approved_clockout last_status (ID: 10) 247333605 0.0 Planning (ID: 10) 108484297031 0.0 print input_data[input_data['last_status'].str.contains(r'(?&lt;!\S)\(ID: 10\)(?!\S)', na=False)] I have also tried regex codes that gave 0 results such as: print input_data[input_data['last_status'].str.contains(r' ^(\(ID: \d+\))$', na=False)] print input_data[input_data['last_status'].str.contains(r'^(\(ID: 10\))$', na=False)] Perhaps I don't understand regex thoroughly, what would be the correct way of writing regex? Thanks in advance.
has comment: http://stackoverflow.com/comment/84239158
has comment: http://stackoverflow.com/comment/84238786
has answer: http://stackoverflow.com/a/48621920
has answer: http://stackoverflow.com/a/48621413
downvote count: 0
possible better answer: http://stackoverflow.com/a/48621413
tagged with: pandas
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/48621587
tagged with: string
has title: Finding exact regex match for string in column
has comment: http://stackoverflow.com/comment/84239309
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84239311
has comment: http://stackoverflow.com/comment/84238783
has answer: http://stackoverflow.com/a/48621540
has comment: http://stackoverflow.com/comment/84239421
accepted answer: http://stackoverflow.com/a/48621540
tagged with: python

http://stackoverflow.com/comment/84051762
type: Comment
comment on: http://stackoverflow.com/a/48528167
score: 0
type: AnswerComment
has text: if it's harder to read, then don't use it. I was just suggesting a different approach

http://stackoverflow.com/comment/84075060
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48539751
has text: The edges are not all black, only some pixels are. *Very*, *very* few, actually. Clicking here and there I can't even find *one*. What do you want to happen with pixels on the border that are not black, dark, or even medium – but still 'darker than a random adjecent pixel'?
score: 1

http://stackoverflow.com/comment/84288399
comment on: http://stackoverflow.com/a/48645428
type: AnswerComment
score: 0
type: Comment
has text: that is left side from word that is the reference, just change word+"O" to "O"+word

http://stackoverflow.com/q/48518434
has answer: http://stackoverflow.com/a/48519054
downvote count: 0
tagged with: neural-network
tagged with: keras
favorite count: 0
has title: Keras - Negative dimension size caused by subtracting 5 from 4 for 'conv2d_5/convolution' (op: 'Conv2D') with input shapes: [?,4,80,64], [5,5,64,64]
type: Question
has answer: http://stackoverflow.com/a/48518999
tagged with: python
has body: I have a similar model to the one below, but after modifying the architecture, I keep getting the following error: Negative dimension size caused by subtracting 5 from 4 for 'conv2d_5/convolution' (op: 'Conv2D') with input shapes: [?,4,80,64], [5,5,64,64]. I am still new to machine learning so I couldn't make much sense of the parameters. Any help? model_img = Sequential(name="img") # Cropping model_img.add(Cropping2D(cropping=((124,126),(0,0)), input_shape=(376,1344,3))) # Normalization model_img.add(Lambda(lambda x: (2*x / 255.0) - 1.0)) model_img.add(Conv2D(16, (7, 7), activation="relu", strides=(2, 2))) model_img.add(Conv2D(32, (7, 7), activation="relu", strides=(2, 2))) model_img.add(Conv2D(32, (5, 5), activation="relu", strides=(2, 2))) model_img.add(Conv2D(64, (5, 5), activation="relu", strides=(2, 2))) model_img.add(Conv2D(64, (5, 5), activation="relu", strides=(2, 2))) model_img.add(Conv2D(128, (3, 3), activation="relu")) model_img.add(Conv2D(128, (3, 3), activation="relu")) model_img.add(Flatten()) model_img.add(Dense(100)) model_img.add(Dense(50)) model_img.add(Dense(10)) model_lidar = Sequential(name="lidar") model_lidar.add(Dense(32, input_shape=(360,))) model_lidar.add(Dropout(0.1)) model_lidar.add(Dense(10)) model_imu = Sequential(name='imu') model_imu.add(Dense(32, input_shape=(10, ))) model_imu.add(Dropout(0.1)) model_imu.add(Dense(10)) merged = Merge([model_img, model_lidar, model_imu], mode="concat") model = Sequential() model.add(merged) model.add(Dense(16)) model.add(Dropout(0.2)) model.add(Dense(1)) Answer: I couldn't complete the training because of issues with sensor but the model works fine now thanks to the 2 answers below
score: 2
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/48518999
accepted answer: http://stackoverflow.com/a/48519054
upvote count: 2

http://stackoverflow.com/comment/84106426
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48508101
has text: Thanks. Yes indeed I followed all of it.I think you might be right because I've playing around with this for the past two days and it may be the case that there is no point in using dropout for this dataset. Is there a rule or rule of thumb to decide when dropout may not be necessary? Like a parameter or a certain difference to watch for?
score: 0

http://stackoverflow.com/a/48494715
type: Answer
accepted answer of: http://stackoverflow.com/q/48492341
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48492341
has body: A print statement shown to a task is meaningless. You'll never see it. Only the task sees it. Let the task talk to you via the logs. See if this makes better sense: from flask import Response from google.appengine.api import taskqueue import logging @app.route('/task', methods=["GET", "POST"]) def testtask(): logging.info("sending task to queue in testtask...") taskqueue.add( url = "/execute_task", name = "task_name_here", method = "POST", params = { "sender": "me" } ) return Response("sending task to queue... Check logs", mimetype='text/plain', status=200) @app.route('/execute_task', methods=["GET", "POST"]) def execute_task(): logging.info("I did the task") logging.info("params: {}".format(request.form)) return Response("did it. You'll never see this message", mimetype='text/plain', status=200)
score: 2

http://stackoverflow.com/comment/84086694
score: 0
comment on: http://stackoverflow.com/q/48545494
type: QuestionComment
has text: BTW your attempt makes no sense in many aspects.
type: Comment

http://stackoverflow.com/a/48597546
answers question: http://stackoverflow.com/q/48596294
type: Answer
score: 0
type: AcceptedAnswer
has body: Your consumer loop while not q.empty(): can sometimes end if the consumer manages to temporarily empty the queue even though the creator is still running and puts more items on the queue afterwards. Therefore you should find a different way to end the loop, such as counting the number of items consumed and ending when it reaches 1000.
accepted answer of: http://stackoverflow.com/q/48596294
has comment: http://stackoverflow.com/comment/84192591

two-factor-authentication
tags question: http://stackoverflow.com/q/48600737
tag name: two-factor-authentication
type: Tag

http://stackoverflow.com/comment/84144180
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48573560
type: Comment
has text: `set()` creates, well, [a set](https://www.programiz.com/python-programming/set). You can try `a = set('=<5') ; print(a) ; print(bool(a))` to see, what your code did.

http://stackoverflow.com/comment/84021795
comment on: http://stackoverflow.com/q/48513445
type: Comment
type: QuestionComment
score: 0
has text: it is blank, missing value according to df.describe()

http://stackoverflow.com/q/48590488
has comment: http://stackoverflow.com/comment/84178526
has answer: http://stackoverflow.com/a/48591193
possible better answer: http://stackoverflow.com/a/48591193
has comment: http://stackoverflow.com/comment/84178436
tagged with: pandas
has comment: http://stackoverflow.com/comment/84178594
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/48590824
tagged with: dictionary
has answer: http://stackoverflow.com/a/48590628
tagged with: apply
accepted answer: http://stackoverflow.com/a/48590628
answer count: 4
upvote count: 8
favorite count: 0
score: 8
type: Question
linked to: http://stackoverflow.com/q/48510405
has body: Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x. df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ipad2', 'acer chromebook', 'acer chromebookx', 'mac air', 'mac pro', 'lenovo x4'], 'price':range(10)}) For Example I would like to take the above df and create a new column df['company'] and set it to a mapping of strings. I was thinking of doing something like product_map = {'dell':'Dell Inc.', 'apple':'Apple Inc.', 'acer': 'Acer Inc.', 'mac': 'Apple Inc.', 'lenovo': 'Dell Inc.'} Then I wanted to iterate through it to check the df.comp column and see if each entry contained one of those strings, and to set the df.company column to the value in the dictionary. Not sure how to do this correctly though.
has title: map str.contains across pandas DataFrame
has answer: http://stackoverflow.com/a/59037499
downvote count: 0
has comment: http://stackoverflow.com/comment/84178485
has comment: http://stackoverflow.com/comment/84178373
has comment: http://stackoverflow.com/comment/84178504
type: AnsweredQuestion

http://stackoverflow.com/q/48510545
tagged with: python
has comment: http://stackoverflow.com/comment/84016045
has comment: http://stackoverflow.com/comment/84016470
tagged with: tabpy
tagged with: python-3.x
score: 0
has body: I am working on a project in Tableau- ver 10.4.2. My data is in a SQL Cube - and the columns I am working with are formatted as: MemberID - this is a string field with a member ID AdmissionDate - This is a DateTime field with format mmddYYYY DischargeDate - This is a DateTime field with format mmddYYYY What I am trying to accomplish is this - I need to find instances where the patient was discharged, and then re-admitted within the ensuing 30 days. So, I need the difference of the Discharge date and the NEXT admission date, per patient (memberID). There are multiple admit &amp; discharge dates for each MemberID (patient). I thought an easy solution would be to shift the column for admission dates up by 1, using pandas... (I am running a TabPy server instance on my computer and it is functioning properly) - for each memberID - but keep running into errors like this - "TypeError : Object of type Series is not JSON serializable" My script is SCRIPT_REAL(" import pandas as pd df = pd.DataFrame({'MemberID': _arg1,'AdmitDate': _arg2}) df['AdmitDate'] = pd.to_datetime(df['AdmitDate']) MemberID = df.MemberID for i in MemberID: newadmitdate = df.AdmitDate.shift(-1) return newadmitdate ", ATTR([GR2MCL Member ID]),attr([AdmitDateCalc]) ) To troubleshoot, I created a csv file formatted similarly - and can see that my script is shifting the column properly. The only issue I can see is that it is not looping properly on each MemberID, but I am not getting errors like I am getting in Tableau. Any thoughts on this would be appreciated!
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84016437
has comment: http://stackoverflow.com/comment/84016562
tagged with: tableau-api
type: Question
has comment: http://stackoverflow.com/comment/84016528
has title: Tableau with Python Script - Pandas SHIFT function issue

http://stackoverflow.com/q/48508900
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48508967
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48508982
possible better answer: http://stackoverflow.com/a/48508982
favorite count: 0
has answer: http://stackoverflow.com/a/48509008
type: Question
has title: Pandas - Update columns if condition is met
has answer: http://stackoverflow.com/a/48508970
has answer: http://stackoverflow.com/a/48508967
answer count: 5
has body: I have three columns that I'm trying to update the values in. The logic is: If a particular row in the column is blank, I want to change it to say n instead of None. If it has a value in it, then I want to change that value to say y. An example is below: Current data: barcode dash_1 dash_2 dash_3 ABC123 ABC123 ABC123 None ABC124 ABC124 ABC124 ABC124 ABC125 None ABC125 ABC125 ABC126 ABC126 None None Desired output: barcode dash_1 dash_2 dash_3 ABC123 y y n ABC124 y y y ABC125 n y y ABC126 n n n I've been trying to do something similar to the code below, but I get the message str object has no attribute isnull. Any ideas what I'm doing wrong? Thanks! for idx, row in barcodes2.iterrows(): for col in ['dash_1','dash_2','dash_3']: if row[col].isnull(): row[col] == 'n' else: row[col] == 'y'
has answer: http://stackoverflow.com/a/48508968
tagged with: python

http://stackoverflow.com/comment/84144874
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48574003
has text: Thanks for your nice comment, it was very helpful. I'm a beginner with python. I also tried just using months and that doesn't work either.

http://stackoverflow.com/comment/136802791
comment on: http://stackoverflow.com/q/48560138
type: Comment
score: 0
has text: I'm from the future using JupyterLab 4 and it seems plotly isn't compatible with that version according to: https://community.plotly.com/t/does-plotly-work-with-jupyterlab-4/76095
type: QuestionComment

http://stackoverflow.com/comment/84205519
has text: For starters, please format your code and reduce it to the _minimal_ example.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48604403

http://stackoverflow.com/comment/83987267
has text: None is `null` or `nil` for python. So it's empty passed parameter.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48497133
score: 0

http://stackoverflow.com/comment/84019733
has text: It's better if you can elaborate on the expected behavior. Is it you mean the `loop.run_until_complete(close_connection(session))` is not executed concurrently along with `loop.run_until_complete(post(session, 'http://localhost:8000'))`?
comment on: http://stackoverflow.com/q/48512045
score: 0
type: Comment
type: QuestionComment

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/48641406
type: Tag
tags question: http://stackoverflow.com/q/48593427

http://stackoverflow.com/a/48630254
accepted answer of: http://stackoverflow.com/q/48630022
answers question: http://stackoverflow.com/q/48630022
upvote count: 5
has comment: http://stackoverflow.com/comment/84268920
type: Answer
has body: The first one calculates a random 1000×3 matrix, all values are between 0 and 1, so the rows represent points in a 3D unit cube: np.random.random((1000, 3)) Next we use reshape, to construct an 1000×1×3 matrix, with X.reshape(1000, 1, 3). Now when we subtract that reshaped matrix something happens that is very popular in numpy: broadcasting. So we have a 1000×1×3 matrix, and a 1000×1×3 matrix. That means that we will "blow up" the first matrix by hypothetically repeating the second dimension 1000 times. So a matrix like: [x1, y1, z1, x2, y2, z2, ... xn, yn, zn] Will now be transformed into: [[[x1, y1, z1], [x1, y1, z1], ..., [x1, y1, z1]], [[x2, y2, z2], [x2, y2, z2], ..., [x2, y2, z2]], ... , ... , ... , [[xn, yn, zn], [xn, yn, zn], ..., [xn, yn, zn]]] Where each triple is repeated n times per row. We blow up the second matrix as well, such that: [[x1, y1, z1], [x2, y2, z2], ... [xn, yn, zn]] (mind that we have one pair of square brackets less per row), will blow up to: [[x1, y1, z1], [x2, y2, z2], ..., [xn, yn, zn], [x1, y1, z1], [x2, y2, z2], ..., [xn, yn, zn], ... , ..., ..., ... , [x1, y1, z1], [x2, y2, z2], ..., [xn, yn, zn]] If we now subtract the two matrices, we get: [[[x1-x1, y1-y1, z1-z1], [x1-x2, y1-y2, z1-z2], ..., [x1-xn, y1-yn, z1-zn]], [[x2-x1, y2-y1, z2-z1], [x2-x2, y2-y2, z2-z2], ..., [x2-xn, y2-yn, z2-zn]], ... , ... , ... , [[xn-x1, yn-y1, zn-z1], [xn-x2, yn-y2, zn-z2], ..., [xn-xn, yn-yn, zn-zn]]] So we constructed a 1000×1000×3 matrix, where the i,j-th element is a 3-tuple containing the difference of the coordinates of the point specified at row i and the coordinate of the point specified at row j. We store that result in diff. Next we use diff**2 to caculate the elementwise square, so now: (diff**2)[i, j] == array([(xi-xj)**2, (yi-yj)**2, (zi-zj)**2]) Finally we call .sum(2) on that matrix (this means axis=2). This means that we for each element of (diff**2) will sum up the components, so then: ((diff**2).sum())[i, j] == (xi-xj)**…
type: AcceptedAnswer
score: 5
downvote count: 0

http://stackoverflow.com/q/48511794
type: Question
has body: I am trying to write a decorator that takes an arbitrary number of functions as positional arguments and then composes these functions with the function that is being decorated. Conceptually, I am trying to do this: @format(f1, f2, f3) def f0(param): return value f0(arg) should evaluate to f3(f2(f1(f0(arg)))) Here is a simple example I have been working on to illustrate the concept. def lc(s): s = s.lower() return s def punc(s): if s[-1] != ".": s = s + "." return s else: return s def cap(s): s = s[0].upper() + s[1:] return s def format(*args): def wrapper(func, *a): for f in args: func = f(func) return func return wrapper @format(lc, punc, cap) def example_func(param): return param What I'm expecting is this: f0("MY TEST STRING") My test string. I'm getting the following error message: AttributeError: 'function' object has no attribute 'lower' There may be an easier way to do this, such as pass the functions directly into the original and not use a decorator, but I am looking for a solution that specifically uses a decorator in this way. Thank you.
tagged with: function-composition
score: 1
has answer: http://stackoverflow.com/a/48511903
tagged with: python
type: AnsweredQuestion
has title: Python decorator that takes arbitrary number of functions as arguments and returns composition of functions
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/30195045
accepted answer: http://stackoverflow.com/a/48511903
answer count: 1
has comment: http://stackoverflow.com/comment/84018550
tagged with: decorator
favorite count: 0

http://stackoverflow.com/a/48688304
accepted answer of: http://stackoverflow.com/q/48642605
type: Answer
has comment: http://stackoverflow.com/comment/84452854
score: 0
has body: The python dependencies need to be available on all nodes where Spark/Sparkling Water is running - that means on both executors and driver. This is because the operations are executed in parallel and require the same dependencies as on driver. What I would suggest is to run your Spark application in the uniform environment - ie, have same environment, dependencies for all spark executors and driver to prevent bunch of issues
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84374831
answers question: http://stackoverflow.com/q/48642605

http://stackoverflow.com/q/48514724
score: 0
answer count: 0
has title: Python Client error: [Errno 111] Connection refused
tagged with: arduino
tagged with: django
has body: I don't really know the problem but I got an error: "connection refused". I don't know what to do please help me. I'm trying to send a count when the button is pressed on android app and I'm using nanpy to connect to arduino but I got an error. import socket from nanpy import (ArduinoApi, SerialManager) ledpin = 13 buttonpin = 12 buttonpin1 = 2 buttonpin2 = 3 buttonstate1 = 1 buttonstate2 = 1 buttonstate3 = 1 connection = SerialManager() a = ArduinoApi(connection = connection) a.pinMode(ledpin, a.OUTPUT) a.pinMode(buttonpin, a.INPUT) a.pinMode(buttonpin1, a.INPUT) a.pinMode(buttonpin2, a.INPUT) ADDR2 = ('192.168.1.7', 21568) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(ADDR2) while True: try: buttonstate1 = a.digitalRead(buttonpin) buttonstate2 = a.digitalRead(buttonpin1) buttonstate3 = a.digitalRead(buttonpin2) if buttonstate1: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) if buttonstate2: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) if buttonstate3: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) finally: sock.close this is the error some know how to fix this? Traceback (most recent call last): File "/home/pi/Desktop/counter.py", line 24, in &lt;module&gt; sock.connect(ADDR2) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) error: [Errno 111] Connection refused
type: Question
has comment: http://stackoverflow.com/comment/84033700
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/84032300
has comment: http://stackoverflow.com/comment/84024079

http://stackoverflow.com/a/48640714
upvote count: 5
answers question: http://stackoverflow.com/q/48640403
type: Answer
has comment: http://stackoverflow.com/comment/84284129
type: AcceptedAnswer
downvote count: 0
has body: Using zip_longest in one line: from itertools import zip_longest major, minor, patch, revision, appendix = [x + y for x, y in zip_longest( version_str.split(','), [''] * 5, fillvalue='')] or: split = version_str.split(',') major, minor, patch, revision, appendix = split + [''] * (5 - len(split))
accepted answer of: http://stackoverflow.com/q/48640403
score: 5

http://stackoverflow.com/comment/83981605
type: AnswerComment
has text: @SethMMorton Yeah your right, keeping them as strings to begin with work just as fine. I'll update it, cheers.
type: Comment
comment on: http://stackoverflow.com/a/48494051
score: 0

http://stackoverflow.com/q/48557055
tagged with: python-2.7
downvote count: 4
has title: map() in python 2.7
answer count: 1
has comment: http://stackoverflow.com/comment/84109925
upvote count: 1
has answer: http://stackoverflow.com/a/48557109
favorite count: 0
type: Question
has body: Reduce() is working fine but when I use the same Lambda() with Map() it's showing TypeError. I'm not able to resolve the error. l = [2,4,6,8,10] reduce(lambda x,y: x+y,l) output: 30 l = [2,4,6,8,10] map(lambda x,y: x+y,l) output: TypeError Traceback (most recent call last) in () ----> 1 map(lambda x,y: x+y,l) TypeError: () takes exactly 2 arguments (1 given)
has comment: http://stackoverflow.com/comment/84110022
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/84109948
tagged with: python
tagged with: lambda

http://stackoverflow.com/comment/84274214
comment on: http://stackoverflow.com/q/48638633
score: 0
type: Comment
type: QuestionComment
has text: I am sorry but I know this article. It does not contain the answer to my question.

http://stackoverflow.com/comment/83980652
comment on: http://stackoverflow.com/q/48493447
type: QuestionComment
type: Comment
has text: One '?' is enough. Try adding explanations / clarifications rather than extra ?'s.
score: 0

http://stackoverflow.com/a/48613168
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48613006
score: 7
upvote count: 7
type: AcceptedAnswer
has body: Because the client side represented by your python code does not yet know that the server's socket is closed and gone. Think of the TCP connection as two separate channels: one in each direction. The TCP protocol allows each side to close its sending side of the connection at a time of its own choosing. And TCP has no way of indicating to the other side that future sends in the other direction will not be accepted. In more detail... Ordinary termination of a TCP session involves each side sending a packet with the FIN flag set. That indicates that the peer sending the FIN will not send any more data. It does not indicate that the receiver of the FIN packet may not send any more data. So, what happens here is that when you kill netcat, a FIN packet is sent from the server side to the client (and acknowledged by the network stack on behalf of the client). That closes the server=>client direction of the socket. However, the client=>server direction is still usable as far as the client side knows. Later, when your client attempts to send data, a packet is sent containing the data. Now, the network stack on the server side immediately responds telling the client side that the server is no longer there by sending a RST packet. However, your sendall function call is long-finished by the time that is received. So, if your client were to sleep another second (or actually just a small fraction of a second) and then attempt another send, that subsequent send would raise an exception. It might be instructive to create a packet capture of the entire session and study it with wireshark. Run this in another window before invoking your python code (then kill with Ctrl-C afterward): sudo tcpdump -i lo -w /tmp/f.pcap port 8080 You can also use wireshark to capture it, specifying the same port 8080 as a capture filter -- or tcp.port == 8080 as a display filter.
has comment: http://stackoverflow.com/comment/84223107
has comment: http://stackoverflow.com/comment/84247761
type: Answer
answers question: http://stackoverflow.com/q/48613006
has comment: http://stackoverflow.com/comment/84223137

http://stackoverflow.com/q/48618462
linked to: http://stackoverflow.com/q/18624039
score: 3
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48622104
possible better answer: http://stackoverflow.com/a/48622104
tagged with: pandas
favorite count: 0
type: Question
has title: how can i move time-series data from yesterday to today in pandas?
tagged with: time-series
tagged with: python
has body: i have dataframe that is cross the day(12-02~1203) belows.. and i wanna move yesterday data(12-02 22:00~00:00) to today data(12-03) everyday. date/time is mutli-indexed. this is needed when i analyze data, it's more convenient day by day. but now i need to analyze data including yesterday last 2hours... so i need this dataframe manipulation. .. date time a b 2015-12-02 21:00:00 23.97 0 2015-12-02 21:15:00 24.06 0 2015-12-02 21:30:00 24.03 0 2015-12-02 21:45:00 23.99 0 2015-12-02 22:00:00 24.03 0 2015-12-02 22:15:00 23.89 0 2015-12-02 22:30:00 23.71 0 2015-12-02 22:45:00 23.64 0 2015-12-02 23:00:00 23.29 0 2015-12-02 23:15:00 23.8 0 2015-12-02 23:30:00 23.82 0 2015-12-02 23:45:00 23.86 0 2015-12-03 0:00:00 23.66 0 2015-12-03 0:15:00 23.64 0 2015-12-03 0:30:00 23.7 0 2015-12-03 0:45:00 23.69 0 2015-12-03 1:00:00 23.65 0 2015-12-03 1:15:00 23.48 0 2015-12-03 1:30:00 23.45 0 .. results should be like below(12-02 22:00~23:45 data is moved to 12-03 how can i do it ? .. 2015-12-02 21:00:00 23.97 0 2015-12-02 21:15:00 24.06 0 2015-12-02 21:30:00 24.03 0 2015-12-02 21:45:00 23.99 0 2015-12-03 22:00:00 24.03 0 2015-12-03 22:15:00 23.89 0 2015-12-03 22:30:00 23.71 0 2015-12-03 22:45:00 23.64 0 2015-12-03 23:00:00 23.29 0 2015-12-03 23:15:00 23.8 0 2015-12-03 23:30:00 23.82 0 2015-12-03 23:45:00 23.86 0 2015-12-03 0:00:00 23.66 0 2015-12-03 0:15:00 23.64 0 2015-12-03 0:30:00 23.7 0 2015-12-03 0:45:00 23.69 0 2015-12-03 1:00:00 23.65 0 2015-12-03 1:15:00 23.48 0 2015-12-03 1:30:00 23.45 0 ..
has answer: http://stackoverflow.com/a/48621846
has answer: http://stackoverflow.com/a/48628366
accepted answer: http://stackoverflow.com/a/48628366
tagged with: move
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/84316879
type: Comment
type: QuestionComment
score: 0
has text: thank you blackjack, sorry for the confusing question. I would like to login to a page. After that I would like the function to open the browser and the page to be visible
comment on: http://stackoverflow.com/q/48643863

http://stackoverflow.com/a/48605017
answers question: http://stackoverflow.com/q/48604896
score: 0
has body: Nothing is wrong in your script nor in your txt files, it is running fine on my system!! Please try to run again in the different file or in other systems. Or there may be some problem with your python lib files. You don't need to remove $ from your txt file like answered by @johnashu
type: Answer

http://stackoverflow.com/comment/84052290
has text: @RenanAndrade I don't see any syntax errors in your image.
type: Comment
comment on: http://stackoverflow.com/a/48528454
type: AnswerComment
score: 0

facebook
tags question: http://stackoverflow.com/q/48554536
tag name: facebook
tags question: http://stackoverflow.com/q/48573248
tags question: http://stackoverflow.com/q/48547743
type: Tag
tags question: http://stackoverflow.com/q/48508782

http://stackoverflow.com/comment/84200944
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48601771
has text: Does `sudo` work any better for you? (I don't have any linux machines to try this on myself).

http://stackoverflow.com/a/48631089
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48630146
type: Answer
has body: If the strings are duplicates, I want the first instance of the string to have an ID containing 6 characters. For the duplicates of that string, I want the ID to be the same as the original one, but with an additional two characters. Try using a collections.defaultdict. Given import ctypes import collections as ct filename = "test.txt" def read_file(fname): """Read lines from a file.""" with open(fname, "r") as f: for line in f: yield line.strip() Code dd = ct.defaultdict(list) for x in read_file(filename): key = str(ctypes.c_size_t(hash(x)).value) # make positive hashes if key[:6] not in dd: dd[key[:6]].append(x) else: dd[key[:8]].append(x) dd Output defaultdict(list, {'133259': ['123 Test'], '13325942': ['123 Test', '123 Test'], '210763': ['567 Test'], '21076377': ['567 Test'], '240895': ['321 Test']}) The resulting dictionary has keys (of length 6) for every first occurrence of a unique line. For every successive replicate line, two additional characters are sliced for the key. You can implement the keys however you wish. In this case, we used hash() to correlate the key to each unique line. We then sliced the desired sequence from the key. See also a post on making positive hash values from ctypes. To inspect your results, create the appropriate lookup dictionaries from the defaultdict. # Lookups occurrences = ct.defaultdict(int) ids = ct.defaultdict(list) for k, v in dd.items(): key = v[0] occurrences[key] += len(v) ids[key].append(k) # View data for k, v in occurrences.items(): print("{} instances of {}".format(v, k)) print("IDs:", ids[k]) print() Output 1 instances of 321 Test IDs: ['240895'] 2 instances of 567 Test IDs: ['21076377', '210763'] 3 instances of 123 Test IDs: ['13325942', '133259']
answers question: http://stackoverflow.com/q/48630146
has comment: http://stackoverflow.com/comment/84338724
score: 1

http://stackoverflow.com/comment/84222564
type: AnswerComment
has text: Verified! Works great, thanks! I hadn't found batch_dot in my searches and that's a neat bit of reshape syntax too.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48612851

http://stackoverflow.com/a/48603374
downvote count: 0
type: AcceptedAnswer
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/48603339
upvote count: 6
answers question: http://stackoverflow.com/q/48603339
has body: You can't. If you want to run JavaScript, you'll need to use a headless browser. Otherwise, you'll have to disassemble the JavaScript and see what it does. Click on the element while your browser's developer tools are open in the Network tab: You can now see that the JavaScript downloads new HTML from that URL. You can easily send the same request with urllib.

http://stackoverflow.com/q/48605555
tagged with: pandas
answer count: 0
downvote count: 0
favorite count: 0
type: Question
has body: Consider the following program: import pandas as pd import datetime import time import psutil import os import gc # Construct a trivial pandas time series data = [] indexes = [] for _ in xrange(5): data.append(_) indexes.append(datetime.datetime.now()) time.sleep(1) s = pd.Series(data, index=indexes) for _ in xrange(100000): # Remove the next line to prevent memory leak foo = datetime.datetime.now() - s.index[-1] # These lines are okay foo_dt = datetime.datetime.now() foo_idx = s.index[-1] #gc.collect() # This mitigates but does not eliminate the problem # Get memory per https://stackoverflow.com/a/21632554/939259 process = psutil.Process(os.getpid()) print(process.memory_info().rss) This gives the result (if the gc.collect() is included): $ python ./test_leak.py | uniq 60502016 60547072 60755968 &lt;snip&gt; Without the gc.collect() is similar: $ python ./test_leak.py | uniq 60518400 60588032 60776448 &lt;snip&gt; What's going on here? Why is memory increasing when all I'm doing is assigning a temporary?
upvote count: 2
type: UnansweredQuestion
tagged with: memory-leaks
tagged with: garbage-collection
tagged with: python
has title: Why does this simple pandas operation leak memory?
linked to: http://stackoverflow.com/q/938733
score: 2

http://stackoverflow.com/a/48613163
upvote count: 15
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84223127
accepted answer of: http://stackoverflow.com/q/48613146
has comment: http://stackoverflow.com/comment/84223720
type: Answer
answers question: http://stackoverflow.com/q/48613146
score: 15
has body: You're instantiating the class here, which you shouldn't. It should be: path('organizations/', views.OrganizationListView.as_view(), name='organizations'),
has comment: http://stackoverflow.com/comment/84223208

http://stackoverflow.com/comment/84252086
type: QuestionComment
has text: Yes. That would be good. But I wanted to know how to do it without of virtualization. @RayToal
score: 0
comment on: http://stackoverflow.com/q/48627444
type: Comment

http://stackoverflow.com/comment/100814509
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48527480
has text: You should be able to find your credential in Google API Console: https://console.developers.google.com/apis/credentials
score: 0

http://stackoverflow.com/comment/84228544
comment on: http://stackoverflow.com/a/48594301
type: AnswerComment
has text: Welcome borther @J. Torres
score: 0
type: Comment

http://stackoverflow.com/q/48603692
type: AnsweredQuestion
has title: Parsing XML Data with Python
upvote count: 2
accepted answer: http://stackoverflow.com/a/48604817
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48604817
favorite count: 0
type: Question
tagged with: lxml
has body: actually I am working on a small project and need to parse public available XML data. My goal is to write the data to an mysql database for further processing. XML Data Link: http://offenedaten.frankfurt.de/dataset/912fe0ab-8976-4837-b591-57dbf163d6e5/resource/48378186-5732-41f3-9823-9d1938f2695e/download/parkdatendyn.xml XML structure (example): 0.2533602 <parkingAreaOccupancyTrend>stable</parkingAreaOccupancyTrend> <parkingAreaReference targetClass="ParkingArea" id="2[Zeil]" version="1.0"/> <parkingAreaStatusTime>2018-02- 04T01:30:00.000+01:00</parkingAreaStatusTime 0.34625 <parkingAreaOccupancyTrend>stable</parkingAreaOccupancyTrend> <parkingAreaReference targetClass="ParkingArea" id="5[Dom / Römer]" version="1.0"/> Using the code import csv import pymysql import urllib.request url = "http://offenedaten.frankfurt.de/dataset/912fe0ab-8976-4837-b591-57dbf163d6e5/resource/48378186-5732-41f3-9823-9d1938f2695e/download/parkdatendyn.xml" from lxml.objectify import parse from lxml import etree from urllib.request import urlopen locations_root = parse(urlopen(url)).getroot() locations = list(locations_root.payloadPublication.genericPublicationExtension.parkingFacilityTableStatusPublication.parkingAreaStatus.parkingAreaReference) print(*locations) I expected to get a list of all "parkingAreaReference" entries within the XML document. Unfortunately the list is empty. Playing arround with some code I got the sentiment that only the first block is parsed, I was able to fill the list with the value of "parkingAreaOccupancy" of the "parkingAreaReference" id="2[Zeil]" block by using the code locations = list(locations_root.payloadPublication.genericPublicationExtension.parkingFacilityTableStatusPublication.parkingAreaStatus.parkingAreaOccupancy) print(*locations) -> 0.2533602 which is not the expected outcome -> 0.2533602 -> 0.34625 MY question is: What is the best way to get a matrix i can further work with of all blocks incl. the corresponding values stated in the XML documen…
tagged with: python
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
score: 2

http://stackoverflow.com/q/48637985
upvote count: 2
type: AnsweredQuestion
score: 2
has title: Identify channels in a wav file?
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51028661
favorite count: 0
has answer: http://stackoverflow.com/a/51028661
type: Question
has comment: http://stackoverflow.com/comment/84323472
has body: I have numerous audio wav files. Every audio files have 2 channels and each channel contains voices of 2 different persons so I want to get the channel where the activity is more or we can say the channel where the speaker is saying more and I have to delete the other channel. As of now I am doing this with audacity but can i do it via python or any terminal command in ubuntu?
tagged with: python
tagged with: wav
has comment: http://stackoverflow.com/comment/84326584
has comment: http://stackoverflow.com/comment/84331531
tagged with: audio
has comment: http://stackoverflow.com/comment/84326623
has comment: http://stackoverflow.com/comment/84353507

http://stackoverflow.com/comment/84147465
score: 0
has text: From what I understand, only one radiobutton of each group should be selectable. I am right?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48575298

for-loop
tags question: http://stackoverflow.com/q/48625782
tags question: http://stackoverflow.com/q/48534380
tags question: http://stackoverflow.com/q/48517177
tags question: http://stackoverflow.com/q/48510455
tags question: http://stackoverflow.com/q/48562563
tags question: http://stackoverflow.com/q/48638004
tags question: http://stackoverflow.com/q/48590311
tags question: http://stackoverflow.com/q/48591755
tags question: http://stackoverflow.com/q/48587475
tags question: http://stackoverflow.com/q/48550897
tags question: http://stackoverflow.com/q/48595418
tags question: http://stackoverflow.com/q/48630603
tags question: http://stackoverflow.com/q/48494831
tags question: http://stackoverflow.com/q/48596542
type: Tag
tags question: http://stackoverflow.com/q/48494110
tags question: http://stackoverflow.com/q/48522335
tags question: http://stackoverflow.com/q/48627715
tags question: http://stackoverflow.com/q/48629153
tags question: http://stackoverflow.com/q/48530320
tags question: http://stackoverflow.com/q/48645464
tags question: http://stackoverflow.com/q/48517912
tags question: http://stackoverflow.com/q/48595211
tags question: http://stackoverflow.com/q/48608600
tags question: http://stackoverflow.com/q/48617196
tags question: http://stackoverflow.com/q/48592831
tag name: for-loop
tags question: http://stackoverflow.com/q/48611525
tags question: http://stackoverflow.com/q/48564743
tags question: http://stackoverflow.com/q/48515437
tags question: http://stackoverflow.com/q/48588103
tags question: http://stackoverflow.com/q/48601406
tags question: http://stackoverflow.com/q/48566704
tags question: http://stackoverflow.com/q/48629695
tags question: http://stackoverflow.com/q/48498635
tags question: http://stackoverflow.com/q/48513802
tags question: http://stackoverflow.com/q/48623494
tags question: http://stackoverflow.com/q/48522316
tags question: http://stackoverflow.com/q/48519265
tags question: http://stackoverflow.com/q/48498018

http://stackoverflow.com/comment/84092584
type: Comment
has text: I tried using if num.isdigit() == True: l.append(num) but that works only with integers
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48548236

http://stackoverflow.com/q/48585532
has comment: http://stackoverflow.com/comment/84168165
has comment: http://stackoverflow.com/comment/84168175
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I am working with a python list as the following code: x=[0.1,0.1,0.1] dx=0.1 R=1 while x[0] &lt; R: while x[1] &lt; R: if np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2) &lt; R: x[2] = x[2] + dx counter = counter + 1 else: x[1] = x[1] + dx x[0]= dx print(counter) x[0] = x[0] + dx x[1] = dx But for a bigger list for example: x=[0.1,0.1,0.1,0.1] dx=0.1 #we have to add another while loop while x[0]&lt;R: while x[1]&lt;R: while x[2]&lt;R: if np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2) &lt; R: x[3] = x[3] + dx counter = counter + 1 else: x[2] = x[2] + dx x[1]= dx x[1] = x[1] + dx x[2] = dx x[0]=x[0]+dx x[1]=dx and so on What I am trying to to do is to find a way to implement this code for any list of any number of element (the general case) But I cannot find out how to transform these while loops to any number of dimesnions (number of elements in the array) and just in case this code will do the following: example: for dx=0.1 and R=1 and we start with 0.1 start with x=[0.1, 0.1, 0.1] (after the first loop) x=[0.9, 0.1, 0.1] And then [0.1, 0.2, 0.1] And so on until [0.9, 0.9, 0.1] After we will get [0.1,0.1,0.2] And we will start again with [0.2, 0.1, 0.2] and so on Any help would be much appreciated
has comment: http://stackoverflow.com/comment/84168004
has comment: http://stackoverflow.com/comment/84168131
tagged with: list
score: 0
tagged with: while-loop
has comment: http://stackoverflow.com/comment/84168270
has title: find the general case of while loops
tagged with: loops
has comment: http://stackoverflow.com/comment/84176150
has comment: http://stackoverflow.com/comment/84168033
has comment: http://stackoverflow.com/comment/84168071
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48585728

http://stackoverflow.com/q/48559356
answer count: 7
accepted answer: http://stackoverflow.com/a/48559400
has body: I want to convert all the excel document(.xls) sheets into csv, If excel document has one sheet only then I am converting like as follow- wb = open_workbook(path1) sh = wb.sheet_by_name('Sheet1') csv_file = open(path2, 'w') wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL) for rownum in range(sh.nrows): wr.writerow(sh.row_values(rownum)) csv_file.close() If my excel(.xls) document have more than one sheet i.e.('Sheet1', 'Sheet2', 'Sheet3', 'Sheet4') than how to convert all sheets into csv. Any help would be appreciated.
has answer: http://stackoverflow.com/a/68397327
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53474120
upvote count: 8
has comment: http://stackoverflow.com/comment/125986446
has answer: http://stackoverflow.com/a/57313286
downvote count: 2
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/48559400
has title: How to convert multiple excel sheets to csv python
tagged with: excel
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61429851
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/65497391
has answer: http://stackoverflow.com/a/60794003
possible better answer: http://stackoverflow.com/a/60794003

http://stackoverflow.com/q/48620532
accepted answer: http://stackoverflow.com/a/48649499
has answer: http://stackoverflow.com/a/48649499
upvote count: 2
tagged with: python
has body: I'm trying to copy an entire column over using OpenPyXL. Google seems to offer a lot of examples using ranges, but not for an entire column. I have a workbook with a single worksheet with a load of dates in column A and column JX (A contains monthly dates, JX contains quarterly dates). I want the monthly dates column (in A:A) to be copied over to each worksheet ending in 'M' in my target workbook, and the quarterly dates column (in JX:JX) to the worksheets ending in 'Q'. However, for some reason the last nested for loop, for src, dst in zip(ws_base[monthRange], ws_target['A:A']): is only copying the first cell, and nothing else. It looks like I'm identifying the correct column with my monthRange and quarterRange strings, but Python isn't looping through the whole column despite the fact that I've got two ranges defined. Does anyone have any ideas? # Load the target workbook targetwb = openpyxl.load_workbook('pythonOutput.xlsx') # Load the source workbook wb_base = openpyxl.load_workbook('Baseline_IFRS9_' + reportingMonth+'.xlsx') # Go to row 9 and find "Geography:" to identify the relevant # month and quarter date columns sentinel = u"Geography:" ws_base = wb_base.active found = 0 dateColumns = [] for column in ws_base: for cell in column: if cell.value == sentinel: dateColumns.append(cell.column) # found + 1 if found == 2: break ColumnM = dateColumns[0] ColumnQ = dateColumns[1] print('Monthly col is ' + ColumnM) print('Quarterly col is ' + ColumnQ) IndexM = int(openpyxl.utils.column_index_from_string(str(ColumnM))) IndexQ = int(openpyxl.utils.column_index_from_string(str(ColumnQ))) print('Monthly col index is ' + str(IndexM)) print('Quarterly col index is ' + str(IndexQ)) print('Proceeding to paste into our new workbook...') sheetLoop = targetwb.get_sheet_names() for sheets in sheetLoop: if sheets.endswith('Q'): ws_target = targetwb[sheets] quarterRange = ColumnQ + ':' + ColumnQ print('Copying and pasting quarterly dates into: ' + sheets) for src, dst in zip(ws_bas…
type: AnsweredQuestion
score: 2
has title: Copying an entire column using OpenPyXL in Python 3
tagged with: openpyxl
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/84181751
has text: What do you mean by "require variable input"? Generally Python functions don't care about the original variable names of their arguments (in fact they don't even know, though you can introspect it), they only care about the objects themselves.
comment on: http://stackoverflow.com/a/48591784
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84211041
type: Comment
type: QuestionComment
has text: @louc Sure, I can use `append` as well instead of reassigning the layout to the complete list. But the problem is what I have written in my question: "It works well in a number of situations" (as Bryan says). I want to build a complex layout, so I was wondering if I do `curdoc().clear()` and `curdoc().add_root(new_layout)` would solve the problem. Moreover I can read on your link "Additive development, not subtractive or mutative", what I need to do is substractive or mutative.
comment on: http://stackoverflow.com/q/48566181
score: 0

http://stackoverflow.com/a/48671403
score: 1
upvote count: 1
has body: The POST request with attached file can be sent using POSTMAN. 1) Select: Select POST option from the drop-down list. 2) Add File: File can be added through the Body > Binary option. Choose the file to be sent. 3) Check Request object List of files sent to Django Server at localhost:8000 can now be received by request.FILES The Docs on request object can be found here 4) Create Django File Object Further, to make the file acceptable by Django Model's FileField, it has to be in Django's File Object format. from django.core.files import File file_obj = open(path_to_file,"r") django_file = File(file_obj) This can be manually passed to Model's instance's FileField, and will be accepted. For more information on Django File Object, see docs.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48641130
type: Answer
accepted answer of: http://stackoverflow.com/q/48641130
downvote count: 0

http://stackoverflow.com/comment/84004485
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48505116
score: 0
has text: Does it work on a normal worksheet (as opposed to a chartsheet)?

http://stackoverflow.com/comment/83970561
comment on: http://stackoverflow.com/q/48488703
score: 0
type: Comment
type: QuestionComment
has text: I've appended the reason why I want this to the Q. But my intention is to end up having a filter-able field on each of my <Thing>s.

http://stackoverflow.com/a/48630334
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48630019
has body: updated (sorry for typo's) Since you're reading in all the lines into an array anyway. Just read the entire file into a string. Then clean it up with a find (?m)$(?:\s*\r?\n)+ replace \r\n Use whatever CRLF translation your system uses. This just removes all extra linebreaks. If you want to make it with an extra line separation, make the replacement \r\n\r\n.

http://stackoverflow.com/a/52803626
has body: I am on windows 10, python 3.5, pip 10 dlib didn't work even after installing cmake. Solution : Add cmake into PATH(C:\Program Files\CMake\bin) Then install using pip: pip install dlib==19.4 Works like a charm. Edit: After windows October update, the above method works, but sometimes there are errors like boost error and cmake incompatible. so, Download and install CMake msi Add cmake into PATH(C:\Program Files\CMake\bin) Restart Windows pip install dlib or pip install dlib==19.4
upvote count: 6
answers question: http://stackoverflow.com/q/48624415
type: Answer
has comment: http://stackoverflow.com/comment/109892163
type: AcceptedAnswer
downvote count: 1
score: 5
accepted answer of: http://stackoverflow.com/q/48624415

http://stackoverflow.com/q/48603505
score: -3
has comment: http://stackoverflow.com/comment/84203682
tagged with: python
has comment: http://stackoverflow.com/comment/84219882
possible better answer: http://stackoverflow.com/a/62281172
type: AnsweredQuestion
has title: Space between words when writing to csv
has answer: http://stackoverflow.com/a/62281172
downvote count: 3
has body: when I execute the below lines. I receive a space between each letter and the words do not format properly. any help is appreciated. import csv with open('u2.csv', 'w', newline='') as csvfile: wf = csv.writer(csvfile, delimiter = '\t') for key in wordcount.keys(): wf.writerow("%s %s" %(key, wordcount[key]))
accepted answer: http://stackoverflow.com/a/48611824
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48611824
answer count: 2
upvote count: 0
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/84281197
score: 0
has text: `b = ('mfcc_delta_{} ' * 10).format(*range(1, 11)).split()`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48642092

http://stackoverflow.com/q/48506461
type: AnsweredQuestion
score: 0
tagged with: tokenize
has body: I want to be able to analyze a local txt file I have using NLTK. By analyze, I mean use NLTK capabilities such as tokenizing, sentiment analysis etc. I have a local file in my Python directory named 'example.txt'. import nltk from nltk.tokenize import sent_tokenize, word_tokenize with open ('example.txt', 'r') as f: for line in f: f_contents = f.readlines() print(word_tokenize(f_contents)) I am trying to print 'f_contents' in tokenized format. 'F_contents' in this case should be the text within 'example.txt'. Any help would be appreciated.
answer count: 1
accepted answer: http://stackoverflow.com/a/48511803
duplicate of: http://stackoverflow.com/q/12703842
has answer: http://stackoverflow.com/a/48511803
type: Question
tagged with: nltk
linked to: http://stackoverflow.com/q/12703842
tagged with: python
has title: How to tokenize a file?

http://stackoverflow.com/q/48597958
answer count: 6
tagged with: regex
has answer: http://stackoverflow.com/a/48603824
has body: I have a specific scenario where I have a data frame in which in one column I have text values like 'AZZZZ0ZZZZ', 'ZZZZZ0ZZZZ', 'BOMBAY 2.0' and I want to replace the middle '0' with 'NA'. If I use simple replace command the other strings replace correctly but 'BOMBAY 2.0'. I tried many different RegEx combinations but no luck. df['column'].str.replace ('0','na') - results in changing the BOMBAY 2.0 df['column'].str.replace (r'\B0\B','na') - results in changing other values where I have 'nagpur' to '0gpur'
score: -3
has answer: http://stackoverflow.com/a/48599609
has comment: http://stackoverflow.com/comment/84192574
has answer: http://stackoverflow.com/a/48598109
upvote count: 0
has answer: http://stackoverflow.com/a/48599122
downvote count: 3
has comment: http://stackoverflow.com/comment/84192749
has answer: http://stackoverflow.com/a/48606530
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84192476
has comment: http://stackoverflow.com/comment/84193414
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48598206
has title: How to replace 0 from middle of string
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/48645285
tagged with: python
tagged with: monitoring
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84287760
answer count: 0
tagged with: subprocess
score: 1
has comment: http://stackoverflow.com/comment/84287446
downvote count: 0
has comment: http://stackoverflow.com/comment/84287525
upvote count: 1
tagged with: file-upload
favorite count: 0
type: Question
has body: I have a scenario where I need to upload some huge files to a remote location and that runs for 3 days (700+ GB), here, all are command line activity and there is no UI or GUI to monitor it. How do I do it using some interesting and useful python modules? Any suggested modules would help here. Currently, i am doing it using the while loop which is not helping much here. I am running the job inside a screen, once the job completed - checking the md5sum of each of the files and compare it with source &amp; destination. I am using modules os, sys, subprocess, pexpect, time, glob etc.
type: UnansweredQuestion
has title: How do i monitor a job that run for 3 days using python? Any suggested modules to be use here?

http://stackoverflow.com/comment/84111177
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48557624
has text: What did you try and what problems did you run into? As it stands it looks like a programming service request, which is clearly off-topic.

http://stackoverflow.com/q/48601299
answer count: 1
tagged with: split-apply-combine
favorite count: 0
has answer: http://stackoverflow.com/a/48601471
type: Question
has title: Groupby cumulative mean with wide/long pivoting
tagged with: python
accepted answer: http://stackoverflow.com/a/48601471
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has body: I have a DataFrame that looks like this (see bottom here for code to reproduce it): date id_ val 0 2017-01-08 a; b 9.3 1 2017-01-07 a; b; c 7.9 2 2017-01-07 a 7.3 3 2017-01-06 b 9.0 4 2017-01-06 c 8.1 5 2017-01-05 c 7.4 6 2017-01-05 d 7.1 7 2017-01-05 a 7.0 8 2017-01-04 b; a 7.7 9 2017-01-04 c; a 5.3 10 2017-01-04 a; c 8.0 I want to groupby the individual (semicolon-delimited) elements of id_ and calculate a cumulative mean of val up to but not including each date. This should give NaNs for the first occurence of any id_, which I'm then filling with some arbitrary value (6.0 here). Output: id_ a 0 6.0000 1 9.3000 2 8.6000 7 8.1667 8 7.8750 9 7.8400 10 7.4167 b 0 6.0000 1 9.3000 3 8.6000 8 8.7333 c 1 6.0000 # fill value 4 7.9000 # first actual occurrence of id_='c' 5 8.0000 # cumulative mean of the first two 'c' 9 7.8000 10 7.1750 d 6 6.0000 Name: val, dtype: float64 This is my current process, which is quite slow--can it be improved? Secondly, can I maintain the date col in the final result? # seems like `pd.melt` might be more direct here df.sort_values('date', inplace=True) stacked = df.id_.str.split('; ', expand=True).stack() stacked.index = stacked.index.droplevel(1) stacked = stacked.to_frame()\ .merge(df, left_index=True, right_index=True)\ .drop('id_', axis=1)\ .rename({0: 'id_'}, axis=1) def trend_scorer(s: pd.Series, fillvalue=6.): return s['val'].expanding().mean().shift(1).fillna(fillvalue) stacked.groupby('id_').apply(trend_scorer) DataFrame creation: import pandas as pd data = \ {'id_': {0: 'a; b', 1: 'a; b; c', 2: 'a', 3: 'b', 4: 'c', 5: 'c', 6: 'd', 7: 'a', 8: 'b; a', 9: 'c; a', 10: 'a; c'}, 'date': {0: '1/8/17', 1: '1/7/17', 2: '1/7/17', 3: '1/6/17', 4: '1/6/17', 5: '1/5/17', 6: '1/5/17', 7: '1/5/17', 8: '1/4/17', 9: '1/4/17', 10: '1/4/17'}, 'val': {0: 9.3, 1: 7.9, 2: 7.3, 3: 9.0, 4: 8.1, 5: 7.4, 6: 7.1, 7: 7.0, 8: 7.7, 9: 5.3, 10: 8.0}} df = pd.DataFrame(data) df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)

http://stackoverflow.com/comment/84053603
type: QuestionComment
has text: It looks like the website's certificate is messed up: [see here](https://swd.bits-goa.ac.in)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48529032

http://stackoverflow.com/a/61879604
has comment: http://stackoverflow.com/comment/129518081
answers question: http://stackoverflow.com/q/48543834
has comment: http://stackoverflow.com/comment/129475396
type: Answer
upvote count: 18
has comment: http://stackoverflow.com/comment/131233887
downvote count: 0
score: 18
has body: I recommend the approach detailed in this article (section 2). He uses virtualenv so pip install stores all the python code, binaries, etc. under one folder instead of spread out all over the file system. Then it's easy to copy just that one folder to the final "production" image. In summary: Compile image Activate virtualenv in some path of your choosing. Prepend that path to your docker ENV. This is all virtualenv needs to function for all future docker RUN and CMD action. Install system dev packages and pip install xyz as usual. Production image Copy the virtualenv folder from the Compile Image. Prepend the virtualenv folder to docker's PATH

http://stackoverflow.com/comment/84276309
has text: @casevh you all are forgetting that the underlying data is encoded in binary, at least the float64. This way, on top of the rounding in the numerical library another rounding is done when printing a number with decimals. The answer from user2357112 reflects this. The displayed difference most likely will be larger than when comparing the binary representation.
score: 2
comment on: http://stackoverflow.com/q/48638398
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83988588
comment on: http://stackoverflow.com/q/48497115
has text: Add the entire error stack trace
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/48610188
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84216821
downvote count: 2
has comment: http://stackoverflow.com/comment/84216955
upvote count: 1
linked to: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/84216894
has comment: http://stackoverflow.com/comment/84216862
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48610209
has title: python test multiple conditions with or operator
linked to: http://stackoverflow.com/q/16579085
has body: How can I test if one of the multiple items exist in a list using or? I tried: data = [[1,'a',4,],['a','b','c'],['c',3,5]...] for i,val enumerate(data): if 'a' or 'b' or 'c' in val: data.pop(i) But it removes the first row only
has comment: http://stackoverflow.com/comment/84216839
duplicate of: http://stackoverflow.com/q/15112125
tagged with: python
duplicate of: http://stackoverflow.com/q/16579085
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/48610211

http://stackoverflow.com/a/48621632
has body: The standard trick with numpy.lib.stride_tricks.as_strided should work here: das = np.lib.stride_tricks.as_strided(data, (5, 5, 100, 2, 3, 3), data.strides[-2:] + data.strides) patches = das[(*pos, np.arange(100))] You can verify it works using: for i in range(data.shape[0]): assert np.all(patches[i]==data[i,:,pos[0,i]:pos[0,i]+size,pos[1,i]:pos[1,i]+size])
has comment: http://stackoverflow.com/comment/84242231
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48620923
answers question: http://stackoverflow.com/q/48620923
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48599380
accepted answer: http://stackoverflow.com/a/48600274
has comment: http://stackoverflow.com/comment/84195266
has comment: http://stackoverflow.com/comment/84195333
has comment: http://stackoverflow.com/comment/84195553
has comment: http://stackoverflow.com/comment/84195282
has answer: http://stackoverflow.com/a/48600274
has body: Suppose I have a nested tuple as follows: a = (((1, 2), 2), 3) I know we could use a[0][0][1] to acquire the second element 2. However, this method might be inefficient with a long tuple. Is there any more efficient way to acquire the tuple element in this case?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84195736
has comment: http://stackoverflow.com/comment/84195564
has comment: http://stackoverflow.com/comment/84195345
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/84195366
possible better answer: http://stackoverflow.com/a/48599702
has comment: http://stackoverflow.com/comment/84195527
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84195609
has title: Acquire tuple element in python
has answer: http://stackoverflow.com/a/48599702
answer count: 2
has comment: http://stackoverflow.com/comment/84195277
has comment: http://stackoverflow.com/comment/84195665
score: -2
has comment: http://stackoverflow.com/comment/84195360
has comment: http://stackoverflow.com/comment/84195605
tagged with: python

http://stackoverflow.com/q/48612225
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
tagged with: scraper
type: UnansweredQuestion
has title: How to get values and item name from website using Beautiful Soup
has body: Bit of a basic bs4 question here, but been trying for hours! url = 'https://www.currys.co.uk/gbuk/search-keywords/xx_xx_xx_xx_xx/acer/xx-criteria.html' r = urllib.request.urlopen(url).read() soup = BeautifulSoup(r,'lxml') price = soup.find_all("div", class_="productPrices") How do I now go about consuming the price? In this case, that is the "strong class="price" data-product="price"> tag. I also want to be able to consume the product SKU: "productSKU":"200341" I'd like to be able to loop through all pages matching my search (in this case, just "acer") and store as a dataframe ALL skus and prices matching that search.
downvote count: 5
tagged with: python
score: -5
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48612514
favorite count: 0

http://stackoverflow.com/comment/84076951
type: QuestionComment
comment on: http://stackoverflow.com/q/48540589
type: Comment
score: 0
has text: What's your python and numpy version?

http://stackoverflow.com/q/48643243
accepted answer: http://stackoverflow.com/a/48668704
has title: matplotlib y-scale as log with base e
has answer: http://stackoverflow.com/a/48668704
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84306684
answer count: 1
has comment: http://stackoverflow.com/comment/84283884
has comment: http://stackoverflow.com/comment/84333934
tagged with: logging
type: Question
has comment: http://stackoverflow.com/comment/84306885
has body: I am trying to plot a a function which goes as I_threshold=A*e^(T/T_0). so the y-axis are log scaled with base e. My input look like this Temp=[10,12.5,15,17.5,20,22.5,25,27.5,30,32.5,35,37.5,40,42.5,45,47.5,50] and output, which is I_threshold looks like this [22.376331312083646, 22.773439481450737, 23.440242034972115, 23.969920199339803, 24.80014584753161, 25.275728442307503, 26.291852943772966, 26.969268640398795, 28.09683889698702, 28.952552190706545, 30.325961112054102, 31.488435380923281, 33.176033568454699, 34.613872631424236, 36.710165595581906, 38.567151879424728, 41.245216030694756] I tried to def a function and return the function with the equation described above. And so I used the following code to scatter and plot the function. fig3=plt.figure(3) ax3=fig3.add_subplot(111) def efit(T,T_0,A): return(A*np.e**(T/T_0)) Temp=[10,12.5,15,17.5,20,22.5,25,27.5,30,32.5,35,37.5,40,42.5,45,47.5,50] params_dremp, covariance_dremp= optimize.curve_fit(efit,Temp,I_threshold) #print(params_dremp[0],params_dremp[1]) majorLocator_2=MultipleLocator(5) majorFormatter_2=FormatStrFormatter('%.1f') minorLocator_2=MultipleLocator(1) #ax3.xaxis.set_major_locator(majorLocator_2) #ax3.xaxis.set_major_formatter(majorFormatter_2) #ax3.xaxis.set_minor_locator(minorLocator_2) locmaj = LogLocator(base=np.e, numticks=1) ax3.yaxis.set_major_locator(locmaj) print(I_threshold) #print(np.size(Temp),np.size(I_threshold)) plt.scatter(Temp,I_threshold) ax3.set_yscale('log',basey=np.e) #plt.semilogy(Temp,I_threshold, basey=np.e) #plt.plot(Temp,fitt(Temp,*params_dremp),'b--') plt.xlabel('$ T_c \ (^0 C)$') plt.ylabel('$ I_t \ (mA) $') #plt.tick_params(axis='y', which='minor') plt.grid(True,which="major",color='black',ls="-",linewidth=0.5) when i scatter plot the data in normal scale. i get the following image. However, I get the following image when scattering with y-axis in log scale with base e. This graph does not seem to be linear when looking at the image. Does someone know what went wrong …
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/q/48502871
tagged with: python
possible better answer: http://stackoverflow.com/a/48503607
has body: size = (raw_input ('\nWhat Size do you want?').lower() l_size =['large' , 'lerge' , 'l', 'larg' ,'lorge' ,] m_size =['m' , 'med' , 'medium'] s_size =['s' , 'small' , 'smell', 'smoll'] I'm using this in order to get the correct input, if the user types incorrectly while size not in ('l_size', 'm_size','s_size'): print ("\033[1;31m Invalid input! Trying Again\n"), size = raw_input("\033[1;32;40m What Size do you want? \n") If the user types incorrectly I want to run the program from the start if size in l_size: print '\nYour coffee is Large! ' elif size in m_size: print '\n Your Coffee is Medium' elif size in s_size: print '\nYour Coffee is Small' else: print '\nIncorrect Typing! Type Properly'\
has comment: http://stackoverflow.com/comment/83999336
favorite count: 0
has answer: http://stackoverflow.com/a/48503607
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/48581835
answer count: 3
accepted answer: http://stackoverflow.com/a/48503296
has title: How can i insert a multiple listed variable in a while loop?
has answer: http://stackoverflow.com/a/48503296
downvote count: 6
score: -6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83999413

http://stackoverflow.com/a/48549165
has comment: http://stackoverflow.com/comment/84095944
accepted answer of: http://stackoverflow.com/q/48549065
downvote count: 0
has body: Here is one way via itertools.combinations. from itertools import combinations lst = [2, 8, 16] result = sorted({sum(i) for j in range(1, len(lst)+1) for i in combinations(lst, j)}) # [2, 8, 10, 16, 18, 24, 26]
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48549065
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/comment/84079402
score: 0
has text: I tried Sudo pip install vpython but when I try import vpython on python shell, it says there is no module with that name
comment on: http://stackoverflow.com/a/48520458
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84094243
comment on: http://stackoverflow.com/q/48547818
score: 1
type: QuestionComment
has text: `df.tail(n)` is about as simple as it gets. If all you need are dates, can you `groupby` date or index?
type: Comment

http://stackoverflow.com/comment/84145555
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48551523
type: QuestionComment
has text: @WillemVanOnsem i know but i have never used dynamic programming, I'm still learning recursion shouldn't i learn that first?

http://stackoverflow.com/comment/84050360
type: Comment
has text: My sum code is not here as it was not working!
type: QuestionComment
comment on: http://stackoverflow.com/q/48527573
score: 0

http://stackoverflow.com/comment/84176290
score: 0
comment on: http://stackoverflow.com/q/48582698
type: QuestionComment
has text: Checked.. You are right. I was using spark 1.6. Can you try by the older way of creating dataframe.? I think, zeppelin support that as well. Also, u cam check rdd.toDF() to create dataframe.
type: Comment

http://stackoverflow.com/comment/84032976
comment on: http://stackoverflow.com/q/48519001
score: 0
has text: `$ python2 setup-app.py -bash: python2: command not found`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84177006
has text: @jp_data_analysis yep , when I writing down my working script , I always break it down to multiple line (easy for debug and setting block ), but seems like SOer addict to one liner solution :-)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48589848

http://stackoverflow.com/q/48589567
has comment: http://stackoverflow.com/comment/84176345
tagged with: python
tagged with: heatmap
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48589773
has answer: http://stackoverflow.com/a/48589773
tagged with: matplotlib
answer count: 1
downvote count: 0
upvote count: 10
has title: How to centre a colorbar at a defined value for seaborn heatmap?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84176314
tagged with: seaborn
score: 10
has body: I am trying to plot a heatmap using seaborn. I have values from 0 to 5 and I need to make a blue-to-red color scale, with white being at 1, blue- below 1, and red - from 1 to 5. How can I do that? import seaborn as sns; sns.set() hm=sns.heatmap(proportion, vmin=0, vmax=5, cmap='RdBu') This is what I try to do, but it is not customized... 'proportion' is my variable. Is there anything I can do?

http://stackoverflow.com/q/48592863
has answer: http://stackoverflow.com/a/48592884
type: AnsweredQuestion
has title: Python - Multiplying an element from a dictionary nested in a list by another element from the same dictionary?
tagged with: python
tagged with: dictionary
type: Question
score: 0
has body: I have a challenge that I need to complete for Codio, but I'm stuck. The challenge is to create a list of dictionaries that are grocery items (you'll see what I mean in the 'while' statement). Then find the cost of each item by multiplying the price by the number of that item, then adding them all up and displaying it. I keep receiving the error: "TypeError: can't multiply sequence by non-int of type 'float'" when I attempt to multiply value*value2. I have specified which dictionary within the list to pull key/values from (by setting x equal to the number of elements in the list) and which key/value to pull a number from, so I don't know what's going on exactly. How would I multiply the value of 'number' by the value of 'price'? The code below is just one of many methods I have tried. Thanks! grocery_item = {} grocery_history = [] stop = 'go' while stop!='q': item_name=input("Item name:\n") quantity=int(input("Quantity purchased:\n")) cost=float(input("Price per item:\n")) grocery_item={'name':item_name, 'number':int(quantity), 'price':float(cost)} grocery_history.append(grocery_item) stop=input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit") grand_total=0 #Define a 'for' loop. for x in range(0, len(grocery_history)): value=float(grocery_history[x]['number']) value2=float(grocery_history[x]['price']) #Calculate the total cost for the grocery_item. item_total="%.2f" % value*value2 #Add the item_total to the grand_total grand_total="%.2f" % float(grand_total+item_total) #Output the information for the grocery item to match this example: #2 apple @ $1.49 ea $2.98 print (grocery_history[x]['number']+" "+grocery_history[x]['name']+" @ "+grocery_history[x]['price']+" ea $"+grand_total) item_total=0 print (grand_total)
answer count: 1
tagged with: nested
accepted answer: http://stackoverflow.com/a/48592884
has comment: http://stackoverflow.com/comment/84183105

http://stackoverflow.com/comment/84061721
score: 0
has text: Do you have any experience with web-dev? I can recommend some ideas based on your experience.
comment on: http://stackoverflow.com/q/48532933
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84191568
comment on: http://stackoverflow.com/a/48597147
type: AnswerComment
score: 0
has text: Please post plain text in the question, not images.
type: Comment

http://stackoverflow.com/comment/84046282
score: 0
comment on: http://stackoverflow.com/a/48515962
type: Comment
type: AnswerComment
has text: So you want a dictionary?

http://stackoverflow.com/a/48592830
type: Answer
has body: Your test matrix is currently one dimensional. If you want to create a random matrix with numpy, you can just do: num_rows = 3 num_columns = 3 random_matrix = numpy.random.random((num_rows, num_columns)) The result would be: array([[ 0.15194989, 0.21977027, 0.85063633], [ 0.1879659 , 0.09024749, 0.3566058 ], [ 0.18044427, 0.59143149, 0.25449112]]) You can also create a random matrix without numpy: import random num_rows = 3 num_columns = 3 random_matrix = [[random.random() for j in range(num_rows)] for i in range(num_columns)] The result would be: [[0.9982841729782105, 0.9659048749818827, 0.22838327707784145], [0.3524666409224604, 0.1918744765283834, 0.7779130503458696], [0.5239230720346117, 0.0224389713805887, 0.6547162177880549]] Per the comments, I've added a function to convert a one dimensional array to a matrix: def convert_to_matrix(arr, chunk_size): return [arr[i:i+chunk_size] for i in range(0, len(arr), chunk_size)] arr = [1,2,3,4,5,6,7,8,9] matrix = convert_to_matrix(arr, 3) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]] is the output
score: 0
has comment: http://stackoverflow.com/comment/84182966
answers question: http://stackoverflow.com/q/48592731
has comment: http://stackoverflow.com/comment/84183037
has comment: http://stackoverflow.com/comment/84183085
has comment: http://stackoverflow.com/comment/84183018

http://stackoverflow.com/a/48530098
answers question: http://stackoverflow.com/q/48529957
type: Answer
has body: list_b only contains one element, ['name2', 2, 'name4', 4, 'name4', 1, 'name4', 6, 'name2', 6]. To unpack list_b in a for loop, you would need to use ten variables: for name1, val, name2, val2, name3, val3, name4, val4, name5, val5 in list_b: pass Since the above is long and unpythonic, you can flatten list_b and then regroup: from collections import defaultdict def data_sums(matrix): sums = defaultdict(int) for name, value in matrix: sums[name] += value result = [[k,v] for k,v in sums.items()] return result list_b = 'name2', 2, 'name4', 4, 'name4', 1, 'name4', 6, 'name2', 6 list_b = [i for b in list_b for i in b] final_b = [list_b[i:i+2] for i in range(0, len(list_b), 2)] print(data_sums(final_b)) Output: [['name4', 11], ['name2', 8]]
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/48507433
has body: Update :-) pd.concat([df[df.index.get_level_values(level=0)!='baz'],df.reindex(list(zip(['baz']*4,['two','four','three','one'])))]) Out[1156]: 0 1 2 3 bar one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 foo one 1.0 1.0 1.0 1.0 two 1.0 1.0 1.0 1.0 baz two 1.0 1.0 1.0 1.0 four 1.0 1.0 1.0 1.0 three 1.0 1.0 1.0 1.0 one 1.0 1.0 1.0 1.0
has comment: http://stackoverflow.com/comment/84010052
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48507197
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48547017
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
linked to: http://stackoverflow.com/q/21895756
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52328832
linked to: http://stackoverflow.com/q/1089018
accepted answer: http://stackoverflow.com/a/52328832
tagged with: floating-point
upvote count: 4
has comment: http://stackoverflow.com/comment/84090811
type: Question
tagged with: numpy
has body: Preface I'll preface this by saying two things: I'm new(er) to python/pandas, and trying not to reinvent the wheel I've read the documentation for pandas.to_numeric I've read Why Are Floating Point Numbers Inaccurate? and Why can't decimal numbers be represented exactly in binary?. I understand the concepts we're working with here, and am trying to figure out a "good" solution to getting a modicum of precision I know it would be easier to ensure users only enter numbers, but I don't have control over the source data; the program is a large-scale data validation tool which has to accept everything from the user no matter what was provided Background I'm working on porting a project from R to python, and am struggling to find a good way to translate a text-to-float conversion process. Specifically, I'm: Reading a pandas dataframe in from a SQL database (pandas.read_sql) Casting a column which is stored as text back into a number using pd_to_numeric Using the error='coerce' option to force the coercion from text to floats Checking the before/after to see if/where input was coerced to NaN Question How to I get pandas to neatly coerce a text representation of a float value to the corresponding float cleanly? The issue I'm running into is with the numerical precision. For example: In[1]: pd.to_numeric('3.785', errors='coerce') Out[2]: 3.7850000000000001 I understand why that's happening (i.e. 3.785 is represented in a way that's not easily presentable in the underlying binary representation). What I'm trying to figure out is if there's a way to work around why it's happening efficiently. For example, in R, there's a lot that goes on under the hood, but in the as.numeric API, you get the number that's ostensibly represented by the text value: &gt; as.numeric('3.785') [1] 3.785 which is my desired behavior. Is that possible using pandas/python? I'm open to incorporating other packages, or being told "that's impossible."
has comment: http://stackoverflow.com/comment/84152022
has comment: http://stackoverflow.com/comment/84151780
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/588004
score: 4
has comment: http://stackoverflow.com/comment/84091124
has title: Pandas to_numeric numerical precision

http://stackoverflow.com/q/48552036
answer count: 3
downvote count: 0
tagged with: pip
has answer: http://stackoverflow.com/a/61797876
favorite count: 0
type: Question
has title: ModuleNotFoundError: No module named 'psycopg2'
has comment: http://stackoverflow.com/comment/84101546
has answer: http://stackoverflow.com/a/55524314
has answer: http://stackoverflow.com/a/50525605
tagged with: python
type: UnansweredQuestion
tagged with: psycopg2
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/84100387
has body: I'm using Mac os. I installed pyscopg2 successfully (pip3 install psycopg2) But when I try to import psycopg2 I get the following message: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'psycopg2'

http://stackoverflow.com/comment/83980339
comment on: http://stackoverflow.com/a/48493572
type: Comment
score: 0
type: AnswerComment
has text: Also, if you're going to write an answer, you may as well fix the other problems... no 0 needed in `range`, and they could just do `a, b = b, a + b` instead of whatever it is they're doing now, etc.

http://stackoverflow.com/q/48528247
has body: I'm writing a simple time tracking application in Python3 and PyQt5. Time is tracked in separate thread. Function that this thread is running doesn't access GUI code. On Windows10 application freezes after trying to close it. It's caused by calling thread.join(). I need to end the process in task manager to close it. On Linux Mint it works fine. I'm using threads from threading library. It doesn't work also with QThread's. If I comment out the thread.join() line it closes without a problem, but the code that's running by this thread doesn't finish. Thread is initialized in __init__() function of Window class. self.trackingThread = Thread(target = self.track) Function that is responsible for tracking time: def track(self): startTime = time() lastWindowChangeTime = startTime while self.running: # check if active window has changed if self.active_window_name != get_active_window_name(): if self.active_window_name in self.applications_time: self.applications_time[self.active_window_name] += int(time() - lastWindowChangeTime) // 60 # time in minutes) else: self.applications_time[self.active_window_name] = int(time() - lastWindowChangeTime) // 60 # time in minutes lastWindowChangeTime = time() self.active_window_name = get_active_window_name() totalTime = int(time() - startTime) // 60 # time in minutes if date.today() in self.daily_time: self.daily_time[date.today()] += totalTime else: self.daily_time[date.today()] = totalTime Joining the thread: def saveAndQuit(self): self.running = False self.trackingThread.join() # the line that's causing application freeze self.save() QApplication.instance().quit() EDIT: Example: https://pastebin.com/vt3BfKJL relevant code: def get_active_window_name(): active_window_name = '' if system() == 'Linux': active_window_name = check_output(['xdotool', 'getactivewindow', 'getwindowname']).decode('utf-8') elif system() == 'Windows': window = GetForegroundWindow() active_window_name = GetWindowText(window) return active_window_name EDIT2: Afte…
has comment: http://stackoverflow.com/comment/84107127
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/84103588
has comment: http://stackoverflow.com/comment/84059409
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48528659
has answer: http://stackoverflow.com/a/48528659
tagged with: multithreading
tagged with: python
tagged with: freeze
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48553517
accepted answer: http://stackoverflow.com/a/48553517
has title: python application freeze on thread.join()

http://stackoverflow.com/comment/84242635
type: Comment
score: 2
has text: Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)
comment on: http://stackoverflow.com/q/48620963
type: QuestionComment

http://stackoverflow.com/comment/84288573
has text: What issue did you have using the msvcrt module?
score: 0
comment on: http://stackoverflow.com/q/48645643
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/111370060
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48509364
type: Comment
has text: @Karthikeyan: All the links which you shared in answer redirect to Amplify framework documentation. Why AWS is pushing to use amplify? I have asked a separate question https://stackoverflow.com/questions/62973171/android-amplify-uploading-downloading-file-to-from-aws-s3-using-amplify for clarification. Can you please answer there?

shopify
tag name: shopify
type: Tag
tags question: http://stackoverflow.com/q/48547677
tags question: http://stackoverflow.com/q/48567621

http://stackoverflow.com/q/48643256
tagged with: arrays
score: 16
has body: I am trying to write a very basic nearest neighbor calculation. I basically want to see what t looks like but I got this type error. When I asked the funciton to return just t it said "". When I asked it to turn to list it threw "TypeError: iteration over a 0-d array Python " How do I fix this please? ... t = np.array(map(lambda v: map(lambda w: distance(v, w, L), x_train.values), x_test.values)) ... Full trace:
downvote count: 1
upvote count: 17
possible better answer: http://stackoverflow.com/a/65158333
has answer: http://stackoverflow.com/a/48643464
accepted answer: http://stackoverflow.com/a/48643464
type: AnsweredQuestion
tagged with: typeerror
tagged with: python
has answer: http://stackoverflow.com/a/65158333
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
tagged with: iterator
has title: TypeError: iteration over a 0-d array Python

http://stackoverflow.com/comment/83985946
has text: Ok, so it because of your requirement.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48496073
type: QuestionComment

c#
tags question: http://stackoverflow.com/q/48614790
tag name: c#
type: Tag
tags question: http://stackoverflow.com/q/48515473
tags question: http://stackoverflow.com/q/48512301
tags question: http://stackoverflow.com/q/48496242

http://stackoverflow.com/q/48525338
answer count: 2
tagged with: unzip
type: UnansweredQuestion
has body: I want to create a lambda that gets a zip file(which may contain a list of csv files) from S3, unzip it and upload back to s3. since lambda is limited by memory/disk size, I have to stream it from s3 and back into it. I use python (boto3) see my code below count = 0 obj = s3.Object( bucket_name, key ) buffer = io.BytesIO(obj.get()["Body"].read()) print (buffer) z = zipfile.ZipFile(buffer) for x in z.filelist: with z.open(x) as foo2: print(sys.getsizeof(foo2)) line_counter = 0 out_buffer = io.BytesIO() for f in foo2: out_buffer.write(f) # out_buffer.writelines(f) line_counter += 1 print (line_counter) print foo2.name s3.Object( bucket_name, "output/"+foo2.name+"_output" ).upload_fileobj(out_buffer) out_buffer.close() z.close() result is, creating empty files in the bucket. for example: if file: input.zip contained files: 1.csv,2.csv i get in the bucket 2 empty csv files with the corresponding names. also, i'm not sure it indeed stream the files, or just download all the zip file thanks
has comment: http://stackoverflow.com/comment/84046922
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48528644
type: Question
tagged with: amazon-s3
has title: how to upload stream to AWS s3 with python
upvote count: 5
has answer: http://stackoverflow.com/a/62286213
has comment: http://stackoverflow.com/comment/84052684
tagged with: python
tagged with: boto3
has comment: http://stackoverflow.com/comment/110158591
score: 4
tagged with: lambda

http://stackoverflow.com/q/48553222
has title: python opening .txt error file an integer is required (got type str)
has comment: http://stackoverflow.com/comment/84102955
has comment: http://stackoverflow.com/comment/84103013
linked to: http://stackoverflow.com/q/47738537
has comment: http://stackoverflow.com/comment/84103063
has comment: http://stackoverflow.com/comment/84103026
score: 0
has comment: http://stackoverflow.com/comment/84103016
has body: I've never used from os import * So this duplicate suggestion is not valid. Please look at the code in the description. I'm not sure why I am running into this error. I thought it would be a simple with open() method but it isn't working. I have a .txt file that I'm trying to open and I'm getting this error. I'm not sure why it is asking for a integer vs a string to open a .txt file import os import spacy import en_core_web_sm import plac from collections import Counter from __future__ import unicode_literals file = 'spacy_sample.txt' with open(file, 'r' )as f: '''Do something''' TypeError Traceback (most recent call last) &lt;ipython-input-198-b6441a57e84e&gt; in &lt;module&gt;() ----&gt; 1 with open(file, 'r' )as f: 2 print(f) TypeError: an integer is required (got type str)
answer count: 0
has comment: http://stackoverflow.com/comment/84102923
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84102904
has comment: http://stackoverflow.com/comment/84103104
type: Question
has comment: http://stackoverflow.com/comment/84102982
linked to: http://stackoverflow.com/q/1046656
tagged with: python
has comment: http://stackoverflow.com/comment/84103184

http://stackoverflow.com/comment/84186063
comment on: http://stackoverflow.com/a/48594464
has text: In virtualbox also, you should go with virtualenv. It helps a lot in future. And after some time you will feel it is trivial.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84169238
type: AnswerComment
has text: Thank you, now i undestand it. I didn't know that I have to use 'data'. I will simply use the separate list with the data.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48574345

http://stackoverflow.com/comment/84283290
comment on: http://stackoverflow.com/q/48643212
score: 1
type: Comment
type: QuestionComment
has text: So to be clear on what i am proposing: do not ever touch the site-packages dir (probably overwritten at next install). Keep your sklearn sources somewhere, modify, install using setup.py. This boils down on being able to install sklearn from sources.

http://stackoverflow.com/comment/84199114
type: AnswerComment
has text: @Mephy Untestet!! Could you please test and report?
type: Comment
comment on: http://stackoverflow.com/a/48601213
score: 0

http://stackoverflow.com/comment/84236727
type: Comment
type: AnswerComment
has text: Thanks, it works.But if i want to click it more than one time. likes this: `for i in range(5): wait = WebDriverWait(driver,10) wait.until(EC.element_to_be_clickable((By.ID,'getMoreArticles'))).click()` The same will be returned for the third and fourth time, or the twice and the third, anyway, there is a problem. Besides, i don't want to use `time.sleep()`, it is unstable, and slow.
comment on: http://stackoverflow.com/a/48618850
score: 0

http://stackoverflow.com/comment/84226211
has text: I should mention that the error occurs at the last line: df['PRICE'] = df.apply(interpolate_fwd_price, fx=data, axis=1)
type: QuestionComment
comment on: http://stackoverflow.com/q/48614440
score: 0
type: Comment

http://stackoverflow.com/a/48561743
type: Answer
answers question: http://stackoverflow.com/q/48558714
score: 0
type: AcceptedAnswer
has body: I created a single python program which will do this task successfully. import xlrd from xlwt import Workbook data = [] head = [] mergedlist = [] path = "E:/Sreeraj/Thailand/" file = "1. Ban Kong Niam" text = path + file + ".txt" excel = path + file + ".xls" with open(text) as f: for cnt, line in enumerate(f): if cnt &lt; 12: mergedlist.append(line) with open(text) as f: for line in f: data.append([word for word in line.split("\t") if word]) mergedlist = head + data import xlwt wb = xlwt.Workbook() sheet = wb.add_sheet("New Sheet") for row_index in range(len(mergedlist)): for col_index in range(len(mergedlist[row_index])): sheet.write(row_index, col_index, mergedlist[row_index][col_index]) wb.save(excel) Thus, using the above python program which I wrote, I can perfectly get the excel file output as given below. Created 30/01/2018 18:28 by Windographer 4.0.26 Latitude = N 9.601639 Longitude = E 98.476861 Elevation = 0 m Calm threshold = 0 m/s Included flags: &lt;Unflagged data&gt; Excluded flags: Invalid Time stamps indicate the beginning of the time step. Date/Time Ban Kong Niam [m/s] 2008-06-01 00:00 9999 2008-06-01 01:00 9999 2008-06-01 02:00 9999 2008-06-01 03:00 9999 2008-06-01 04:00 9999 2008-06-01 05:00 9999 2008-06-01 06:00 9999 2008-06-01 07:00 9999 2008-06-01 08:00 9999
accepted answer of: http://stackoverflow.com/q/48558714

http://stackoverflow.com/comment/83979594
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48493129
has text: @StephenRauch The solution in https://stackoverflow.com/questions/1456373/two-way-reverse-map does not have a memory-efficient requirement.
score: 0

http://stackoverflow.com/comment/84037231
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48521360
type: QuestionComment
has text: Do you think `df.fillna(14.56)` - `df.fillna(df['close'].iat[-1])` ?

http://stackoverflow.com/a/48536000
type: Answer
has comment: http://stackoverflow.com/comment/84173420
has comment: http://stackoverflow.com/comment/84067310
has comment: http://stackoverflow.com/comment/84067335
has comment: http://stackoverflow.com/comment/84067428
score: 0
has comment: http://stackoverflow.com/comment/84073287
has comment: http://stackoverflow.com/comment/84067289
has body: Use scipy.spatial.cdist. This will calculate the pairwise distance. Thanks to Warren Weckesser for pointing out this solution.
has comment: http://stackoverflow.com/comment/84154119
has comment: http://stackoverflow.com/comment/84070752
answers question: http://stackoverflow.com/q/48535829

http://stackoverflow.com/comment/84120177
type: Comment
score: 2
type: QuestionComment
has text: The problem is that your `y` values are strings -- try converting them to floats before plotting.
comment on: http://stackoverflow.com/q/48562308

http://stackoverflow.com/a/48508101
has body: which seems to me that keep_prob has to be greater than 1 otherwise nothing would be dropped! The description says: With probability keep_prob, outputs the input element scaled up by 1 / keep_prob, otherwise outputs 0. The scaling is so that the expected sum is unchanged. This means that: keep_prob is used as a probability, so by definition it should always be in [0, 1] (a number outside that range can never be a probability) With probability keep_prob, input elements are multiplied by 1 / keep_prob. Since we've just written that 0 &lt;= keep_prob &lt;= 1, the division 1 / keep_prob is always going to be greater than 1.0 (or exactly 1.0 if keep_prob == 1). So, with probability keep_prob, some elements are going to become bigger than they were without dropout With probability 1 - keep_prob (the "otherwise" in the description), elements are set to 0. This is the dropout, elements are dropped if they got set to 0. If you set keep_prob to exactly 1.0, this means the probability of dropping any node becomes 0. So, if you want to drop some nodes, you should set keep_prob &lt; 1, and if you don't want to drop anything, you set keep_prob = 1. Important note: You only want to use dropout during training, not during testing. If I use a number in range (0,1] for dropout_keep_prob in the sess.run, the accuracy drops drastically. If you do this for the test set, or if you mean you're reporting accuracy on the training set, that doesn't surprise me. Dropout means losing information, so it is indeed going to lose accuracy. It's supposed to be a way of regularizing though; you intentionally lose accuracy during the training phase, but hope this results in improved generalization and therefore improved accuracy during the test phase (when you should no longer be using dropout). If I use a number bigger than 1, like 4, the accuracy goes beyond 0.9. I'm surprised you get this code to run at all. Based on the source code, I wouldn't expect it to run?
type: Answer
has comment: http://stackoverflow.com/comment/84016249
has comment: http://stackoverflow.com/comment/84106426
accepted answer of: http://stackoverflow.com/q/48507778
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84031466
has comment: http://stackoverflow.com/comment/84114688
answers question: http://stackoverflow.com/q/48507778
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/48577171
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48577136
upvote count: 2
downvote count: 0
has body: Use a dictionary to store the values and access by key. def return_value(key): return {'sathya': -5,'varna': -4,'summi': 'any value..'}[key]

http://stackoverflow.com/q/48643441
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84284468
answer count: 1
has answer: http://stackoverflow.com/a/48663328
has title: python 2.7 - csv file pull data from 2 columns
has comment: http://stackoverflow.com/comment/84288728
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84287030
has body: So I have a csv file and I need to find only the specific lines that match a criteria and then count how many occurrences of those lines are. Example file: col1 col2 col3 david1 david2 david3 david4 david1 sev5 david1 sev5 david1 sev4 david2 sev5 david2 sev1 david3 sev5 david3 sev2 david3 sev2 david4 sev1 The desired info I need is to only find lines that match for example: david1 : sev5 david1 : sev4 david3 : sev2 And then give me a total of how many it has found. I've searched around using dictionaries and lists but for some reason I just don't understand how they could skip over certain sections of the file and then count specific lines that match a search. I very much still have my 'L' plates on python and some kind help would be appreciated. Thanks
tagged with: python
has comment: http://stackoverflow.com/comment/84287128
has comment: http://stackoverflow.com/comment/84284499
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84289970

http://stackoverflow.com/q/48611191
type: UnansweredQuestion
has body: I am using ajax to call the following URL: "https://www.bittrex.com/api/v1.1/public/getticker?market=usdt-btc" I am getting the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have installed django-cors-headers and my settings.py looks like this: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'crispy_forms', # The following apps are required: 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1:8000', ) Why am I still getting the error? I have read all the other answers related to this but they have not helped me. I have used the Chrome plugin too and it does work with it but I want a solution without it. Django Version = 1.8
tagged with: django
tagged with: ajax
score: 0
has answer: http://stackoverflow.com/a/48611780
tagged with: http-headers
tagged with: python
has title: Message received is "No 'Access-Control-Allow-Origin' header is present on the requested resource"
type: Question
has answer: http://stackoverflow.com/a/48611701
answer count: 2

http://stackoverflow.com/a/48743473
has comment: http://stackoverflow.com/comment/84487910
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/48643963
has comment: http://stackoverflow.com/comment/84487319
has comment: http://stackoverflow.com/comment/84487135
answers question: http://stackoverflow.com/q/48643963
has comment: http://stackoverflow.com/comment/84490142
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84490242
has comment: http://stackoverflow.com/comment/84489462
has body: Nice attempt with your approach. Firstly, if possible consider using group ids instead of group names to identify managers. Will dramatically improve query performance and spelling related bugs. Following is a quick snippet that I tried and is working for me. (on postgres). User.objects.prefetch_related("groups").annotate( is_super=Case( When( groups__id__in=[1, 2,3 ], then=1 ), default=0, output_field=IntegerField() ) ).order_by("id").values_list("id", "username", "is_super")
has comment: http://stackoverflow.com/comment/84490337

http://stackoverflow.com/comment/84012711
comment on: http://stackoverflow.com/q/48508702
has text: use an array. `images = []; ...; images.append(mi)`
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/84063226
type: AnswerComment
comment on: http://stackoverflow.com/a/48531038
type: Comment
has text: Well ive gotten further, check the new code and output file. thank you so much for your help
score: 0

http://stackoverflow.com/a/48602737
accepted answer of: http://stackoverflow.com/q/48602589
answers question: http://stackoverflow.com/q/48602589
type: Answer
has body: You are expecting this (\((\d{3})\)\s*|(\d{3})-?) to return 123 but you have two pairs of grouping parentheses -- one beginning at the start and the other beginning before \d, and so you get two groups returned. If you don't want the (123) but you do want the 123 then the outer pair needs to be non-capturing: (?:\((\d{3})\)\s*|(\d{3})-?) That only solves one part of your problem. The other is that your third capturing group, that does not match anything, returns None. That can't be easily solved in the regular expression itself because for every pair of grouping parentheses in your regular expression you get something back from match.groups(). That is how groups() is defined. Consider using filter(): &gt;&gt;&gt; regex = re.compile(r"(?:\((\d{3})\)\s*|(\d{3})-?)") &gt;&gt;&gt; regex.match('(123) ').groups() ('123', None) &gt;&gt;&gt; tuple(filter(None, regex.match('(123) ').groups())) ('123',)
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84201827
type: Comment
type: AnswerComment
has text: Whenever you have a data that you need to split on a separator(be it and or comma or colon...), you are essentially looking at a string which can be split
score: 0
comment on: http://stackoverflow.com/a/48602460

http://stackoverflow.com/q/48612077
score: 3
has comment: http://stackoverflow.com/comment/84224279
tagged with: math
tagged with: database
tagged with: python
has comment: http://stackoverflow.com/comment/84224320
has title: Conditionally multiply list python
accepted answer: http://stackoverflow.com/a/48612121
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48612121
has body: I have to multiply a list (a) with one of two other lists (b and c), but conditional on if the value in (a) is positive or negative. I do have a working solution, but it is quite slow and I would like to speed it up significantly. I believe this code in R is what I need, but don't know of a similar approach in Python. EDIT: I have applied Moinuddin Quadri's method: amount = [0,1,0,0,-1,0,1,-1,1] data1 = [10,11,12,13,14,15,16,15,14] data2 = [3,1,2,3,4,5,6,5,4] flow2 = [(i*j if i &gt; 0 else i*k) for i, j, k in zip(amount, data1, data2)] 100000 loops, best of 3: 2.35 µs per loop Whereas my own attempt: amount = [0,1,0,0,-1,0,1,-1,1] data1 = [10,11,12,13,14,15,16,15,14] data2 = [3,1,2,3,4,5,6,5,4] flow = [0]*len(data1) for i in range(len(data1)): if amount[i] &gt; 0: flow[i] = amount[i]*data1[i] else: flow[i] = amount[i]*data2[i] 100000 loops, best of 3: 2.97 µs per loop. So it is a slight improvement, but not huge. I have to iteratively perform this task, many times and need significant improvement...
upvote count: 3
linked to: http://stackoverflow.com/q/26738551
possible better answer: http://stackoverflow.com/a/48612387
downvote count: 0
has answer: http://stackoverflow.com/a/48612387
has comment: http://stackoverflow.com/comment/84221485
has comment: http://stackoverflow.com/comment/84220661
favorite count: 0
has comment: http://stackoverflow.com/comment/84220732
has comment: http://stackoverflow.com/comment/84220717
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84220809

http://stackoverflow.com/comment/84059508
comment on: http://stackoverflow.com/q/48531882
has text: @wim yeah that would make more sense.
type: Comment
type: QuestionComment
score: 0

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

http://stackoverflow.com/q/48621833
favorite count: 0
has comment: http://stackoverflow.com/comment/84240286
has comment: http://stackoverflow.com/comment/84240876
type: Question
has comment: http://stackoverflow.com/comment/84240056
has answer: http://stackoverflow.com/a/48622266
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84258252
has comment: http://stackoverflow.com/comment/84240177
has comment: http://stackoverflow.com/comment/84240114
upvote count: 3
score: 3
answer count: 1
has comment: http://stackoverflow.com/comment/84241517
downvote count: 0
tagged with: machine-learning
has body: Hello! I am using Keras for first time. I trained and saved a model. (as a json file and its weights too) The model it is intended to classify an image among 3 classes. My compile method : model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) After that, I load the model and its weights and i try to make a prediction for a random image # Predicting images img =image.load_img('/path/to/image/index.jpeg', target_size=(224, 224)) x = image.img_to_array(img) #normilize the array output x *= (255.0/x.max()) image = np.expand_dims(x, axis = 0) image = preprocess(image) preds = loaded_model.predict(image,) pred_classes = np.argmax(preds) print(preds) print(pred_classes) How to i get a list with the probabilities? For example [75% 15% 10%] Currently i get as an output 5.571262e-21 0.000000e+00 1.000000e+00 2 This is the model summary print(loaded_model.summary()) Model successfully loaded from disk! _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 222, 222, 64) 1792 _________________________________________________________________ activation_1 (Activation) (None, 222, 222, 64) 0 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 111, 111, 64) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 109, 109, 64) 36928 _________________________________________________________________ activation_2 (Activation) (None, 109, 109, 64) 0 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 54, 54, 64) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 52, 52, 128) 73856 _________________________________________________________________ activation_3 (Activation) (None, 52, 52, 128) 0 _________________________________________________…
tagged with: keras
has title: model.predict() returns classes and not probabilities

http://stackoverflow.com/comment/84062953
type: AnswerComment
comment on: http://stackoverflow.com/a/48533673
score: 0
type: Comment
has text: Great explanation of a very common corner case in tuple construction.

http://stackoverflow.com/q/48616339
has body: I'm making a blog feature on a website and I want to allow the User to edit the text of the post without taking them to a different view. Just like you can edit a post on Facebook, or on Stack. This is just the piece of code containing the form. {% if user.is_authenticated %} {% csrf_token %} {{ form.as_p }} Save {% endif %} I'm not sure where to go from here, in my mind when the button is clicked, I should have some HTML that appears and replaces the HTML that was displaying just the text. The new editable text would be a model that is created by and passed from a view right?
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Allow user to edit a blog post live with Django
has comment: http://stackoverflow.com/comment/84232577
has comment: http://stackoverflow.com/comment/84268447
score: 0
has comment: http://stackoverflow.com/comment/84257940
answer count: 0
has comment: http://stackoverflow.com/comment/84229568
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/84258419

http://stackoverflow.com/q/48633861
downvote count: 0
linked to: http://stackoverflow.com/q/30248128
has answer: http://stackoverflow.com/a/48634051
has answer: http://stackoverflow.com/a/48633948
favorite count: 0
has body: I want to import this .txt file, but due to the space between "No" and "Record", pandas is importing them as separate columns. How can I have varying seps? Regex? data = pd.read_table('file.txt', sep=' ', header=None) Data 01/01/1933 NO RECORD NO RECORD MISSING MISSING 01/02/1933 NO RECORD NO RECORD MISSING MISSING 01/03/1933 NO RECORD NO RECORD MISSING MISSING 01/04/1933 NO RECORD NO RECORD MISSING MISSING 01/05/1933 NO RECORD NO RECORD MISSING MISSING 01/06/1933 NO RECORD NO RECORD MISSING MISSING 01/07/1933 NO RECORD NO RECORD 368.00 MISSING 01/08/1933 NO RECORD NO RECORD MISSING MISSING 01/09/1933 NO RECORD NO RECORD MISSING MISSING 01/10/1933 NO RECORD NO RECORD MISSING MISSING 01/11/1933 NO RECORD NO RECORD MISSING MISSING Current import ** 0 1 2 3 4 5 0 01/01/1933\tNO RECORD \tNO RECORD \tMISSING \tMISSING 1 01/02/1933\tNO RECORD \tNO RECORD \tMISSING \tMISSING 2 01/03/1933\tNO RECORD \tNO RECORD \tMISSING \tMISSING 3 01/04/1933\tNO RECORD \tNO RECORD \tMISSING \tMISSING 4 01/05/1933\tNO RECORD \tNO RECORD \tMISSING \tMISSING**
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48634051
has comment: http://stackoverflow.com/comment/84264775
has comment: http://stackoverflow.com/comment/84264867
tagged with: pandas
has comment: http://stackoverflow.com/comment/84264774
has comment: http://stackoverflow.com/comment/84264738
has title: What can I import a text file with varying space separators?
tagged with: python
accepted answer: http://stackoverflow.com/a/48633948
type: Question
upvote count: 2
answer count: 2

resolution
tag name: resolution
tags question: http://stackoverflow.com/q/48639369
type: Tag

http://stackoverflow.com/q/48507025
linked to: http://stackoverflow.com/q/20935151
has title: Decode HTML from pandas column
has answer: http://stackoverflow.com/a/48510326
favorite count: 0
type: Question
tagged with: decode
has comment: http://stackoverflow.com/comment/84009280
upvote count: 2
has comment: http://stackoverflow.com/comment/84009345
has comment: http://stackoverflow.com/comment/84009606
tagged with: encode
has body: I have a data frame where one of the columns is the currency name in spanish fos US Dolares which is Dólares But its encoded on HTML so i actually read '&oacute;' and i cant find any way to decode this for whole column. This is a problem cause i need to export to .csv after and this causes trouble. I tried with different encoding/decoding libraries like beautifulsoup, HTMLParser and a couple more. Any idea what could be the problem?
has comment: http://stackoverflow.com/comment/84008589
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48510326
tagged with: python
has comment: http://stackoverflow.com/comment/84008561
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84009506
tagged with: pandas
has comment: http://stackoverflow.com/comment/84008840
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/84008911

http://stackoverflow.com/comment/84274065
comment on: http://stackoverflow.com/q/48578304
has text: That was the issue Sergeyol, it was to windows auth, while it should have been otherwise.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/100338958
score: 0
type: AnswerComment
has text: You have to add here appropriate imports of BaseEstimator and TransformerMixin.
type: Comment
comment on: http://stackoverflow.com/a/56326816

http://stackoverflow.com/comment/84214109
type: QuestionComment
comment on: http://stackoverflow.com/q/48608845
score: 0
has text: Too broad? If you have multiple questions, ask multiple questions.
type: Comment

http://stackoverflow.com/comment/84052241
comment on: http://stackoverflow.com/q/48528537
type: Comment
has text: You can probably get unstuck by looking at the [zip](https://docs.python.org/3/library/functions.html#zip) function
type: QuestionComment
score: 0

http://stackoverflow.com/q/48607860
has comment: http://stackoverflow.com/comment/84222784
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84216672
has title: How do I make scipy IQR use the difference of the medians of two halves of the array?
answer count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/84222108
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48615167
has body: I'm trying to work out the IQR of some numbers using scipy's iqr() function. However, when I work this out myself I get a different result to IQR, and I think it's because it's not working it out based on the medians. I've looked at the documentation but can't see anything there. For example, I have this list: list1 = [7.4, 7.9, 4.1, 8.1, 6.2, 7.1, 7.4, 6.7] If I work out the IQR myself by taking the medians from the upper and lower halves I get 1.2. If I use iqr(list1) I get 0.95. In this specific case I tried iqr(list1, interpolation='midpoint') which gave me the correct answer. However, I have this second list: list2 = [5, 7, 2, 1, 3, 4, 8, 8, 6, 6] and did iqr(list2, interpolation='midpoint') but it gave me 3.0 as the answer however I've worked it out to be 4.0. This was a multiple choice question on an online test I was doing, whether I worked it out right or wrong doesn't matter because 3.0 was not an available answer. I get the same results as IQR() if I work out the IQR doing 75% - 25%, which is not the same as the upper and lower medians. Is there a parameter I have missed or one I can change in IQR to get a consistent answer?
has answer: http://stackoverflow.com/a/48615167

http://stackoverflow.com/a/48602525
upvote count: 5
has body: You can use itertools.groupby with regular expressions: import itertools import re s = ['1(Reg)', '100', '103', '102', '100', '2(Reg)', '98', '101', '100', '3(Reg)', '96', '99', '98', '4(Reg)', '100', '100', '100', '100', '5(Reg)', '98', '99', '99', '100', '6(Reg)', '99.47', '99.86', '99.67', '100'] new_data = [list(b) for _, b in itertools.groupby(s, key=lambda x:bool(re.findall('\d+\(', x)))] final_data = [new_data[i]+new_data[i+1] for i in range(0, len(new_data), 2)] Output: [['1(Reg)', '100', '103', '102', '100'], ['2(Reg)', '98', '101', '100'], ['3(Reg)', '96', '99', '98'], ['4(Reg)', '100', '100', '100', '100'], ['5(Reg)', '98', '99', '99', '100'], ['6(Reg)', '99.47', '99.86', '99.67', '100']]
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48602472
score: 5

http://stackoverflow.com/comment/85020327
has text: Thanks, but which one is the standard QR code library? The one that you linked has no ECI support. Actually I needed a Delphi QRCode generator, which I have hacked to append `0111 00000100` as a header, which translates to ECI 4 :)
comment on: http://stackoverflow.com/q/48492274
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/98222850
comment on: http://stackoverflow.com/a/55745418
has text: @obscure can you please clarify. Is my answering style wrong , or what I have mentioned in the answer is wrong ?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48591751
type: Answer
has body: take the help of regression functions import re students = [re.sub(',', '', re.findall('[\d,]+', str(i))[0]) for i in soup.select('.pr-xs')] this will give you the result as ['1184500','697000','167500','145500','81000','172000']
score: 0
answers question: http://stackoverflow.com/q/48591624
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48591624

http://stackoverflow.com/comment/84281394
type: Comment
type: QuestionComment
has text: just a string with a csv
comment on: http://stackoverflow.com/q/48641924
score: 1

http://stackoverflow.com/a/48511004
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48510066
score: 3
type: Answer
has body: I think this is a logic error but I can't test specifically to be sure. Your query is currently: cur.execute("SELECT * FROM birthdays WHERE year=year OR month=month;") row = cur.fetchone() There's two issues with this: You used fetchone() instead of fetchall() so it's clear that you'll only ever get one result; that's what you asked for. Your query is just a simple string. You haven't actually passed any arguments to your function into the query. Every row has a value in year that is equal to that value in year (you're asking each value to compare itself to itself) meaning your query is always True for all rows (so you'll pull the whole database). Caveat: There may be NaN-type values where this is not true, but on-the-whole it is. Try: cur.execute("SELECT * FROM birthdays WHERE year=%s OR month=%s;", (year, month)) row = cur.fetchone() You may need to enclose the %s placeholders in quotation marks, I can't test and don't know your database setup. This is a parameterized query, where year and month are dynamic based on the values passed to the function. You could do this through string formatting (you'll see a lot of people doing this in questions here) but that really exposes you to SQL injection: remember Bobby Tables.

time-series
tags question: http://stackoverflow.com/q/48573715
tags question: http://stackoverflow.com/q/48510229
tags question: http://stackoverflow.com/q/48562123
tags question: http://stackoverflow.com/q/48627109
tags question: http://stackoverflow.com/q/48618462
type: Tag
tags question: http://stackoverflow.com/q/48515334
tags question: http://stackoverflow.com/q/48611534
tag name: time-series
tags question: http://stackoverflow.com/q/48570021
tags question: http://stackoverflow.com/q/48576286
tags question: http://stackoverflow.com/q/48558085
tags question: http://stackoverflow.com/q/48517719
tags question: http://stackoverflow.com/q/48556510
tags question: http://stackoverflow.com/q/48625279
tags question: http://stackoverflow.com/q/48556767

http://stackoverflow.com/comment/84076229
comment on: http://stackoverflow.com/q/48538404
score: 1
type: QuestionComment
has text: Also, your code skips one line only (`tf.TextLineReader(skip_header_lines=1)`), but the file you link to has a lot more header lines. That is probably the source of your error.
type: Comment

http://stackoverflow.com/comment/84054715
type: QuestionComment
has text: Sorry, I just updated it. I don't want to append the classifier I just want to append the number that corresponding to range that I want as you can see in the sheet I provide as an example.
score: 0
comment on: http://stackoverflow.com/q/48529664
type: Comment

http://stackoverflow.com/comment/84095243
has text: Great lead! Thanks for the response. I'm not attached to the data at all. What is the best way to reset a database in django? I'm guessing I'll first go and drop the database in postgreSQL, but then do I need to delete the migrations for the apps too?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48549498
type: Comment

http://stackoverflow.com/a/48554568
has body: singledispatch might be an answer, which transforms a function into a generic function, which can have different behaviors depending upon the type of its first argument. You could see a concrete example in the above link. And you should do some special things if you want to do generic dispatch on more than one arguments.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48553981

http://stackoverflow.com/comment/84127675
type: Comment
has text: I was blown away by yours.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48565531

http://stackoverflow.com/comment/84023341
type: QuestionComment
has text: Yes, I checked that. But the problem exist as well
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48498595

http://stackoverflow.com/comment/84174762
has text: A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](//stackoverflow.com/help/deleted-answers)
comment on: http://stackoverflow.com/a/48588664
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84125183
score: 0
comment on: http://stackoverflow.com/q/48563133
type: Comment
type: QuestionComment
has text: that task you do not have to do in the code of the model. How do you enter the data? Do you have a form?, you have to create a function where you get the selected cells and use the function setData(), you should not overwrite the setData() method. You have a design problem, if you want us to help you, you must provide a [mcve] of your background problem. I stress, you should not modify the setData method to perform that task.

http://stackoverflow.com/comment/84075961
has text: Is the navbar hardcoded in each page, or do you have it in some sort of template?
score: 0
comment on: http://stackoverflow.com/q/48540319
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48582148
tagged with: django-testing
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84161107
type: Question
has comment: http://stackoverflow.com/comment/84161274
has answer: http://stackoverflow.com/a/48664931
tagged with: django-models
tagged with: python
has title: In Django test there is empty queryset when assigned to variable but not empty when printed in console during debug
has comment: http://stackoverflow.com/comment/84161387
tagged with: automated-tests
has body: I'm debugging Django (1.11.8) test and observing strange behavior, when stopped in debugger and switched to Ipython console typing: Model.objects.all() returns non-empty Queryset. However, when the same expressions is assigned to variable e.g.: obj_qs = Model.objects.all() then obj_qs is empty Queryset. I would expect the same result from both statements. Am I missing something important in tests setup? I'm using both setUpTestData() and setUp() methods to initialize objects for the test.
downvote count: 0
tagged with: django
type: UnansweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/48597947
accepted answer: http://stackoverflow.com/a/48597969
upvote count: 2
tagged with: pandas
score: 1
answer count: 1
downvote count: 1
has title: How to convert string of different format(YYYY-MM-DD, DD-MM-YYYY) to date object of one format in pandas?
has answer: http://stackoverflow.com/a/48597969
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python
tagged with: date
has body: I have a column of string object where it contains different format(YYYY-MM-DD, DD-MM-YYYY). How to convert to DD-MM-YYYY of date object. I tried with, df['accepted_date'] = pd.to_datetime(df['accepted_date'], format='%d-%m-%Y') I got error as time data '1899-12-31' does not match format '%d-%m-%Y' (match) Thanks,

http://stackoverflow.com/comment/84199814
type: AnswerComment
comment on: http://stackoverflow.com/a/48600555
score: 0
has text: And if you want to conserve ints and floats what? This is not a good idea in this case.
type: Comment

http://stackoverflow.com/q/48591898
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84181162
has title: model_unpickle() takes exactly 3 arguments (1 given)
tagged with: python-2.7
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84181155
has body: I'm facing this error bellow with celery 3.1.25 and 4.1.0, this happen if I set serializing with pickle (I know is a problem with security) but I use a library that needs this kind of serialization to work with files, anyone have solved this problem?. Will add my freeze at the bottom of the question. Thank you Can't decode message body: DecodeError(TypeError('model_unpickle() takes exactly 3 arguments (1 given)', , (('data_importer', 'FileHistory'),)),) [type:u'application/x-python-serialize' encoding:u'binary' headers:{u'origin': u'gen29@f6876eb537fc', u'lang': u'py', u'task': u'data_importer_task', u'group': None, u'root_id': u'655b3b91-b48e-41c3-a893-ab7b5bdfdf79', u'expires': None, u'retries': 0, u'timelimit': [3600, None], u'argsrepr': u'()', u'eta': None, u'parent_id': None, u'id': u'655b3b91-b48e-41c3-a893-ab7b5bdfdf79', u'kwargsrepr': u"{'source': , 'importer': , 'file': , 'owner': >, 'subproject': , 'action': 'u'}"}] body: '\x80\x02)}q\x01(U\x06sourceq\x02cdjango.db.models.base\nmodel_unpickle\nq\x03U\rdata_importerq\x04U\x0bFileHistoryq\x05\x86\x85Rq\x06}q\x07(U\x06statusq\x08K\x01U\x0bfile_uploadq\tXI\x00\x00\x00upload_history/map_su/2018/02/02/7bee4c1c-751c-44df-a318-d527916148f5.xlsU\x0fcontent_type_idq\nK\x17U\x0f_django_versionq\x0bU\x061.11.9U\ncreated_atq\x0ccdatetime\ndatetime\nq\rU\n\x07\xe2\x02\x02\x16\x188\x00\r\xd7cpytz\n_UTC\nq\x0e)Rq\x0f\x86Rq\x10U\x06_stateq\x11cdjango.db.models.base\nModelState\nq\x12)\x81q\x13}q\x14(U\x06addingq\x15\x89U\x02dbq\x16U\x07defaultq\x17ubU\nupdated_atq\x18h\rU\n\x07\xe2\x02\x02\x16\x188\x00\r\xf4h\x0f\x86Rq\x19U\tobject_idq\x1aNU\x07is_taskq\x1bK\x00U\x13_content_type_cacheh\x03U\x0ccontenttypesq\x1cU\x0bContentTypeq\x1d\x86\x85Rq\x1e}q\x1f(h\x0bU\x061.11.9U\x05modelq X... (220389b) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/kombu/messaging.py", line 592, in _receive_callback decoded = None if on_m else message.decode() File "/usr/local/lib/python2.7/dist-packages/kombu/mess…
type: Question
tagged with: serialization
has answer: http://stackoverflow.com/a/60185770

http://stackoverflow.com/q/48574963
tagged with: python
possible better answer: http://stackoverflow.com/a/48576394
has answer: http://stackoverflow.com/a/48576394
tagged with: format
tagged with: pandas
type: AnsweredQuestion
score: 0
has body: I have a DataFrame with some float numbers, i.e.: Date Value Sep-1 1.2 Sep-2 2.34 Sep-3 10.453 I hope if I could write the DataFrame to a text file with following format: Date Value Sep-1 0001.200 Sep-2 0002.340 Sep-3 0010.453 I tried float_foramt='%4.3f' but it doesn't work.
has title: pandas float output format? (pd.to_csv)
type: Question
accepted answer: http://stackoverflow.com/a/48575001
answer count: 2
has answer: http://stackoverflow.com/a/48575001

http://stackoverflow.com/comment/84357975
type: AnswerComment
type: Comment
has text: I thought about `tee` while thinking of your problem. It, however, will lead to the same issues as all other soluitons. It may change the order of your streams. The stdou and stderr are independent streams. Redirecting them to the same stream does not give a fixed ordering, but depends on the current state of the OS and its other operations. Adding `tee`to the mix, may change this order and is therefore not guaranteed to give the same result. However, if you have intrinsic knowledge of the orders of `stdout` and `stderr` this can be incorporated into a working solution with or without `tee`.
comment on: http://stackoverflow.com/a/48675904
score: 0

http://stackoverflow.com/a/48632402
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/84262245
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48632305
type: Answer
answers question: http://stackoverflow.com/q/48632305
has body: You can use flask, a simple Python web framework, to serve the string: Using flask (pip install flask): import flask app = flask.Flask(__name__) s = """ Home Welcome! """ @app.route('/') def home(): return s if __name__ == '__main__': app.debug = True app.run() Now, can you navigate to 127:0.0.1:5000 or the equivalent IP and port specified when the app is run.
has comment: http://stackoverflow.com/comment/84262314

http://stackoverflow.com/comment/84138011
type: Comment
type: QuestionComment
has text: You can find the rows causing the problem with `print(df.loc[(df >= 100).any(axis=1)])`. And you could filter out those rows by assigning `df = df.loc[(df < 100).any(axis=1)]`.
score: 0
comment on: http://stackoverflow.com/q/48570596

http://stackoverflow.com/q/48600153
tagged with: numpy
has title: Python: use dict and list of tuples to create a numpy array
accepted answer: http://stackoverflow.com/a/48600191
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has body: I have five key/value pairs in a python dict object: dict1 = {0:3, 1:2, 2:2, 3:2, 4:3} And I have a list of tuples: list_of_tuples = [(0, 1), (0, 4), (2, 3)] I want a numpy array of shape (5, 5, 2) that contains the value from the dict object for each tuple value. I get 5 from the number of keys in the dict object, and 2 from the number of values in each tuple. That is: at position (0, 1) of the numpy array, I want a numpy array with values (3, 2); at position (0, 4) of the numpy array, I want a numpy array with values (3, 3); at position (2, 3) of the numpy array, I want a numpy array with values (2, 2); at all other positions of the numpy array, I want a numpy array with values (4, 4), where I use (4, 4) as an indicator of an empty spot. Is there a nice, Pythonic way of doing this?
answer count: 1
has answer: http://stackoverflow.com/a/48600191
type: Question
has comment: http://stackoverflow.com/comment/84197280

http://stackoverflow.com/comment/84202129
type: Comment
score: 3
type: QuestionComment
has text: Is it enough to count how many, or do you want the actual combinations as well?
comment on: http://stackoverflow.com/q/48602709

http://stackoverflow.com/comment/84077773
has text: That doesn't write the df to the new csv the way I want it to. Anyway writing the df isn't the problem, it's trying to insert a new column at the beginning of the df called 'label' which has a value of 1 or 0 depending on what the filename contains.
score: 0
comment on: http://stackoverflow.com/a/48541205
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48540759
has title: Add variable value to read file in Python
type: AnsweredQuestion
tagged with: file
downvote count: 0
score: 1
upvote count: 1
tagged with: variables
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48541016
tagged with: python
has comment: http://stackoverflow.com/comment/84076751
has comment: http://stackoverflow.com/comment/84076825
has answer: http://stackoverflow.com/a/48541016
has body: I have a question regarding adding variable value to text that is read from file. My situation is that I would like to have separate html file with variables that would pull value from code. Example of .txt file: """Current value of variable x is: """ + str(x) + """ and so on.""" Code that I have tried, is: x = 5 f = open("C:\\Test\\reading.txt",'r') print(f.read()) What I would like to finish with is: """Current value of variable x is: 5 and so on.""" Reason why I would like to have it is to have separate html file, generate html code from it in combination with variable values and than use that string further for sending email. Worst case, I can embed html code into code where I calculate variable values, but would be more handy to keep them separated.

http://stackoverflow.com/comment/84057285
type: Comment
type: QuestionComment
score: 0
has text: Doesn't that line have an *EOLN* (`\n`, *0X0A*) at the end?
comment on: http://stackoverflow.com/q/48530848

http://stackoverflow.com/a/48514465
downvote count: 0
has comment: http://stackoverflow.com/comment/84023636
score: 1
upvote count: 1
has body: You need to identify the bottlenecks in your code and then figure out how to reduce them. It's difficult to help you with the minimal amount of code that you have provided, but the most likely cause is that each HTTP request takes most of the time, and the parsing is probably negligible in comparison. See if you can figure out a way to paralleise the HTTP requests, e.g. using the multiprocessing or threading modules.
type: Answer
answers question: http://stackoverflow.com/q/48514389

http://stackoverflow.com/comment/84060366
type: QuestionComment
has text: This returns products from all categories. I have added the code from my template aswell.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48532194

http://stackoverflow.com/comment/84165555
has text: So you want to video to start when you open the tool? Why not just call the play function in the setupUI function?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48583776

http://stackoverflow.com/comment/84159461
type: Comment
has text: Curl actually is not an option, the only allowed way to get data from WildFly is CLI, but yeah I've managed to change symbol '=>' to ':' and get more like Json format& trying to convert it, thanks for tip.
type: QuestionComment
comment on: http://stackoverflow.com/q/48580822
score: 0

http://stackoverflow.com/comment/84200222
comment on: http://stackoverflow.com/q/48601786
has text: `data[result['id']] = temp.copy()` that'd work
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48541863
has comment: http://stackoverflow.com/comment/84081439
upvote count: 1
linked to: http://stackoverflow.com/q/38336090
has comment: http://stackoverflow.com/comment/84080521
has body: I'm trying to mock a global variable which is list type. Below is the illustration - This is first_main.py - url=[] -- The result off url.append(hello.replace(-test','')) is getting stored here which is in method_a() and this is global variable def method_a(): url.append(hello.replace(-test','')) return something Now, url=[] is used in another method. def method_b(): *Some codes and url=[] is used here in this code.* print url return True Now, I'm testing method_b - @mock.patch('first_main.url') def test_method_b(self, mock_url_list): mock_url_list.return_value.url.return_value = [['a','b'],['c','d']] reponse = method_b() print response Now, if i put a print statement for url which is getting used in method_b it should return me the [['a','b'],['c','d']] instead of id. ------------Console------------ MagicMock name='url' id='090909090' I want return_type in list ie. [['a','b'],['c','d']] instead of id. Thank You Let me know incase of clarification.
has comment: http://stackoverflow.com/comment/84079723
tagged with: unit-testing
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48547675
has comment: http://stackoverflow.com/comment/84080310
score: 1
tagged with: python-unittest
tagged with: python
has title: How to mock global variable of List Type?
answer count: 2
tagged with: mocking
has answer: http://stackoverflow.com/a/49326390
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84080707
downvote count: 0

http://stackoverflow.com/a/48558409
answers question: http://stackoverflow.com/q/48558372
downvote count: 0
upvote count: 1
type: Answer
score: 1
has body: You defined a function, not a method. That means you have to call is_empty(l) not l.is_empty()

http://stackoverflow.com/comment/84245446
type: Comment
type: QuestionComment
has text: No, it won’t. The function has already exited.
comment on: http://stackoverflow.com/q/48624364
score: 1

http://stackoverflow.com/q/48564965
upvote count: 2
has title: using __slots__ is faster than a dict, but initiation is slower, any workaround?
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: class
has body: So I am trying to have a faster creation + attribute access than a dict() so assuming a very simple class / dict you can see that __slots__ is faster/equivalent for attribute access: import timeit class A: __slots__ = ('a',) def __init__(self, a): self.a = a a = A(10) v = {'B': 10} %timeit A.a %timeit v['B'] 10000000 loops, best of 3: 28.3 ns per loop 10000000 loops, best of 3: 29 ns per loop but if you test the speed including initiation of the class / dict the results are very different : %timeit A(10).a %timeit {'B': 10}['B'] 1000000 loops, best of 3: 216 ns per loop 10000000 loops, best of 3: 58.8 ns per loop is there any way to speed up the initiation phase of the class? Why is dict() initiation so much faster? thanks!
tagged with: performance
answer count: 0
score: 2
has comment: http://stackoverflow.com/comment/84126064
downvote count: 0
tagged with: slots
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84125999
has comment: http://stackoverflow.com/comment/84126084

http://stackoverflow.com/comment/84169207
comment on: http://stackoverflow.com/a/48585825
score: 0
type: Comment
has text: Yea that would be simpler. `data` is a string so no need to convert to json object to convert back to string.
type: AnswerComment

http://stackoverflow.com/comment/84001706
type: QuestionComment
comment on: http://stackoverflow.com/q/48500283
has text: Unrelated, but there should be no need to call `iter` on the generator function `line_producer`; `next` works just fine without it.
type: Comment
score: 0

http://stackoverflow.com/a/48519221
answers question: http://stackoverflow.com/q/48518425
score: 0
type: Answer
has body: I can see couple of problems with your code and data. a. Wrong tag mathing at start of your xml file b. etree doesn't have method parse, it should be ET.parse('Matching_Result.xml) c. I thing you can do this without minidom too. This code is working for me, add encoding-decodings and check. from xml.etree import ElementTree as ET tree = ET.parse('Matching_Result.xml') root = tree.getroot() for mot in root.findall('mot'): name = mot.get('id') rank = mot.find('val').text print name , rank if name == 'abc': val= mot.find('val') val.text = 'new_val' tree.write('Matching_Result.xml') Initial Matching_Result.xml : testing Final Matching_Result.xml : testing new_val
has comment: http://stackoverflow.com/comment/84033830
has comment: http://stackoverflow.com/comment/84033866
has comment: http://stackoverflow.com/comment/84033594

http://stackoverflow.com/q/48535962
type: AnsweredQuestion
score: 0
tagged with: categorical-data
has answer: http://stackoverflow.com/a/48537640
accepted answer: http://stackoverflow.com/a/48537640
has body: My data has a feature called level, and the data may have levels(-1,0,1,2,3) but my data now has only 2 levels 0 and -1. I'm using python for binary classification. How to do one-hot-encoding with all levels? What is the right approach to deal with this problem? Can I include all levels as I may expect them in test data? Or should I use only 2 levels ?
has answer: http://stackoverflow.com/a/48536402
possible better answer: http://stackoverflow.com/a/48536402
has title: how to deal with categorical data when training data has not got all expected categories?
type: Question
answer count: 2
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/84265485
has text: Thanks! I thought you could do ' except SyntaxError or NameError or ZeroDivisionError '
score: 0
comment on: http://stackoverflow.com/a/48634261
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84159985
has text: Mh, allright, I'm going to add the common way too!
comment on: http://stackoverflow.com/a/48581764
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48645643
has title: Python non-blocking input to communicate through serial with an Arduino
score: 0
has comment: http://stackoverflow.com/comment/84320255
answer count: 0
linked to: http://stackoverflow.com/q/22365473
has comment: http://stackoverflow.com/comment/84423904
has comment: http://stackoverflow.com/comment/84289937
type: Question
has comment: http://stackoverflow.com/comment/84288573
has body: I have connected my Arduino to the USB and I want to read data from it, but also to send commands through serial. The problem is that it prints to the terminal what the Arduino sends, but not until I send command from the PC. I searched over other posts, and this happens because the input is blocking. I have read many posts on stackoverflow, such as this: link_1 but everything I tried from there, does not work. I found this post: link_2 but I have problem with termios, and as I searched it does not cooperate with windows. Is there any way to make the code work without blocking and waiting from the input to write something? I started learning python programming python a few weeks, so maybe I missing something from code.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84409968
tagged with: python
linked to: http://stackoverflow.com/q/2408560

http://stackoverflow.com/a/48549968
has body: The problem lies in the last for loop. You are traversing for each basket and iterating over each product in the current basket. For each item you are checking that if it is equal to current productId. As there are 3 productIds you are getting 3x entries of item present in basket. Example: For basket1 , you are looping through first item=>23 for this you are making 3 entries in your output file: for i in productIds 1. 23 = 23 => 1 2. 23 = 24= >0 3. 23= 25=> 0 Additionally, you have one more problem. As your dict is not sorted by keys the order of basket looping is not guaranteed to be from basket1 to basket5 in increasing order. Replace the last for loop with:(sorting the dict followed by the correct iteration) data=collections.OrderedDict(sorted(data.items())); for key in data: # Will loop through each basket for productId in productIds: #Loop through each productId if productId in data[key]: # check if productId in the basket products txtFile.write('1 ') else: txtFile.write('0 ') txtFile.write('\n') Output: 23 24 25 1 1 1 1 0 0 1 0 0 0 0 1 0 1 1
answers question: http://stackoverflow.com/q/48541955
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48541955
type: Answer

http://stackoverflow.com/comment/84093092
type: QuestionComment
comment on: http://stackoverflow.com/q/48548231
has text: I guess the book could be wrong but it shouldn't be, it hasn't been as of yet, I just can't figure out where it's missing 2 values then.
score: 0
type: Comment

http://stackoverflow.com/a/48539221
score: 6
answers question: http://stackoverflow.com/q/48538581
has body: You can use a ChainMap from the collections module. From the doc: A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. [...] Lookups search the underlying mappings successively until a key is found. [...] So, you could create a config dict containing the key-value pairs from your config file, a cmd_line_args dict containing the ones given on the command line Then, create a ChainMap: from collections import ChainMap combined = ChainMap(cmd_line_args, config) When you access combined['arg1'], arg1 will first be looked up in the cmd_line_args dict, and if it isn't found there, config[arg1] will be returned. You can chain as many dicts as you wish, which lets you combine as many levels of defaults as you wish.
downvote count: 0
type: Answer
upvote count: 6

http://stackoverflow.com/a/48491997
downvote count: 0
has body: In your Python-CLI try the following: &gt;&gt;&gt; import scipy &gt;&gt;&gt; scipy.__version__ '1.0.0' &gt;&gt;&gt; scipy.__file__ '/usr/local/lib/python3.6/site-packages/scipy/__init__.py' Look if your output looks anything similar to this one. If scipy.__file__ points to a private directory of yours, then you have to resolve that namespace problem by renaming your own package. In case it looks similar, then in another terminal move into that directory: cd /usr/local/lib/python3.6/site-packages/scipy/ ls Look for a folder called stats/, if it is missing then your scipy is not installed correctly and you should reinstall it.
has comment: http://stackoverflow.com/comment/133354050
type: Answer
answers question: http://stackoverflow.com/q/48491649
score: 3
has comment: http://stackoverflow.com/comment/111284121
accepted answer of: http://stackoverflow.com/q/48491649
has comment: http://stackoverflow.com/comment/133396327
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/48549790
tagged with: sqlite
tagged with: python
score: -1
has body: I try to Update my DB via Input. import sqlite3 conn = sqlite3.connect('datenbank.db') print ("Opened database successfully") kunde1 = input("Der Kundename: ") anzahl1 = input("Anzahl Bewertung: ") conn.execute('''UPDATE kundenname SET anzahl = ? WHERE kundename = ?''', (anzahl1, kunde1)) conn.commit it dosent Show any Errors.. but it get not updated in DB? Thanks a lot !
type: Question
has answer: http://stackoverflow.com/a/48550033
upvote count: 0
type: UnansweredQuestion
answer count: 1
has title: Python - SQLite3 - Update not working via input
has comment: http://stackoverflow.com/comment/84095736
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/77145478
answers question: http://stackoverflow.com/q/48633156
type: Answer
has body: Same principle as user2357112's and root-11's, i.e., keeping the first element fixed and permuting all the others. Just faster. from itertools import permutations, islice from math import factorial def permutations_without_rotations(lst): return islice( permutations(lst), factorial(max(len(lst) - 1, 0)) ) Times for ten elements: 8.51 ± 0.04 ms Kelly 64.56 ± 0.54 ms root_11 90.87 ± 1.21 ms user2357112 Python: 3.11.4 (main, Sep 9 2023, 15:09:21) [GCC 13.2.1 20230801] Benchmark script (<a href="https://ato.pxeger.com/run?1=fVTNjtMwEL5wylMM4lBnla02XQooUp8AISFxLFXkJmPWWsfO2pMVVbVPwmUvcOcVeAyeZv2TNF0Q-JTM9_mbz-MZf_vRH-jG6MfH7wOJy3e_X3yQXW8sgSS0ZIxymbCmA5IdSh9NYPpLiCNO0pFs3IR2yHXh4y3eJ0pjlMKGpNEnTot3Ayb0lGnCLPbI6R9gj7YbQkovVoB0SjajTsfpZmIJ3pCxkqtsDLiDy7KsRQHvUakDU47yKgO_LNJg9ajEzuUjqZi1WMe_MoU6xuESygKu8jwfdQeHdnW9fluWKxZc873CMcUr-NRj4xWg4Q4rwK6nA0ykSJl-YAPKV3NWSKgAbehESqphHSSqFlh-CqTTZPFfSOuogAuLjrzus3zCWHDDPhwXpJ7LvHxWgLAz_yvbpDvunwpgjaG6LJnDu3FPSCL_Iz8zx0PK7dUOXm7AA_5rhsLaW-S3f1iRWSYG7Ttvc17-YrJSpMvOstCvgXQUFWx30ZcIvuLmh-g-tLFjYvRDgb0luIASryOfAt_5VsKWRbmt2OXbar3bnXeRWBxD9zNyefVmuRIP8OsnHOMoxNjrGOscLLxzr1oHVcv1F2Sr9VnVZndzEcIdpsFjinf7lldpiphgSaH03RhasgA9dHu0m3Lui8nykvc9an-EPBkQZ8eK-Qq4xcMmVmP001upiU318fOwrGvNO6xrr5HAxWf9Mb4j1aIIo7a8R-v8FefpVRkfl-mReQI" rel="nofollow noreferrer">Attempt This Online!): import itertools from timeit import timeit from statistics import mean, stdev from collections import deque from itertools import repeat from itertools import permutations, islice from math import factorial import sys def Kelly(lst): return islice(permutations(lst), factorial(max(len(lst) - 1, 0))) def user2357112(iterable): # Special case: empty iterable iterable = list(iterable) if not iterable: yield () return first, *rest = iterable for subperm in itertools.permutations(rest): yield (first, *subperm) def root_11(seq): for i in itertools.permutations(seq): if i[0] != seq[0]: break yield i funcs = user2357112, root_11, Kelly times = {f: [] for f in funcs} def stats(f): ts =…
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/84181885
has text: `Error has occurred: 'str' object has no attribute 'decode' `
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48592259

http://stackoverflow.com/comment/84147589
score: 0
type: QuestionComment
has text: If a value is a dict, then recursively apply your function.
comment on: http://stackoverflow.com/q/48574533
type: Comment

http://stackoverflow.com/comment/84061098
comment on: http://stackoverflow.com/q/48532721
score: 4
has text: What is the `Data` class or function? You need to give complete details in a question like this. See [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48528363
accepted answer of: http://stackoverflow.com/q/48490259
has body: Confusion often arises when you have an operation that mutates state (like iterator.get_next()) in your TensorFlow graph. The rule is fairly simple: Each stateful operation in a graph (that is not in a tf.while_loop() or tf.cond()) will execute exactly once per Session.run() call. Applying that rule, there is only one iterator.get_next() op in your graph, and so the iterator will only advance once per Session.run() call, and the same element will be used to calculate A and B. To get your desired behavior, you will need to create a second iterator.get_next() op. Moreover, to get deterministic behavior, we will need to ensure that there are control dependencies between the two iterator.get_next() ops. For example, the following program exhibits your desired behavior: import tensorflow as tf dataset1 = tf.data.Dataset.range(5) dataset2 = tf.data.Dataset.range(5) dataset3 = tf.data.Dataset.zip((dataset1, dataset2)) iterator = dataset3.make_initializable_iterator() with tf.Session() as sess: sess.run(iterator.initializer) next1, next2 = iterator.get_next() A = next1 # Get a second element from `iterator` and add a control dependency to # ensure that it is consumed *after* `A` is computed. with tf.control_dependencies([A]): next3, next4 = iterator.get_next() B = next3 + next4 while True: try: a, b = sess.run([A,B]) print(a,b) except tf.errors.OutOfRangeError: print('done') break
type: AcceptedAnswer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/48490259
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84051993

http://stackoverflow.com/comment/84268329
has text: sorry that's my bad, i must have screwed it up while copying and pasting my code, i've just noticed that the return statement was outside of the def solution as well.... i've put the if statement and the while inside the for loop (edited the code above)but still getting the same error as described in the original question... is this a problem with my strategy
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48628207

http://stackoverflow.com/a/48513354
has comment: http://stackoverflow.com/comment/84021496
type: Answer
has comment: http://stackoverflow.com/comment/84021665
has comment: http://stackoverflow.com/comment/84021582
score: 0
has comment: http://stackoverflow.com/comment/84021727
has comment: http://stackoverflow.com/comment/84021877
has body: There are two basic looping strategies you could use here: you could count up to n, reading lines as you go you could read lines from file, keeping track of how many you've read, and stop when you reach a certain number. def filewrite(textfile, n): with open(textfile) as infile: for _ in range(n): print(infile.readline(), end='') print() def filewrite(textfile, n): with open(textfile) as infile: counter = 0 for line in infile: if counter &gt;= n: break print(line, end='') counter += 1 The first is obviously more readable, and since readline will just return an empty string if it runs out of lines, it's safe to use even if the user asks for more lines than the infile has. Here I'm also using a context manager to make sure the files are closed when I'm done with them. Here's a version without the stuff you don't recognize def filewrite(textfile, n): infile = open(textfile) count = 0 while count &lt; n: print(infile.readline()) count += 1 infile.close()
has comment: http://stackoverflow.com/comment/84021476
has comment: http://stackoverflow.com/comment/84021643
answers question: http://stackoverflow.com/q/48513205
has comment: http://stackoverflow.com/comment/84021793

http://stackoverflow.com/comment/84265281
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48634110
has text: Are you just counting the number of times a country appears? Sounds like you want to load with the `csv` module, then count with `collections.Counter`, but we're not going to write the code for you.

http://stackoverflow.com/q/48609111
has answer: http://stackoverflow.com/a/48609167
downvote count: 1
has comment: http://stackoverflow.com/comment/84215128
favorite count: 0
type: Question
answer count: 2
tagged with: python-internals
has body: So I'm trying to know the details of dir() function. First I looked at the implementation of it: https://github.com/python/cpython/blob/e76daebc0c8afa3981a4c5a8b54537f756e805de/Objects/object.c#L1450-L1477 /* Helper for PyObject_Dir: object introspection. */ static PyObject * _dir_object(PyObject *obj) { PyObject *result, *sorted; PyObject *dirfunc = _PyObject_LookupSpecial(obj, &amp;PyId___dir__); assert(obj); if (dirfunc == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "object does not provide __dir__"); return NULL; } /* use __dir__ */ result = _PyObject_CallNoArg(dirfunc); Py_DECREF(dirfunc); if (result == NULL) return NULL; /* return sorted(result) */ sorted = PySequence_List(result); Py_DECREF(result); if (sorted == NULL) return NULL; if (PyList_Sort(sorted)) { Py_DECREF(sorted); return NULL; } return sorted; } And found that the _dir_object function doesn't do any work itself, but invokes the __dir__ method of the introspected object. &gt;&gt;&gt; def test(): pass &gt;&gt;&gt; test.__dir__ &lt;built-in method __dir__ of function object at 0x10ee57ae8&gt; So how to know the implementation of it?
tagged with: python
has answer: http://stackoverflow.com/a/48609428
score: 2
has title: How is __dir__ implemented exactly, and how should I know it?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84214866
has comment: http://stackoverflow.com/comment/84215143
upvote count: 3
accepted answer: http://stackoverflow.com/a/48609167
possible better answer: http://stackoverflow.com/a/48609428

http://stackoverflow.com/a/48511225
has comment: http://stackoverflow.com/comment/84017729
has comment: http://stackoverflow.com/comment/84018625
accepted answer of: http://stackoverflow.com/q/48511034
has comment: http://stackoverflow.com/comment/84017367
has comment: http://stackoverflow.com/comment/84018135
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84017569
has comment: http://stackoverflow.com/comment/84017755
has comment: http://stackoverflow.com/comment/84018398
has comment: http://stackoverflow.com/comment/84018022
has comment: http://stackoverflow.com/comment/84018313
has comment: http://stackoverflow.com/comment/84018339
has comment: http://stackoverflow.com/comment/84018420
has comment: http://stackoverflow.com/comment/84017609
has comment: http://stackoverflow.com/comment/84018528
has body: The word database should be db and then you should be fine and connect. Change your loginpart into below code: cnx = MySQLdb.connect(user ='phpmyadmin', passwd ='raspberry', host ='192.168.0.58', db ='freddy') This gives you oversight of used keys and values. Enjoy ;-)
has comment: http://stackoverflow.com/comment/84017425
has comment: http://stackoverflow.com/comment/84018786
has comment: http://stackoverflow.com/comment/84018577
has comment: http://stackoverflow.com/comment/84018578
type: Answer
has comment: http://stackoverflow.com/comment/84017499
has comment: http://stackoverflow.com/comment/84018656
answers question: http://stackoverflow.com/q/48511034
has comment: http://stackoverflow.com/comment/84018810
has comment: http://stackoverflow.com/comment/84017679
has comment: http://stackoverflow.com/comment/84017854
score: 0
has comment: http://stackoverflow.com/comment/84018727
has comment: http://stackoverflow.com/comment/84018504

http://stackoverflow.com/comment/84242367
type: Comment
comment on: http://stackoverflow.com/a/48619647
type: AnswerComment
score: 0
has text: Yes, changing the input format makes it another question. The whole point of the question is to how deal with such inputs. Regarding the performance you're using a nested loop and using both `products` and `combinations`. Just imagine how this approach will perform if the number of excludes and lists are larger. Also using list object in combinations is not memory efficient as well (due to immutability and lack of cashing etc.).

http://stackoverflow.com/comment/84158404
has text: http://www.devils-heaven.com/facebook-access-tokens/
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48579740
type: QuestionComment

http://stackoverflow.com/q/48554497
has title: How do I write to stdin (returned from exec_command) in paramiko?
upvote count: 8
has answer: http://stackoverflow.com/a/48554793
tagged with: python
tagged with: paramiko
tagged with: unix
score: 8
has body: I am trying to write to a custom program's stdin with paramiko. Here is a minimal (non-)working example: ~/stdin_to_file.py: #! /usr/bin/python import time, sys f = open('/home/me/LOG','w') while True: sys.stdin.flush() data = sys.stdin.read() f.write(data+'\n\n') f.flush() time.sleep(0.01) Then I do these commands in IPython: import paramiko s = paramiko.client.SSHClient s.load_system_host_keys() s.connect('myserver') stdin, stdout, stderr = s.exec_command('/home/me/stdin_to_file.py') stdin.write('Hello!') stdin.flush() Unfortunately, nothing then appears in ~/LOG. However, if I do $ ~/stdin_to_file.py &lt; some_other_file The contents of some_other_file appear in ~/LOG. Can anyone suggest where I've gone wrong? It seems like I'm doing the logical thing. None of these work either: stdin.channel.send('hi') using the get_pty parameter sending the output of cat - to stdin_to_file.py
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: ssh-tunnel
accepted answer: http://stackoverflow.com/a/48554793
type: AnsweredQuestion

sensors
type: Tag
tags question: http://stackoverflow.com/q/48563680
tag name: sensors

http://stackoverflow.com/q/48564368
tagged with: python
has comment: http://stackoverflow.com/comment/84124579
has comment: http://stackoverflow.com/comment/84124658
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84127976
has comment: http://stackoverflow.com/comment/84124613
possible better answer: http://stackoverflow.com/a/48564793
answer count: 2
has comment: http://stackoverflow.com/comment/84125206
tagged with: pandas
has answer: http://stackoverflow.com/a/48564793
score: 0
accepted answer: http://stackoverflow.com/a/48564749
tagged with: dataframe
has title: Transform dedicated colums from Dataframe to Numpy array and loop properly
has answer: http://stackoverflow.com/a/48564749
has body: I have a data frame... A B C D E F 0 2018-02-01 2 3 4 5 6 1 2018-02-02 6 7 8 4 2 2 2018-02-03 3 4 5 6 7 ...which I convert to a numpy array... [['2018-02-01' 2 3 4 5 6] ['2018-02-02' 6 7 8 4 2] ['2018-02-03' 3 4 5 6 7]] What I would like to do is the following: Store only columns A, B, and C in the numpy array, rather than all the columns. I would like to loop over the first column, then the second and the third one. How can I achieve that? My code is as follows: import pandas as pd df = pd.DataFrame([ ['2018-02-01', 1, 3, 6, 102, 8], ['2018-02-01', 2, 3, 4, 5, 6], ['2018-02-02', 6, 7, 8, 4, 2], ['2018-02-03', 3, 4, 5, 6, 7] ], columns=['A', 'B', 'C', 'D', 'E', 'F']) print(df) #--&gt; Here only save Columns A,B,C nparray = df.as_matrix() print(nparray) #--&gt; Loop throug Columns and would like to have it looped over the Column A first for i in nparray: print(i) #Using the Values in B and C columns for that loop calc= [func(B,C) for B, C in zip(nparray)] Update: I made a numerical example. A B C D E F 0 2018-02-01 1 3 6 102 8 1 2018-02-01 2 3 4 5 6 2 2018-02-02 6 7 8 4 2 3 2018-02-03 3 4 5 6 7 Dummy code looks likte the following (it is more a nested loop) loop over date 2018-02-01: calc = func(Column B + Column C) = 1+3 = 4 next row is the same date so: calc += func(Column B + Column C) = 4 + 2+ 3 = 9 for date 2018-02-01 the result is 9 and can be stored e.g. in a csv file loop over date 2018-02-02 calc = func(Column B + Column C) = 6+7 = 13 for date 2018-02-02 the result is 13 and can be stored e.g. in a csv file loop over date 2018-02-03 calc = func(Column B + Column C) = 3+4 = 7 for date 2018-02-03 the result is 7 and can be stored e.g. in a csv file etc
type: Question
tagged with: numpy
tagged with: arrays

http://stackoverflow.com/q/48629033
downvote count: 4
has title: modifying iterative function to be recursive
upvote count: 2
has body: I have an interative function that takes in a sequence of integers and returns the index position of a target item or returns where the target should be inserted.(if the item is not in the list) The function works great but I am trying to figure out what is the leanest way to change this function from iterative to recursive implimentation without the aid of any auxilliary functions. def binary_search(a_list, first, last, target): """a sequence of integers, index of first item, index of last item, target to search for """ while first &lt;= last: middle = (first + last) // 2 if a_list[middle] == target: return middle if target &lt; a_list[middle]: last = middle - 1 else: first = middle + 1 return first print(binary_search([2, 5, 8, 11, 17], 0, 4, 5))
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48629177
type: Question
has answer: http://stackoverflow.com/a/48629177
tagged with: algorithm
score: -2
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84240565
score: 0
comment on: http://stackoverflow.com/q/48621973
type: QuestionComment
has text: @Ev.Kounis: I'd like to be getting the outer key, inner key and the inner value for every iteration.
type: Comment

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/48574075
tags question: http://stackoverflow.com/q/48591862
tags question: http://stackoverflow.com/q/48621852
tags question: http://stackoverflow.com/q/48591768
tags question: http://stackoverflow.com/q/48630089
tags question: http://stackoverflow.com/q/48492451
type: Tag

http://stackoverflow.com/comment/84163707
comment on: http://stackoverflow.com/q/48583184
has text: OK, thanks. I guess it is time for a less elegant solution. Will try and get this question closed.
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/84223817
type: Comment
type: QuestionComment
has text: You might find it easier to use something like [mechanize](https://github.com/python-mechanize/mechanize) to automate the browser activity. Or you can use the developer console in Chrome to capture the interaction so you can replicate it using requests.
score: 0
comment on: http://stackoverflow.com/q/48613356

http://stackoverflow.com/comment/84048981
type: QuestionComment
has text: yes, I can viewed the new file which is same as the original one...
comment on: http://stackoverflow.com/q/48526062
score: 0
type: Comment

http://stackoverflow.com/q/48620068
has body: I have a number of training examples in my dataset and would like to rotate each one so that I get double the number. I am using datasets and tried it like this: def addrotation(images, labels): images_rotated_left = tf.contrib.image.rotate(images, pi/2.0) labels_rotated_left = tf.stack([labels[1], labels[2], labels[0]]) return tf.stack([images,images_rotated_left]), tf.stack([labels, labels_rotated_left]) But when I now use dataset = dataset.map(addrotation), I get examples with double the data. Is it possible to return the rotated tensors in a way so that they count as seperate examples or "lines"?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48623951
score: 0
answer count: 1
tagged with: tensorflow
linked to: http://stackoverflow.com/q/47343228
tagged with: tensorflow-datasets
type: Question
has title: How to make two out of one training example in tensorflow dataset using map

http://stackoverflow.com/q/48640014
type: UnansweredQuestion
answer count: 1
score: -1
upvote count: 0
has title: how to concatenate string in python inside a test run method?
has comment: http://stackoverflow.com/comment/84276725
downvote count: 1
favorite count: 0
has body: I have one method and its parameters are as below: func_stat.update(utils.run_test_cases(api_tests.APITest(apiclient).AWS_post_provider())) i want to make this "AWS_post_provider()" as a variable and execute as a whole. Hence i read it from command line and concatenate. but it did not work. tname = sys.argv[4] testapp='api_tests.APITest(apiclient).'+tname func_stat.update(utils.run_test_cases(testapp)) any suggestion ?
type: Question
has answer: http://stackoverflow.com/a/48640200
tagged with: python

http://stackoverflow.com/q/48616051
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48616501
has comment: http://stackoverflow.com/comment/84229196
has comment: http://stackoverflow.com/comment/84229135
type: Question
tagged with: phantomjs
tagged with: python
accepted answer: http://stackoverflow.com/a/48616277
has comment: http://stackoverflow.com/comment/84229046
has body: I want to click on the Next-button at https://free-proxy-list.net/. The XPATH selector is //*[@id="proxylisttable_next"]/a I do this with the following piece of code: element = WebDriverWait(driver, 2, poll_frequency = 0.1).until (EC.visibility_of_element_located((By.XPATH, '//*[@id="proxylisttable_next"]/a'))) if (element.is_enabled() == True) and (element.is_displayed() == True): element.click() print "next button located and clicked" # printed in case of success Subsequently, I get all the IPs from the table like this: IPs = WebDriverWait(driver, 2, poll_frequency = 0.1).until (EC.presence_of_all_elements_located((By.CSS_SELECTOR, ':nth-child(n) &gt; td:nth-child(1)'))) Although the CSS_selector is the same for all tabs, and although I get a next button located and clicked, the IPs output is the same for both tabs (i.e. it seems like the Next-button never was clicked). Additionally, there is no Exception thrown. Therefore, there must be something fundamentally wrong with my approach. How to click on visible &amp; enabled buttons correctly in phantomJS using python/selenium? For your understanding, here is the html of the page section I am referring to:
has title: Web-element is visible and enabled but .click() fails in python selenium with phantomJS
has comment: http://stackoverflow.com/comment/84229066
has answer: http://stackoverflow.com/a/48616277
type: AnsweredQuestion
answer count: 2
tagged with: screen-scraping
possible better answer: http://stackoverflow.com/a/48616501
score: 0
tagged with: selenium

http://stackoverflow.com/q/48490633
has comment: http://stackoverflow.com/comment/83974233
has comment: http://stackoverflow.com/comment/83974363
score: 0
has body: Hello fellow programmers! I am reading about the functionality of the interactive shell reached through running ...python manage.py shell. This is something that I have done many times before, however I am not quite sure exactly How the actual shell connects with Django. Before asking this question, I have indeed tried to find my way through the official documentation - as well as other posts on this website. This question does not appear to have been presented with an answer a beginner like me can comprehend. I have read that the manage.py shell-command 'gives us an interactive shell with the Python path set up correctly for Django.'. I know that it can be used to interact with a Django project, and to query configured databases and models - however what happens behind the scenes? For example, when writing ModelName.objects.all() - what is the origin of .objects and .all(), because it does not seem to be pure python syntax? How does Django understand this? Is the shell a special python-version provided by Django, with some added syntax that Django understands? Because that would make sense. Thank you from Sweden!
has comment: http://stackoverflow.com/comment/83974534
answer count: 1
has comment: http://stackoverflow.com/comment/83974641
tagged with: shell
has comment: http://stackoverflow.com/comment/83974556
type: Question
has answer: http://stackoverflow.com/a/48491364
type: UnansweredQuestion
tagged with: django
has title: How is the python interactive shell connected to Django?
tagged with: python

http://stackoverflow.com/comment/83979519
comment on: http://stackoverflow.com/q/48493008
score: 0
type: QuestionComment
type: Comment
has text: @Rawing It may or may not, depending on whether the space width is fixed or not.

http://stackoverflow.com/comment/84113740
comment on: http://stackoverflow.com/a/48558916
has text: Thanks tried this but its still giving entries which has amount 0 :(
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84276000
has text: this works, thank you ayhan
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48639281
type: Comment

http://stackoverflow.com/comment/84281613
score: 0
comment on: http://stackoverflow.com/q/48642444
type: QuestionComment
has text: @schwobaseggl slicing indeed works, thanks
type: Comment

http://stackoverflow.com/comment/84283276
has text: @ArpitSolanki Yes
type: QuestionComment
comment on: http://stackoverflow.com/q/48642111
score: 0
type: Comment

http://stackoverflow.com/q/48574572
score: 0
has comment: http://stackoverflow.com/comment/84167113
answer count: 1
has comment: http://stackoverflow.com/comment/84161834
upvote count: 1
has comment: http://stackoverflow.com/comment/84145931
accepted answer: http://stackoverflow.com/a/48582458
linked to: http://stackoverflow.com/q/8548030
has comment: http://stackoverflow.com/comment/84164612
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48582458
has comment: http://stackoverflow.com/comment/84161359
has comment: http://stackoverflow.com/comment/84146379
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84151573
has body: I'm lost trying to install this package. It looks like I have it, but I can't install? Error pip location EDIT: I've tried running in cmd but I get another error cmd error cmd error
has comment: http://stackoverflow.com/comment/84167003
has title: "pip install pymysql" syntax error for python 2.7.13
tagged with: python
has comment: http://stackoverflow.com/comment/84145928
has comment: http://stackoverflow.com/comment/84145933
has comment: http://stackoverflow.com/comment/84162538
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84164638

http://stackoverflow.com/a/48575978
has comment: http://stackoverflow.com/comment/84148797
upvote count: 3
answers question: http://stackoverflow.com/q/48575889
has comment: http://stackoverflow.com/comment/84184133
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84188036
has body: You were fairly close: &gt; doit = subprocess.Popen('here.exe -command', cwd='C:/myproject/betty/') This would actually work if your command were called here.exe -command but of course, no such file exists. You want ['here.exe', '-command'] (or somewhat more unsafely and less efficiently add shell=True; but really, don't). It seems you forgot to pass in env=my_env in this attempt, too; though does here.exe really require you to modify the PATH? And if it does, repeatedly creating a new copy for each new subprocess seems slightly wasteful. You'll also want to switch to subprocess.run() or one of the legacy wrappers; you should really only use the low-level Popen() function directly from library functions. On the other hand, does here.exe really need to run in a particular directory, and does that directory exist on your PATH? Windows is slightly weird and Windows programmers are often unaware of basic command-line usability design principles; but if here.exe is at all correctly written, perhaps you are actually looking for s = subprocess.run(['c:/myproject/betty/here.exe', '-command'], env=my_env)
score: 3

http://stackoverflow.com/comment/84211961
comment on: http://stackoverflow.com/a/48571831
type: Comment
score: 0
type: AnswerComment
has text: MyModel(author='abc') - if author field was monkey-patched to non-data descriptor, there are two attributes exists now, one is instance attribute (author='abc') and the other is class-attr (author=Descriptor()), but instance attribute has higher priority then class-attr. So in case, of model.author you get 'abc', but if you 'del model.author' you would be able to get older value. Thats why you can set any non-related model field value to any data, even to list for example "model.balance = [1,2,3]" and it won`t fail even if balance is integer field, of course until you would try to save it.

http://stackoverflow.com/comment/84234888
type: QuestionComment
comment on: http://stackoverflow.com/q/48619065
type: Comment
score: 0
has text: Thats great. what about the rest of my comment?

http://stackoverflow.com/q/48493343
has title: Python Numpy - numpy axis performance
has comment: http://stackoverflow.com/comment/83988366
has comment: http://stackoverflow.com/comment/83995919
downvote count: 0
answer count: 1
has body: By default, numpy is row major. Therefore, the following results are accepted naturally to me. a = np.random.rand(5000, 5000) %timeit a[0,:].sum() 3.57 µs ± 13.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit a[:,0].sum() 38.8 µs ± 8.19 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) Because it is a row major order, it is natural to calculate faster by a [0,:]. However, if use the numpy sum function, the result is different. %timeit a.sum(axis=0) 16.9 ms ± 13.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit a.sum(axis=1) 29.5 ms ± 90.3 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) If use the numpy sum function, it is faster to compute it along the column. So My point is why the speed along the axis = 0 (calculated along column) is faster than the along the axis = 1(along row). For example a = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], order='C') In the row major order, [1,2,3] and [4,5,6], [7,8,9] are allocated to adjacent memory, respectively. Therefore, the speed calculated along axis = 1 should be faster than axis = 0. However, when using numpy sum function, it is faster to calculate along the column (axis = 0). How can you explain this? Thanks
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83979912
score: 5
type: UnansweredQuestion
upvote count: 5
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/83993866
has comment: http://stackoverflow.com/comment/83996989
has answer: http://stackoverflow.com/a/48493360

http://stackoverflow.com/q/48586738
upvote count: 13
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/55816982
has title: Seaborn heatmap - colorbar label font size
has answer: http://stackoverflow.com/a/55816982
downvote count: 0
has body: How do I set the font size of the colorbar label? ax=sns.heatmap(table, vmin=60, vmax=100, xticklabels=[4,8,16,32,64,128],yticklabels=[2,4,6,8], cmap="PuBu",linewidths=.0, annot=True,cbar_kws={'label': 'Accuracy %'}
favorite count: 0
has answer: http://stackoverflow.com/a/48587137
score: 13
type: AnsweredQuestion
tagged with: seaborn
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/48587137

http://stackoverflow.com/comment/84138742
score: 0
has text: Did you tried my updated answer or the original one?
comment on: http://stackoverflow.com/a/48570200
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84054432
type: AnswerComment
type: Comment
has text: I also tried df['Missing']=df.where(df.isnull().any(1)) .stack().reset_index().groupby('level_0')['level_1'].apply(','.join) and it gives me the opposite of what I want haha
comment on: http://stackoverflow.com/a/48528995
score: 0

http://stackoverflow.com/a/48559277
score: 12
upvote count: 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48558973
has body: The short answer is IEEE 754 specifies NaN as a float value. As for what you should do about converting a pd.Series to specific numeric data types, I prefer to use pd.to_numeric where possible. The below examples demonstrate why. import pandas as pd import numpy as np s = pd.Series([1, 2.5, 3, 4, 5.5]) # s.dtype = float64 s = s.astype(float) # s.dtype = float64 s = pd.to_numeric(s, downcast='float') # s.dtype = float32 t = pd.Series([1, np.nan, 3, 4, 5]) # s.dtype = float64 t = t.astype(int) # ValueError t = pd.to_numeric(t, downcast='integer') # s.dtype = float64 u = pd.Series([1, 2, 3, 4, 5, 6]) # s.dtype = int64 u = u.astype(int) # s.dtype = int32 u = pd.to_numeric(u, downcast='integer') # s.dtype = int8
type: Answer
has comment: http://stackoverflow.com/comment/84114236
answers question: http://stackoverflow.com/q/48558973

http://stackoverflow.com/comment/84021046
has text: @Schilcote: So if this is a public facing server, that's a bad idea; the question made it sound like this was just for repeatable (assumed local) unit tests.
comment on: http://stackoverflow.com/q/48513058
score: 3
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84228419
type: Comment
comment on: http://stackoverflow.com/q/48566534
type: QuestionComment
score: 0
has text: I think you need to backtrack a little. How did you end up with multiple counters? Wouldn't it be easier to get the counts into the indexed dictionaries you want before producing the intermediate list of counters?

http://stackoverflow.com/q/48592154
tagged with: python-imaging-library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84191252
tagged with: python
score: 2
upvote count: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/84182645
has body: I have a problem with a basic steganography script in Python, using PIL. Here is my goal: I want to store four MSB of the pixel values of every bands of an image I want to hide. Then store them in the four LSB of another image. In order to reveal the hidden image, I just want to extract the four LSB and add '0000'. I know this is very destructive. But the image that hides should at least disapear. Actually it doesn't. I don't know what is wrong with my code. Could you help me please ? from PIL import Image global image, pixels, s_image, s_pixels def hide_stegano(): def new_pixel(pix, s_pix): return (pix &amp; 240) | ((s_pix &amp; 240) &gt;&gt; 4) l, h = image.size temp = Image.new('RGB', (l, h)) temp_pix = temp.load() for i in range(l): for j in range(h): rgb = list(pixels[i, j]) s_rgb = list(s_pixels[i, j]) for band, (value, s_value) in enumerate(zip(rgb, s_rgb)): rgb[band] = new_pixel(value, s_value) temp_pix[i, j] = tuple(rgb) temp.save("temp.jpg") temp.show() def reveal_stegano(): def new_pixel(pix): return (pix &amp; 15) &lt;&lt; 4 l, h = image.size temp = Image.new('RGB', (l, h)) temp_pix = temp.load() for i in range(l): for j in range(h): rgb = list(pixels[i, j]) for band, value in enumerate(rgb): rgb[band] = new_pixel(value) temp_pix[i, j] = tuple(rgb) temp.save("temp.jpg") temp.show() image = Image.open("image1.jpg").convert('RGB') pixels = image.load() image.show() # Hidden image s_image = Image.open("image2.jpg").convert('RGB') s_image = s_image.resize(image.size) s_pixels = image.load() s_image.show() hide_stegano() reveal_stegano() Do you see something wrong ? Best regards
has comment: http://stackoverflow.com/comment/84181705
has title: Simple steganography with python 3 / PIL
has comment: http://stackoverflow.com/comment/84182011
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84181989
tagged with: steganography

http://stackoverflow.com/comment/84073148
has text: What makes you think there's JSON to be decoded there? You've accessed the home page of a website, the response is in HTML.
comment on: http://stackoverflow.com/q/48539039
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48552542
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am using a pre-tained vector to create an embedding like so import numpy import gensim import tensorflow ft_model=gensim.models.KeyedVectors.load_word2vec_format("ft_model.vec") vocabulary=ft_model.vocab embeddings=numpy.array([ft_model.word_vec(x) for x in vocabulary.keys()]) vocabulary_size=len(vocabulary) embedding_size=embeddings.shape[1] W=tensorflow.Variable( tensorflow.constant(0.0, shape=[vocabulary_size, embedding_size]), trainable=False, name="W" ) embedding_placeholder=tensorflow.placeholder( tensorflow.float32,[vocabulary_size,embedding_size], name="fasttext_vector" ) embedding_init=W.assign(embedding_placeholder) data_placeholder=tensorflow.placeholder(tensorflow.int32,shape=[None, max_length]) embedding_layer=tensorflow.nn.embedding_lookup(W, data_placeholder) I get an error after it briefly runs through 1 or two training batches and the code crashes completely! ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[5000,14621,100] The stack trace cleary states that this is caused by the embedding_layer=tensorflow.nn.embedding_lookup(W, data_placeholder) line. Any idea what could be causing this? 100 is the embedding size but those other numbers (5000, 14621) are rather strange, larger than I exected, and seem to be causing TensorFlow to completely chew up all GPU memory! embedding lookups seem like such a common thing and the .vec file I am incorporating is very small.
has comment: http://stackoverflow.com/comment/84102264
has answer: http://stackoverflow.com/a/64185088
tagged with: python
has comment: http://stackoverflow.com/comment/84101899
score: 2
has title: TensorFlow running out of memory (ResourceExhaustedError) when executing embedding_lookup
has comment: http://stackoverflow.com/comment/84103280
upvote count: 2
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/48590278
tagged with: python
has body: I am trying to get an article link and title of that article from an HTML data of a page, I tried using this code def get_ndtvsports_articles(): cricbuzz_article_link = "https://sports.ndtv.com/cricket" r = requests.get(ndtvsports_article_link) ndtvsports_article_html = r.text soup = BeautifulSoup(ndtvsports_article_html, "html.parser") # print(soup.prettify()) ndtvsports_items = soup.find_all("div", {"class": "post-title"}) ndtvsports_article_dict = {} for div in ndtvsports_items: ndtvsports_article_dict[div.find('a')['title']] = div.find('a')['href'] return ndtvsports_article_dict I ended up getting output as this &lt;function get_ndtvsports_articles at 0x7f33fb762950&gt; This does not have a text entry This does not have a text entry This does not have a text entry This does not have a text entry This does not have a text entry This does not have a text entry I was expecting to get href link and page title like this {'Mendis misses out on maiden double ton': 'http://www.cricbuzz.com/cricket-news/100130/bangladesh-vs-sri-lanka-1st-test-day-3-tea-kusal-mendis-dananjaya-de-silva-report'}
score: 0
has title: why am I not able to print the html address and title from a html page source?
answer count: 1
has answer: http://stackoverflow.com/a/48590431
tagged with: parsing
type: Question
tagged with: python-3.x
type: UnansweredQuestion

addition
tags question: http://stackoverflow.com/q/48609055
type: Tag
tag name: addition
tags question: http://stackoverflow.com/q/48549065

http://stackoverflow.com/comment/84201455
type: Comment
has text: Awesome!! Thanks for the solution. Would you mind to explain a bit more on how to use .data?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48602058

http://stackoverflow.com/q/48566747
type: Question
has comment: http://stackoverflow.com/comment/84140929
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84140111
type: UnansweredQuestion
has body: I have a 2D grid of points z. Each point has an associated label. The labels are from the range [0.0, 4.0]. I want to do a contourf plot having a single contour line for each label occurring in z. import matplotlib.pyplot as plt from matplotlib import colors import numpy as np cmap = colors.ListedColormap([ 'red', 'orange', 'yellow', 'green', 'royalblue' ]) x = np.linspace(-1.0, 1.0, num=50) xx, yy = np.meshgrid(x, x) z1 = np.ones(shape=xx.shape) z1 = np.tril(z1) levels1 = np.arange(z1.min(), z1.max() + 2) - 0.5 z2 = np.ones(shape=xx.shape) + 3 z2 = np.tril(z2) levels2 = np.arange(z2.min(), z2.max() + 2) - 0.5 print('Labels (left): ', np.unique(z1)) print('Labels (right): ', np.unique(z2)) fig, axes = plt.subplots(nrows=1, ncols=2) im1 = axes[0].contourf(xx, yy, z1, levels=levels1, cmap=cmap) im2 = axes[1].contourf(xx, yy, z2, levels=levels2, cmap=cmap) # c = axes.contour(xx, yy, z, colors='k', levels=levels, linwidths=.1) fig.colorbar(im1, ax=axes[0], ticks=np.arange(0, 5)) fig.colorbar(im2, ax=axes[1], ticks=np.arange(0, 5)) plt.show() This produces the following output: For the plot on the left everything is as expected. However, for the plot on the right its not. Here, the grid contains the two labels 0 and 4. So, there should be only two colors, blue and red. However, contourf also draws contour lines for all the labels in between, i.e 1, 2, and 3. How can I fix this? Ideally, the plot on the right should look exactly as the plot on the left (except for the colors).
has comment: http://stackoverflow.com/comment/84139648
tagged with: python
has comment: http://stackoverflow.com/comment/84143804
tagged with: plot
has comment: http://stackoverflow.com/comment/84140589
score: 2
has comment: http://stackoverflow.com/comment/84152504
has comment: http://stackoverflow.com/comment/84143584
has comment: http://stackoverflow.com/comment/84139951
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84131313
downvote count: 0
has title: Filled contour plot with arbitrary integer labels
favorite count: 0

http://stackoverflow.com/a/48638655
upvote count: 0
has body: As you can read here because HTMLParseError is deprecated from Python 3.3 onwards and removed in Python 3.5. I will recommend you to use other parser. Check BeautifulSoup Documentation
downvote count: 1
answers question: http://stackoverflow.com/q/48637930
type: Answer
score: -1

http://stackoverflow.com/comment/84280877
comment on: http://stackoverflow.com/q/48640937
type: Comment
type: QuestionComment
has text: Right, any idea how do I go about it?
score: 0

http://stackoverflow.com/q/48575090
favorite count: 0
type: Question
tagged with: networkx
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84147172
accepted answer: http://stackoverflow.com/a/48575124
has comment: http://stackoverflow.com/comment/84147080
tagged with: python
has body: Hi everybody I am trying to create a list (pd.Series) with one future obtained by using nx.jaccard_coefficient, the problem is that I am getting an iterator and I have no idea how to extract the result that I am supposed to obtain. The function is supposed to return a iterator with 3 parameters u,v,p. So I created a comprenhension list to extract the data for some set of edges. future_connections["Jaccard"] = [nx.jaccard_coefficient(G,edge) for edge in future_connections['index']] And I get the following retults Future Connection index a b Common_Neighbors \ (6, 840) 0.0 (6, 840) 6 840 9 (4, 197) 0.0 (4, 197) 4 197 2 (620, 979) 0.0 (620, 979) 620 979 0 (519, 872) 0.0 (519, 872) 519 872 2 Jaccard (6, 840) &lt;generator object jaccard_coefficient.&lt;locals&gt;... (4, 197) &lt;generator object jaccard_coefficient.&lt;locals&gt;... (620, 979) &lt;generator object jaccard_coefficient.&lt;locals&gt;... (519, 872) &lt;generator object jaccard_coefficient.&lt;locals&gt;... Any idea on how to extract the values of the generator??? Thanks.
has comment: http://stackoverflow.com/comment/84147265
answer count: 2
possible better answer: http://stackoverflow.com/a/59256515
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/48575124
has title: How to deal with iterators in python?
has answer: http://stackoverflow.com/a/59256515
downvote count: 0
has comment: http://stackoverflow.com/comment/84146887
upvote count: 1

http://stackoverflow.com/comment/84038715
has text: yes sir the client is still going to send and it will stay connected,ihave only one client,and i want to do is when the client send the data it will update my textview. the counting is already process in the client so it will only send the output.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48521184
type: QuestionComment

http://stackoverflow.com/comment/83974961
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48490895
has text: Sure, makes sense. Was there some reason you didn't just use this? Did it pass your tests?
type: Comment

http://stackoverflow.com/comment/84411898
type: AnswerComment
has text: @Lukas you cannot sort as it is but with a slight modification you could do it (`sort` the name lists before the composition of the query).
comment on: http://stackoverflow.com/a/48687349
type: Comment
score: 0

http://stackoverflow.com/comment/84246033
score: 0
comment on: http://stackoverflow.com/q/48624364
type: QuestionComment
type: Comment
has text: Unfortunately, the `overlay_frac`, `blank_bb` and `scale` are already functions provided beforehand. But `overlay_frac` takes in 3 arguments (a fraction of the top layer, pattern1, pattern2). `blank_bb` is just a blank sheet to help with the coding. `scale` is to scale down the shape of the original rune. So what I am aiming for is actually 4 circles (almost like a dartboard), with the middle circle the darkest and the circle fading as it spreads out.

http://stackoverflow.com/comment/84252837
has text: My guess is that they cut the tweet off using the `...` to signify that they cut it off. But I can't be sure unless you provide an image of the exact source to see if that's the case.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48613919
type: QuestionComment

http://stackoverflow.com/q/48610634
score: 1
has title: NameError: name 'process_button16' is not defined
has body: I am getting NameError: name 'process_button16' is not defined error when running the following code. It also turns on the LEDs without pushing the button....that shouldn't do that... I am trying to implement a button press action using an app in appdaemon for Home Assistant. I'm a former developer, but not python so I'm banging my head against the keyboard here.... Any help would be most appreciated. import appdaemon.appapi as appapi from gpiozero import Button import RPi.GPIO as GPIO global button BUTTON_PIN = 16 button = None class ButtonSense(appapi.AppDaemon): GPIO.output(17,GPIO.LOW) GPIO.output(27,GPIO.LOW) def initialize(self): self.log("------- Hello -------") button = Button(BUTTON_PIN) button.when_pressed = process_button16() def process_button16(): GPIO.output(17,GPIO.HIGH) GPIO.output(27,GPIO.HIGH) self.log("------- Pressed -------")
answer count: 1
accepted answer: http://stackoverflow.com/a/48610693
tagged with: python
has answer: http://stackoverflow.com/a/48610693
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
tagged with: home-automation
type: AnsweredQuestion

http://stackoverflow.com/comment/84049211
comment on: http://stackoverflow.com/q/48527100
type: QuestionComment
has text: You have lists here
score: 0
type: Comment

http://stackoverflow.com/q/48611992
upvote count: 2
type: UnansweredQuestion
has body: I'm trying to log into my school website that utilizes aspx with requests in order to scrape some data. My problem is similar to the one described here: Log in to ASP website using Python&#39;s Requests module However, my form also requires SubmitButton.x and SubmitButton.y and I don't know where to get them form. I tried to pass in values that worked in manual login, but it didn't work. <a href="https://adfslight.resman.pl/LoginPage.aspx?ReturnUrl=%2f%3fwa%3dwsignin1.0%26wtrealm%3dhttps%253a%252f%252fcufs.resman.pl%253a443%252frzeszow%252fAccount%252fLogOn%26wctx%3drm%253d0%2526id%253dADFS%2526ru%253d%25252frzeszow%25252fFS%25252fLS%25253fwa%25253dwsignin1.0%252526wtrealm%25253dhttps%2525253a%2525252f%2525252fuonetplus.resman.pl%2525252frzeszow%2525252fLoginEndpoint.aspx%252526wctx%25253dhttps%2525253a%2525252f%2525252fuonetplus.resman.pl%2525252frzeszow%2525252fLoginEndpoint.aspx%26wct%3d2018-02-04T18%253a54%253a58Z&amp;wa=wsignin1.0&amp;wtrealm=https%3a%2f%2fcufs.resman.pl%3a443%2frzeszow%2fAccount%2fLogOn&amp;wctx=rm%3d0%26id%3dADFS%26ru%3d%252frzeszow%252fFS%252fLS%253fwa%253dwsignin1.0%2526wtrealm%253dhttps%25253a%25252f%25252fuonetplus.resman.pl%25252frzeszow%25252fLoginEndpoint.aspx%2526wctx%253dhttps%25253a%25252f%25252fuonetplus.resman.pl%25252frzeszow%25252fLoginEndpoint.aspx&amp;wct=2018-02-04T18%3a54%3a58Z" rel="nofollow noreferrer">Here's the page form data from successful manual login from bs4 import BeautifulSoup import requests data = {} with requests.Session() as s: page = s.get('https://adfslight.resman.pl/LoginPage.aspx?ReturnUrl=%2f%3fwa%3dwsignin1.0%26wtrealm%3dhttps%253a%252f%252fcufs.resman.pl%253a443%252frzeszow%252fAccount%252fLogOn%26wctx%3drm%253d0%2526id%253dADFS%2526ru%253d%25252frzeszow%25252fFS%25252fLS%25253fwa%25253dwsignin1.0%252526wtrealm%25253dhttps%2525253a%2525252f%2525252fuonetplus.resman.pl%2525252frzeszow%2525252fLoginEndpoint.aspx%252526wctx%25253dhttps%2525253a%2525252f%2525252fuonetplus.resman.pl%2525252frzeszow%2525252fL…
downvote count: 0
tagged with: python
tagged with: python-requests
has title: Login to aspx website using python requests
tagged with: beautifulsoup
score: 2
tagged with: asp.net
has comment: http://stackoverflow.com/comment/84222684
linked to: http://stackoverflow.com/q/39193278
tagged with: authentication
favorite count: 0
type: Question
answer count: 0

http://stackoverflow.com/comment/84042309
comment on: http://stackoverflow.com/a/48517362
type: Comment
has text: and how exactly would you implement it? Be cause inp and weights have different lengths.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48534692
has title: Python 3.6 tk ScrolledText on TopLevel won't insert
has comment: http://stackoverflow.com/comment/84253280
score: 1
has body: I am having issues with the code below when I use Pyinstaller to compile an executable. I am attempting to open a second GUI window using TopLevel, adding a ScrolledText widget to it, then take the output of ipconfig /all and put it in the ScrolledText. I stripped the code down to just the code relevant to this issue. If I run the python file directly, or compile with Pyinstaller without the --windowed command pyinstaller --onefile toolbox.py, then everything appears to work. When I compile with --windowed pyinstaller --onefile --windowed toolbox.py, then the TopLevel window opens and I get the error message listed in the code and the ScrolledText widget is blank. I have confirmed that using a normal string on the txt.insert command does work, so the issues appear to be with the os.popen command. I did attempt to use subprocess.check_output in place of os.popen but I get the same error message. Also, assigning the os.popen command to a variable then inserting the variable in txt.insert has the same result. from tkinter import * from tkinter import ttk from tkinter import messagebox from tkinter import scrolledtext import os import sys def netIPInfo(): """Open a second window, displays output of ipconfig /all.""" window2 = Toplevel() window2.title("NIC IP Info") window2.geometry("663x650") txt = scrolledtext.ScrolledText(window2, width=80, height=40) txt.pack(expand=1, fill="both") try: txt.insert(INSERT, os.popen("ipconfig /all").read()) # ISSUE!! except: e = sys.exc_info() messagebox.showinfo("Error", e) # Error message below # {&lt;class 'OSError'} # {[WinError 6] The handle is invalid} # {&lt;traceback object at 0x02EEB260&gt;} txt.configure(state="disabled") window2.mainloop() # Primary GUI Window window = Tk() window.title("ProTech QST") tab_control = ttk.Notebook(window) tab1 = ttk.Frame(tab_control) tab_control.add(tab1, text='Network') lfr5 = ttk.LabelFrame(tab1, text="Information") lfr5.pack(fill=X) btn30 = Button(lfr5, text="NIC IP Info") btn30.config(widt…
has comment: http://stackoverflow.com/comment/84066523
has comment: http://stackoverflow.com/comment/84084904
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
answer count: 0
tagged with: pyinstaller
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84184337
downvote count: 0
has comment: http://stackoverflow.com/comment/84172988
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84089595

http://stackoverflow.com/comment/84227554
type: Comment
type: AnswerComment
score: 1
has text: @ZulwiyozaPutra custom 404 page works only with DEBUG=False.
comment on: http://stackoverflow.com/a/48605025

http://stackoverflow.com/comment/84036849
comment on: http://stackoverflow.com/q/48520176
has text: @NimeshkaSrimal I have added the code
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84278913
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48586140
has text: After much fiddling I arrived at a similator solution. This looks cleaner.
type: Comment

http://stackoverflow.com/a/48578121
type: Answer
has body: This works, but is not as efficient as possible since it repeats the second_dict.get() for every entry in mydict: mydict = { 'a': [[2,4], [5,6]], 'b': [[1,1], [1,7,9], [6,2,3]], 'c': [['a'], [4,5]], } second_dict = { 'a': [[2,4]], 'b': [[1,1], [1,7,9], [6,2,3]], } diff_dict = { k: [v for v in vals if v not in second_dict.get(k, [])] for k, vals in mydict.items() } # only keep non-empty lists diff_dict = {k: v for k, v in diff_dict.items() if v} diff_dict # {'a': [[5, 6]], 'c': [['a'], [4, 5]]} This is harder to read but a little more efficient: diff_dict = { k: ( [v for v in vals if v not in second_dict[k]] if k in second_dict else vals ) for k, vals in mydict.items() } diff_dict = {k: v for k, v in diff_dict.items() if v} If you are willing to keep your items in sets of tuples instead of lists of lists, you could do this much more easily and efficiently: mydict = { 'a': {(2,4), (5,6)}, 'b': {(1,1), (1,7,9), (6,2,3)}, 'c': {('a',), (4,5)}, } second_dict = { 'a': {(2,4)}, 'b': {(1,1), (1,7,9), (6,2,3)}, } diff_dict = {key: full - second_dict.get(key, set()) for key, full in mydict.items()} diff_dict # {'a': set([(5, 6)]), 'c': set([(4, 5), ('a',)]), 'b': set([])}
score: 0
has comment: http://stackoverflow.com/comment/84158759
answers question: http://stackoverflow.com/q/48577890
has comment: http://stackoverflow.com/comment/84171695

http://stackoverflow.com/comment/84166098
type: AnswerComment
score: 0
type: Comment
has text: Thank you! But for some reason this is not working for values smaller than 0.1 (for example 0.01 and smaller values) the iterations get somehow completely different
comment on: http://stackoverflow.com/a/48573180

http://stackoverflow.com/comment/84215681
comment on: http://stackoverflow.com/q/48608442
has text: @angel.bonev: I get the error `not all arguments converted during string formatting`
score: 0
type: Comment
type: QuestionComment

javascript
tags question: http://stackoverflow.com/q/48639923
tags question: http://stackoverflow.com/q/48633883
tags question: http://stackoverflow.com/q/48635934
tags question: http://stackoverflow.com/q/48536410
tags question: http://stackoverflow.com/q/48589123
tags question: http://stackoverflow.com/q/48562821
tags question: http://stackoverflow.com/q/48540994
tags question: http://stackoverflow.com/q/48567355
tags question: http://stackoverflow.com/q/48578946
tags question: http://stackoverflow.com/q/48613319
tags question: http://stackoverflow.com/q/48505891
tags question: http://stackoverflow.com/q/48536090
tags question: http://stackoverflow.com/q/48517047
tags question: http://stackoverflow.com/q/48630908
tags question: http://stackoverflow.com/q/48552343
tag name: javascript
tags question: http://stackoverflow.com/q/48605535
tags question: http://stackoverflow.com/q/48571923
tags question: http://stackoverflow.com/q/48540319
tags question: http://stackoverflow.com/q/48570334
tags question: http://stackoverflow.com/q/48594829
tags question: http://stackoverflow.com/q/48563969
tags question: http://stackoverflow.com/q/48592060
tags question: http://stackoverflow.com/q/48608248
tags question: http://stackoverflow.com/q/48523195
tags question: http://stackoverflow.com/q/48638868
tags question: http://stackoverflow.com/q/48525768
tags question: http://stackoverflow.com/q/48584932
tags question: http://stackoverflow.com/q/48521306
tags question: http://stackoverflow.com/q/48488827
tags question: http://stackoverflow.com/q/48588120
tags question: http://stackoverflow.com/q/48570320
tags question: http://stackoverflow.com/q/48529455
tags question: http://stackoverflow.com/q/48625138
tags question: http://stackoverflow.com/q/48608601
tags question: http://stackoverflow.com/q/48544581
tags question: http://stackoverflow.com/q/48603339
tags question: http://stackoverflow.com/q/48551674
tags question: http://stackoverflow.com/q/48555847
tags question: http://stackoverflow.com/q/48547743
type: Tag
tags question: http://stackoverflow.com/q/48577271
tags question: http://stackoverflow.com/q/48496568
tags question: http://stackoverflow.com/q/48634711
tags question: http://stackoverflow.com/q/48541033
tags question: http://stackoverflow.com/q/48553638

http://stackoverflow.com/q/48598089
tagged with: sockets
linked to: http://stackoverflow.com/q/26251861
tagged with: python
tagged with: php
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48598219
accepted answer: http://stackoverflow.com/a/48598219
answer count: 1
has body: I need to create a script that listens to a unix socket and forward the incoming stream to a bot. The scripts are unable to connect. The issues seems to be related to the order of things. Proof of case I have created a socket and I am able to write to it. In session 1, I create a listener connection nc -lU /tmp/tg.sck In session 2, I write to the socket. while true; do echo "hello"; sleep 2; done | nc -U /tmp/tg.sck The above only works if I do it in that order. ==> Writing before you have a listener results in an error. Using scripts (does not work) When I replace the listing process with a PHP (or Python) script, the connection is refused because the socket is not opened. $ python test.py Connecting... socket.error: [Errno 111] Connection refused or $ php test.php Warning: fsockopen(): unable to connect to unix:///tmp/tg.sck:-1 (Connection refused) Changing the order of things If I start a working listener using the command nc -lU /tmp/tg.sck then the script does not die, but the writer process does. Listener scripts import socket import sys server_address = '/tmp/tg.sck' # Analogous to TCP (address, port) pair sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(server_address) sock.recv(512) and the php script $fp = fsockopen('unix:///tmp/tg.sck', -1, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)&lt;br /&gt;\n"; } else { while (!feof($fp)) { echo fgets($fp, 4096); } fclose($fp); }
favorite count: 0
type: Question
tagged with: unix-socket
has title: php (or python) listen to unix domain stream socket

http://stackoverflow.com/q/48564256
answer count: 1
has answer: http://stackoverflow.com/a/48564384
has comment: http://stackoverflow.com/comment/84124285
accepted answer: http://stackoverflow.com/a/48564384
has body: I want to import a .txt file with the following data: no a no a b c no change it to a list (or some other data type): mylist = ["no", "yes", "no", "yes", "yes", "yes", "no"] and save it into a new .txt file What I came up with so far: with open("input.txt", "r") as my_file, open("output.txt", "w") as outfile: for line in my_file: words = line.split() for n, i in enumerate(words): if i != "no": words[n] = "yes" i == words[n] outfile.write(i + "\n") As a result, I want a file with the following data: no yes no yes yes yes no
type: Question
has title: Making changes to a file and saving it into another file (python)
tagged with: io
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48512562
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84020174
has answer: http://stackoverflow.com/a/48513895
tagged with: pandas
score: -2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: Question
upvote count: 0
has title: Combining rows from CSV files in pandas list
downvote count: 2
has body: So I am currently in a python class and am struggling with one of the assignments. The goal is to write a program that finds median total home values for each State from a CSV from which lists were imported using pandas and print them in a certain format. One of the first issues I am having, among many others, is combining rows from the CSV. There are multiple rows for the same state, however, I need to find the median for the entire state and am not sure where to even begin. I honestly am not even sure how to tie the rows in the first place, even before combing them.
type: UnansweredQuestion

http://stackoverflow.com/a/48640668
type: Answer
answers question: http://stackoverflow.com/q/48615284
score: -1
has body: Research in perception suggests that percentages of a whole are probably most effectively visualised with stacked bar charts - the cartesian counterpart of pie charts. If your data has a hierarchy as well, then I agree with neilsfw in using a treemap.
downvote count: 1
upvote count: 0

http://stackoverflow.com/q/48555255
has title: How do I trace UnicodeDecodeError: 'utf8' codec can't decode byte 0x85 in position 1950: invalid start byte
type: UnansweredQuestion
has body: Am trying to run an app in development but I keep getting UnicodeDecodeError: 'utf8' codec can't decode byte 0x85 in position 1950: invalid start byte Please how do trace the exact part of the code where this is coming from as I can't make sense of it's error source Below is the full error screen {u'selected': {}, u'categories': {u'ratings': ((1, u'*'), (2, u'**'), (3, u'***'), (4, u'****'), (5, u'*****')), u'genre s': &lt;QuerySet []&gt;, u'actors': &lt;QuerySet []&gt;, u'directors': &lt;QuerySet []&gt;}} Internal Server Error: /movie/ Traceback (most recent call last): File "c:\python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "c:\python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "c:\python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Roland\Documents\Web2\myproject_env\myproject2\movies\views.py", line 70, in movie_list return render(request, "movies/movie_list.html",context) File "c:\python27\lib\site-packages\django\shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "c:\python27\lib\site-packages\django\template\loader.py", line 67, in render_to_string template = get_template(template_name, using=using) File "c:\python27\lib\site-packages\django\template\loader.py", line 21, in get_template return engine.get_template(template_name) File "c:\python27\lib\site-packages\django\template\backends\django.py", line 39, in get_template return Template(self.engine.get_template(template_name), self) File "c:\python27\lib\site-packages\django\template\engine.py", line 162, in get_template template, origin = self.find_template(template_name) File "c:\python27\lib\site-packages\django\template\engine.py", line 136, in find_…
tagged with: django
tagged with: python
tagged with: unicode
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/48555676
answer count: 1
tagged with: utf-8
type: Question

http://stackoverflow.com/comment/84092086
type: QuestionComment
comment on: http://stackoverflow.com/q/48547936
has text: It´s D-1 Determine solar declination (planetographic). as seen on this page https://www.giss.nasa.gov/tools/mars24/help/algorithm.html
score: 0
type: Comment

http://stackoverflow.com/a/48649701
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84297379
accepted answer of: http://stackoverflow.com/q/48642096
score: 2
answers question: http://stackoverflow.com/q/48642096
has comment: http://stackoverflow.com/comment/84297644
type: Answer
has body: You can get the item size directly by the id, but first, you need to click on the size menu sizemenu = driver.find_element_by_id('dropdown_selected_size_name') sizemenu.click() select = driver.find_element_by_id('size_name_1') #Medium size select.click() to check if there is a menu on the page you can add if driver.find_element_by_id('dropdown_selected_size_name') != 0: if driver.find_element_by_id('dropdown_selected_size_name') != 0: sizemenu = driver.find_element_by_id('dropdown_selected_size_name') sizemenu.click() sleep(5) select = driver.find_element_by_id('size_name_1') #medium size select.click() print("select size") else: print("do nothing") sleep(5) button = driver.find_element_by_id('submit.add-to-cart') button.click()
has comment: http://stackoverflow.com/comment/84297352
has comment: http://stackoverflow.com/comment/84297893
has comment: http://stackoverflow.com/comment/84297436
upvote count: 2
has comment: http://stackoverflow.com/comment/84297325

http://stackoverflow.com/q/48578787
has answer: http://stackoverflow.com/a/48579013
has body: I have a data dict which is ordered OrderedDict([('name', ['aaa', 'bbb', 'ccc']), ('age', [10,12,13])]) How to convert this dictionary to PySpark dataframe? Expected Output Name age --- --- aaa 10 bbb 12 ccc 13
has title: Convert Ordered Dictionary to PySpark Dataframe
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48579013
answer count: 1
has comment: http://stackoverflow.com/comment/84154028
tagged with: apache-spark-sql
type: Question
tagged with: apache-spark
tagged with: pyspark
tagged with: python

http://stackoverflow.com/comment/84249852
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48626452
type: AnswerComment
has text: No but thanks, I want the Y-Axis to be the mean number, not the survived ppl number.

http://stackoverflow.com/q/48631155
has body: import os print(os.listdir.__module__) That code outputs posix, but the docs say: The name of the module the function was defined in, or None if unavailable.
tagged with: python
has title: __module__ usage with the os module
has comment: http://stackoverflow.com/comment/84259391
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84259415
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84259410
score: -2
has answer: http://stackoverflow.com/a/48631202
accepted answer: http://stackoverflow.com/a/48631202
answer count: 1

http://stackoverflow.com/q/48513473
tagged with: python
score: -1
tagged with: ubuntu
has body: In Ubuntu 16.04, I would like to install spyder3 on my default python3 without installing Anaconda, but when I launch pip3 and spyder3, I get this error: File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2066, in _rebuild_mod_path orig_path.sort(key=position_in_sys_path) AttributeError: '_NamespacePath' object has no attribute 'sort'
downvote count: 2
upvote count: 1
tagged with: spyder
answer count: 1
has answer: http://stackoverflow.com/a/48513523
linked to: http://stackoverflow.com/q/42184792
favorite count: 0
type: Question
has title: pip3 install spyder with AttributeError: '_NamespacePath'
has comment: http://stackoverflow.com/comment/84047584
type: UnansweredQuestion
tagged with: pip

http://stackoverflow.com/comment/84169092
type: AnswerComment
comment on: http://stackoverflow.com/a/48585825
score: 0
has text: I made an edit. The `jsonData` needs to be made a string before you try to write it
type: Comment

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/48513824

http://stackoverflow.com/comment/83974556
comment on: http://stackoverflow.com/q/48490633
score: 1
type: Comment
has text: It's perfectly normal Python syntax, so again I don't know what you mean. The Model class defines an `objects` attribute which is a Manager, which has a method `.all()`. There is nothing special about this.
type: QuestionComment

http://stackoverflow.com/comment/84308602
type: Comment
comment on: http://stackoverflow.com/a/48650087
type: AnswerComment
has text: It worked for me, you are a life saviour. I have tensorflow, thanks.
score: 1

http://stackoverflow.com/comment/83988819
has text: Yes, exactly. "http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48496552
score: 0

http://stackoverflow.com/a/48528693
type: Answer
score: 0
has body: You can try this : class PlaceHolder(): '''This class represents a place holder for this example''' pass listofnames = ['Michael', 'Jay', 'Derrick'] for next_name in listofnames: globals()[next_name] = PlaceHolder() #create an instance of class PlaceHolder with name=next_name listofnames[listofnames.index(next_name)]=globals()[next_name] #replace the string in list with the class instance
answers question: http://stackoverflow.com/q/48528042

http://stackoverflow.com/comment/84228607
type: QuestionComment
has text: Here is the summary description of "queryset". AAA company added a building site named BBB. The AAA company then added a subcontractor named CCC to the BBB worksite. The CCC subcontractor is a company at the same time. Then the AAA firm wants to list the subcontractor firm attached to the construction site. The "firm_id" field in the "subcontractor" table is linked to the subcontractor firm "id". The parent company is listing according to the worksite in the "subcontractor" table.
type: Comment
comment on: http://stackoverflow.com/q/48615596
score: 0

http://stackoverflow.com/comment/84232904
type: QuestionComment
has text: Hey, I got pulled away... I'm going to gin up a test data set and test the predictions on that, then I'll share something more concrete. Thanks so much for your help - I very much appreciate it. I'm also getting a message from S.O. to avoid extended discussions so I'll move this to PM...
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48612519

http://stackoverflow.com/q/48541018
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84077160
tagged with: pandas
has body: I am reading multiple .csv files and writing them to a new .csv file. I am trying to use an if/else statement in conjunction with pd.insert() to add a new column to the beginning of a dataframe as such: path = r'.../Model_AMs' allFiles = glob.glob(path + "/*.csv") for file_ in allFiles: df = pd.read_csv(file_, header=None).astype(int).transpose().melt() if 'slot' in file_: df.insert(loc=0, column='label', value=0) print('slot file!') else: df.insert(loc=0, column='label', value=1) print('boss file!') pd.DataFrame(dict(zip(df.index, df.value)), index=[0]).to_csv( 'trainingdata.csv', index=False, header=None, mode='a') Currently the new csv file looks something like this: pixel0, pixel1, pixel2,... 0, 1, 1,... I want it to look like this: label, pixel0, pixel1, pixel2,... 1, 0, 1, 1,... Writing the csv files is working as I want it to, however I want to add a new column to the beginning of each dataframe based on what the file name contains. Not sure if I am using the pd.insert() function correctly or maybe the if/else statement is wrong. Any help would be appreciated
answer count: 1
has title: Correct usage of pd.insert() function
has answer: http://stackoverflow.com/a/48541205
type: Question

http://stackoverflow.com/q/48510369
has comment: http://stackoverflow.com/comment/84020343
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48510510
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84020770
has title: Tkinter entry values not updating in toplevel window
tagged with: python
has body: For some reason when I enter something into the entry field in this code and then hit the save button which should call to simply print the name and initials, it does not take what is currently in the entry box. My interpretation is that when the button is clicked to create the window it is taking whatever is called from the code but is not dynamically checking the entry box, even when I click the button save (which I thought would check it). Any idea on how to do this? This is a toplevel window and I created the main root with a function and had a button call this function to open up a new window to edit the name and initials. def SaveChanges(name, initials, person): print(name) print(initials) ## if person.initials in employees: del employees[person.initials] ## employees[str(initials)] = person ## employees[str(initials)].name = str(name) ## ## Save() ## ## CreateMain() def EditEmployee(person): window = Toplevel() l = Label(window,text='Edit Employee') l.grid(row=0,column=0,columnspan=2) nameLabel = Label(window,text='Name:') nameLabel.grid(row=1,column=0) initialsLabel = Label(window,text='Initials:') initialsLabel.grid(row=2,column=0) name = Entry(window) name.grid(row=1,column=1) name = name.get() print(name) initials = Entry(window) initials.grid(row=2,column=1) initials = initials.get() print(initials) save = Button(window, text='Save', command= lambda n=name, i=initials, p=person: SaveChanges(n,i,p)) save.grid(row=3, column=0,columnspan=2)
has comment: http://stackoverflow.com/comment/84020890
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84020807
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/48510510

http://stackoverflow.com/comment/84245348
comment on: http://stackoverflow.com/q/48623615
score: 0
type: Comment
type: QuestionComment
has text: Do you have the python script you wrote returning just Google Response (List), is it returned without commas or simply the way you have it here ?

http://stackoverflow.com/a/48568878
has body: beta = 0.5 #The interpolation parameter params1 = model1.named_parameters() params2 = model2.named_parameters() dict_params2 = dict(params2) for name1, param1 in params1: if name1 in dict_params2: dict_params2[name1].data.copy_(beta*param1.data + (1-beta)*dict_params2[name1].data) model.load_state_dict(dict_params2) Taken from pytorch forums. You could grab the parameters, transform and load them back but make sure the dimensions match. Also I would be really interested in knowing about your findings with these..
type: Answer
upvote count: 15
has comment: http://stackoverflow.com/comment/84151503
type: AcceptedAnswer
score: 15
accepted answer of: http://stackoverflow.com/q/48560227
has comment: http://stackoverflow.com/comment/84156704
downvote count: 0
answers question: http://stackoverflow.com/q/48560227

http://stackoverflow.com/comment/84155005
comment on: http://stackoverflow.com/q/48575325
type: QuestionComment
type: Comment
has text: In the general case I would say no, the edgelength have no significance. But that may also depend on the actual algorithm in use. Judging from the picture there is not way one could possibly tell. Be reminded that this is a Q&A site about programming. See [mcve] and [ask].
score: 0

http://stackoverflow.com/comment/84235018
type: Comment
has text: sorry, that is not what I want to ask. what if i have "d/e/f/g/h/i/j/k/l/m", need ten levels up?
comment on: http://stackoverflow.com/a/48619145
type: AnswerComment
score: 0

http://stackoverflow.com/a/48567185
score: 0
has body: I think you just need to change the &lt; to a >, like this: x = 4 Number = [1 , 2 , 3 , 4 , 5] List = [] while x &gt;= 0 : List.append(Number[x] * 2) x -= 1 print(List) #output [10, 8, 6, 4, 2] The way your current program is written, the while loop never begins. The initial check to see if x &lt;= 0 fails, because you have defined x as 4. If you update the check to say: while x >= 0, the loop starts because the initial condition is true.
answers question: http://stackoverflow.com/q/48567031
type: Answer

http://stackoverflow.com/q/48533781
tagged with: python
accepted answer: http://stackoverflow.com/a/48553247
tagged with: python-decorators
has answer: http://stackoverflow.com/a/48553247
type: Question
has comment: http://stackoverflow.com/comment/84063209
answer count: 2
score: 5
has title: Python Register Class Methods with a Decorator and Inheritance
downvote count: 0
has answer: http://stackoverflow.com/a/48552257
has comment: http://stackoverflow.com/comment/84089587
favorite count: 0
has comment: http://stackoverflow.com/comment/84064988
has comment: http://stackoverflow.com/comment/84089982
has comment: http://stackoverflow.com/comment/84089876
has body: How do I register class methods with a decorator and use inheritance at the same time. I've found a lot of semi-helpful posts/tutorials online, however, I haven't been able to find exactly what I'm looking for. In the process, I think I've confused myself (class decorators vs metaclasses). Here's the expected operation of what I am hoping to build. (FYI using Python 3.6) class Parent: @property def tagged(self): return # TODO: return list of "tagged" methods @property def parent1(self): return 'parent1' @tag @property def parent2(self): return 'parent2' class Child1(Parent): @tag @property def child1_1(self): return 'child1_1' @tag @property def child1_2(self): return 'child1_2' class Child2(Parent): @property def child2_1(self): return 'child2_1' @tag @property def child2_2(self): return 'child2_2' c1 = Child1() c2 = Child2() print(c1.tagged) # expect: ['parent2', 'child1_1', 'child1_2'] print(c2.tagged) # expect: ['parent2', 'child2_2'] EDIT: Here is what I have actually tried (originally omitted to try and keep the post size down) In this attempt, I tried to use a class decorator. I was hoping to use the tag function as a decorator for the class methods to add a attribute to the method. My understanding is that everything in Python is an object (even functions) so adding an arbitrary attribute should be do-able. My thought was to then use the class decorator (tagger) to add a _tagged attribute of the class that would then contain a list of method names that were "tagged". This obviously does not work as I intended. The added attribute to class methods is not "seen" by the class decorator. def tagger(cls): cls._tagged = [] for methodname in dir(cls): method = getattr(cls, methodname) if hasattr(method, 'tagged'): cls._tagged.append(methodname) return cls def tag(f): def decorator(): f.tagged = True return f return decorator @tagger class Parent: @property def tagged(self): return self._tagged def parent1(self): return 'parent1' @tag @property def parent2(self): re…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84096174
upvote count: 5
has comment: http://stackoverflow.com/comment/84089670
possible better answer: http://stackoverflow.com/a/48552257

http://stackoverflow.com/comment/84123168
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48563600
has text: To most commenters: the OP wants a list of variable *names*, with the result of the loop changing the value of the named variables.

http://stackoverflow.com/comment/84154687
has text: "\r" means "moving the cursor to the beginning of the line", it's not related to python, it's for console and escape code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48579190

http://stackoverflow.com/a/50619189
type: Answer
answers question: http://stackoverflow.com/q/48593715
has body: &gt;&gt;&gt; print("\E:\all_study\python\Bearing_fault.mat") \E:ll_study\python\Bearing_fault.mat It's no surprise that path doesn't exist! Every backslash in the string literal is being parsed for escape sequences, such as \a for alert which produces a bell character. In addition, you don't put backslashes in front of drive letters. You can disable the escape sequences for a particular literal using raw strings: &gt;&gt;&gt; print(r"E:\all_study\python\Bearing_fault.mat") E:\all_study\python\Bearing_fault.mat
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/84284254
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48643720
type: Comment
has text: As a matter of fact I do not need those external " at all. It would be great to have values kept intact (with all quotes and commas inside).

http://stackoverflow.com/comment/84053334
type: QuestionComment
has text: hmm yep saw that earlier. But the answers was not clear to me as one below given by @Wen. So I asked it anyway and found a good simple answer. thanks for noting anyway.
score: 0
comment on: http://stackoverflow.com/q/48528190
type: Comment

http://stackoverflow.com/q/48519553
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/48519930
possible better answer: http://stackoverflow.com/a/48519848
tagged with: loops
has answer: http://stackoverflow.com/a/48519848
favorite count: 0
has comment: http://stackoverflow.com/comment/84034157
has comment: http://stackoverflow.com/comment/84033923
type: Question
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/48519930
has body: I am trying to loop over a dataframe. Especially through the date column so means for every date I get the x, y and z values for that date and fill it into my defined function. Somehow I am not sure how i can properly call it. My code looks like the following: import pandas as pd def calc_funct(x, y, z): func = x*y*z return func if __name__ == '__main__': df = pd.read_csv('C:/Data.csv') for column in df: results = calc_funct(df['x'], df['y'], df['z']) print(result) The input looks like the following: date x y z 0 2017-11-11 18 17 7 1 2017-11-11 16 19 3 2 2017-11-11 13 14 2 3 2017-11-11 12 13 1 4 2017-11-11 11 12 9 5 2017-11-11 10 11 10 6 2017-11-11 21 10 11 7 2017-11-12 13 19 12 8 2017-11-13 18 17 12 9 2017-11-14 9 10 20 10 2017-11-15 2 20 13 11 2017-11-18 13 13 9 12 2017-11-19 18 14 16 13 2017-11-20 14 11 19 14 2017-11-21 18 15 19 For date 2017-11-11 I would calculate the values (e.g. add/subtract all values them at that date) and store it e.g. in a list. Then iterate over the next date 2017-11-12 etc...
has title: Loop over one column and fill rows in fucntion Pandas Dataframe Python
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/93827601
type: AnswerComment
has text: The subdirectories and files are present. I am also facing the same issue.
comment on: http://stackoverflow.com/a/49852755
type: Comment
score: 0

hortonworks-sandbox
type: Tag
tag name: hortonworks-sandbox
tags question: http://stackoverflow.com/q/48577943

http://stackoverflow.com/a/48595058
type: Answer
answers question: http://stackoverflow.com/q/48595039
score: 7
type: AcceptedAnswer
downvote count: 0
upvote count: 7
has body: Instead of counting the values yourself: cnt=Counter() in1="4 8 0 3 4 2 0 3".split(" ") for elt in in1: cnt[elt]+=1 You can simply pass in1 to collections.Counter() to do all the counting for you: cnt = Counter(in1) As for turning your code into a list comprehension, you can try this: from collections import Counter in1="4 8 0 3 4 2 0 3".split() cnt = Counter(in1) print([k for k, v in cnt.items() if v &gt; 1]) Which Outputs: ['4', '0', '3'] Note: You also don't need to pass " " to split(), since it defaults to white space.
accepted answer of: http://stackoverflow.com/q/48595039

http://stackoverflow.com/comment/84070206
type: QuestionComment
comment on: http://stackoverflow.com/q/48534047
has text: Your error does not match the code you've posted. Are you sure you have the trailing slash in the blog include pattern in your real code?
score: 0
type: Comment

http://stackoverflow.com/q/48528674
has comment: http://stackoverflow.com/comment/84052447
has title: How to do something based on user input?
downvote count: 2
has body: I am trying to make a simple calculator, and I want the user to choose an operation at the start. I can run it fine, but it won't call the add method. Here is my code: operation = input("Choose an operation: ") def Addition(): print("Hello, world") def ChooseOperation(): if (operation == "Addition"): Addition()
upvote count: 1
has answer: http://stackoverflow.com/a/48528716
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84052439
has comment: http://stackoverflow.com/comment/84059623
tagged with: python
score: -1

http://stackoverflow.com/comment/84219532
score: 0
type: AnswerComment
has text: Please check the serializer edits. I am pretty sure that's what is causing the error as the message is being successfully saved.
comment on: http://stackoverflow.com/a/48611462
type: Comment

http://stackoverflow.com/a/48631216
has comment: http://stackoverflow.com/comment/136222956
answers question: http://stackoverflow.com/q/48631068
has body: You can't use """ anywhere in the value of a triple-quoted string. Not at the start, and not at the end. That's because, after the first three """ opening characters denoting the start of such a string, another sequence of """ is always going to be the end of the string. Your fourth " lies outside of the string object you created, and a single " without a closing " is not a valid string. Python has no other method of knowing when such a string ends. You can't arbitrarily extend the string 'inwards' with additional " characters before the final """, because that'd be indistinguishable from the valid and legal*: &gt;&gt;&gt; """string 1"""" string 2" 'string 1 string 2' If you must include a " before the closing """, escape it. You can do so by preceding it with a backslash: &gt;&gt;&gt; """This is triple-quoted string that ... ends in a single double quote: \"""" 'This is triple-quoted string that\nends in a single double quote: "' Note that there is no such thing as a quadruple-quote string. Python doesn't let you combine " quotes into longer sequences arbitrarily. Only "single quoted" and """triple-quoted""" syntax exists (using " or '). The rules for a triple-quoted string differ from a single-quoted string; newlines are allowed in the former, not in the latter. See the String and Bytes literals section of the reference documentation for more details, which defines the grammar as: shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"' longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""' and explicitly mentions: In triple-quoted literals, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal, i.e. either ' or ".) (bold emphasis mine). * The expression is legal because it consists of two string literals, one with """ quoting, the next with " quoting. Consecutive string literals are automatically concatenated…
upvote count: 9
type: Answer
score: 9
has comment: http://stackoverflow.com/comment/139571633
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48631068

http://stackoverflow.com/a/48613845
accepted answer of: http://stackoverflow.com/q/48613604
answers question: http://stackoverflow.com/q/48613604
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84257020
type: AcceptedAnswer
downvote count: 0
has body: First, the loop around the subscription makes no sense because x is never used and you should only have to subscribe to a topic once. The MQTT client does not poll a topic each time subscribe is called, it notifies the broker it wants all matching messages then just sits back and waits for the broker to send the matching messages it's way until you unsubscribe or disconnect. You should move the subscribe to before the publish then it's set up and waiting for the response messages before the publish happens, which removes any chance of the client missing the message as it's still try to handle setting up the subscription.

http://stackoverflow.com/comment/84242772
type: Comment
score: 1
type: QuestionComment
has text: Please include the complete error message (i.e the complete traceback) in the question. It shows useful information; in particular, it shows the line that generated the error.
comment on: http://stackoverflow.com/q/48622933

http://stackoverflow.com/comment/84176281
comment on: http://stackoverflow.com/q/48589525
score: 1
type: Comment
type: QuestionComment
has text: "doesn't work" isn't very descriptive, but I'm imagining it's due to `IndexError` since `r[4]` doesn't exist in your input?

http://stackoverflow.com/comment/88169237
score: 0
type: AnswerComment
has text: `StratifiedKFold` would normally use the target, but in my particular shortcut, I'm passing 0's for the target, so you're right
comment on: http://stackoverflow.com/a/49749122
type: Comment

http://stackoverflow.com/a/59936778
type: Answer
has body: As others have mentioned, it may be a PATH issue. However, if you're still able to run other conda commands then you may need to either conda update conda or delete conda and reinstall. In my case, I was running miniconda which I believe simply did not contain the activate binary. Running conda activate instead of source activate solved my issues.
score: 0
answers question: http://stackoverflow.com/q/48632882

http://stackoverflow.com/comment/84022661
has text: My question is, how do you get `7 8 9` for the first 3 rows, and `10 11 12` for the remaining rows in `b`?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48513721

http://stackoverflow.com/comment/84020343
has text: Please provide a [mcve]. Above code does nothing by itself.
comment on: http://stackoverflow.com/q/48510369
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84205516
comment on: http://stackoverflow.com/a/48604445
has text: Awesome Wen! I forgot about this method, I've seen MaxU use that method also. +1
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84267137
score: 1
comment on: http://stackoverflow.com/a/48635138
type: Comment
has text: arr.count('ky') maybe a little problem... if s = 'kkyykymkyyk', arr will be ['k', 'kym', 'k'], so sum(['ky' in i for i in arr]) will be a good way
type: AnswerComment

http://stackoverflow.com/comment/84070107
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48537563
has text: This is not a well explained question. Instead of pasting your code, try explaining what exactly it is you want. Give an example of the 2D array and what maximum sum means for you.

http://stackoverflow.com/q/48567360
has answer: http://stackoverflow.com/a/48567398
type: UnansweredQuestion
has body: I have a data frame with several NaN values like so: first second 0 1.0 3.0 1 2.0 NaN 2 NaN 5.0 and another with lookup values: fill second 200 first 100 Is there a way to replace the NaN values with the fill values based on the column name to get this?: first second 0 1.0 3.0 1 2.0 200 2 100 5.0 This is just an example, as I'm trying to do it on a much larger dataframe. I know that I can rearrange the fields in the dataframes so that the indices match up and I could use pd.where, but I'm wondering if there's a way to make the match just based on column name.
has title: Reassign NaN based on column name in Pandas
tagged with: python
score: 0
tagged with: pandas
answer count: 1
type: Question

http://stackoverflow.com/comment/84233588
has text: have you tried flask migrate?? it can help to intitialize database in production also
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48618325
score: 0

http://stackoverflow.com/comment/84250710
type: Comment
has text: I am really confused, why need multiindex? `raw_data.groupby('Age_group')['Survived'].mean().plot(kind='bar', stacked=False)` does not work?
comment on: http://stackoverflow.com/a/48626524
type: AnswerComment
score: 0

http://stackoverflow.com/q/48625430
favorite count: 0
type: Question
tagged with: statsmodels
tagged with: python
accepted answer: http://stackoverflow.com/a/48625503
has answer: http://stackoverflow.com/a/48625503
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2
downvote count: 0
answer count: 1
has body: I have a time series data frame with x and y as columns name. In my dataframe y is incomplete series and x is complete series. I tried to fit linear regression model between x and y. My intetion is to fill data gap by usig this model. my sample codes are: import statsmodels.formula.api as sm result = sm.ols(formula="y ~ x", data=df_rg).fit() df_rg['y'][df_rg['y'].fillna(predict(df_rg['x']) where df_rg is my dataframe with datetime as an index. my dataframe looks like: date x y 1957-07-31 18.845161 NaN 1957-08-31 18.080645 NaN 1957-09-30 16.156667 NaN 1957-10-31 12.324194 NaN 1957-11-30 8.948333 NaN 1957-12-31 6.253226 NaN ............................. ............................. 2015-03-31 8.316129 20.088710 2015-04-30 10.408333 22.203333 2015-05-31 14.832258 25.258065 2015-06-30 16.815000 26.453333 2015-07-31 18.141935 26.835484 2015-08-31 18.450000 26.637097 2015-09-30 17.016667 26.513333 2015-10-31 11.898387 22.906452 2015-11-30 9.133333 19.376667 2015-12-31 5.366129 14.441935
has title: working with missing data in pandas python

http://stackoverflow.com/comment/84132749
score: 0
comment on: http://stackoverflow.com/a/48553175
type: Comment
has text: Thank you. Works very well.
type: AnswerComment

http://stackoverflow.com/q/48552962
has body: I have been successful solving for an unknown variable with solve() Code here: x = 1000 y = Symbol('y') w = 2.84 * x &gt; x + y, 1.7 * y &gt; x + y solve(w) Now I am trying to get the same result from a Pandas dataframe, unsuccessfully though. df = pd.DataFrame({'A': pd.Series([2.84]),'B': pd.Series([1.7])}) A = Symbol('A') B = Symbol('B') C = 1000 y = Symbol('y') expr = A * C &gt; C + y, B * y &gt; C + y f = lambdify([A,B],expr, modules="sympy") f(df['A'],df['B']) I get the error - NameError: name 'y' is not defined Which is weird because 'y' is what I'm searching for.
tagged with: lambdify
tagged with: sympy
type: UnansweredQuestion
answer count: 1
has title: Sympy Lambdify - solving for unknown variable from two inequalities
has answer: http://stackoverflow.com/a/48553159
type: Question
score: 0
tagged with: python

http://stackoverflow.com/comment/84135798
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48569731
type: QuestionComment
has text: Possible duplicate of [Communicating end of Queue](https://stackoverflow.com/questions/3605188/communicating-end-of-queue)

http://stackoverflow.com/comment/84202213
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48593999
has text: Sorry DYZ, I am pretty new here. I was trying to use a lambda that splits from one the sub strings and apply it to the panda, but it wasn't working. The response provided by jezrael worked

http://stackoverflow.com/a/48515207
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48515176
has body: Convert both to datetime (very powerful with dates). dt_date = datetime.datetime(2017, 10, 10, 10, 10, 10) str_date = 'Thu, 18 Jan 2018 15:50:49 -0500' pd.to_datetime([dt_date,str_date]) Output: DatetimeIndex(['2017-10-10 10:10:10', '2018-01-18 20:50:49']

memory
tags question: http://stackoverflow.com/q/48492079
tags question: http://stackoverflow.com/q/48516696
tag name: memory
type: Tag
tags question: http://stackoverflow.com/q/48530970
tags question: http://stackoverflow.com/q/48544692
tags question: http://stackoverflow.com/q/48500764
tags question: http://stackoverflow.com/q/48582506

http://stackoverflow.com/comment/84145515
has text: While we are at it, please don't use `for i in range(len(n))`. Just use `for i in n` and if you need the index, use `for i, item in enumerate(n)`
score: 0
comment on: http://stackoverflow.com/q/48573742
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48610277
score: 4
accepted answer of: http://stackoverflow.com/q/48610257
has body: Solution There are better ways of doing this but given your code structure you can use else. See the docs. num = input("input your number to be factorialised here!: ") try: num1 = int(num) except ValueError: print("That's not a number!") else: if num1 &lt; 0: print("You can't factorialise a negative number") elif num1 == 0: print("the factorial of 0 is 1") else: ans = 1 for i in range(1,num1+1): ans = ans * i print("the factorial of", num, "is", ans) The else clause only executes if no exceptions are thrown. Suggestions So as not to give away answers to your homework, here are a couple suggestions that you should take a look at to clean up your code: Can you use range more efficiently? Hint: you can iterate over decreasing numbers by setting the step to a negative integer. Can you find a way to get rid of the check num1 == 0?
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48610257
downvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48625138
has body: I've been trying to scrape some raw XML data from an internal company site (url excluded for security purposes). I am currently using selenium and beautifulsoup to do so (but am open to any other options). When accessing the site manually, I am prompted with a javascript browser alert for a username and password (see picture). My attempt to automatically validate credentials is below (does not pass authentication): def main(): #gets specified list of direct reports # username:password@ url ="http://{username}:{password}@myURL.com" driver.get(url) html = driver.page_source soup = BeautifulSoup(html, "lxml") # parsing logic follows ... However, when the script runs I still have to manually enter the username and password in the browsing window controlled by chromedriver and then the rest of the program runs as expected.. Is there a way avoid this manually entry? I've also tried solutions around driver.alert and sending keys &amp; credentials to the browser to no avail.. (I know this may be difficult because the site is not accessible outside of the network, any insight is appreciated!) Edit: I should mention this method was working a couple weeks ago, but following a chrome update no longer does..
answer count: 1
tagged with: selenium
downvote count: 0
tagged with: authentication
has comment: http://stackoverflow.com/comment/84247721
favorite count: 0
has title: Webscraping an internal site that requires authentication w/ Javascript alert
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/48625507
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/84254198
has comment: http://stackoverflow.com/comment/84248198
has answer: http://stackoverflow.com/a/48625507
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/45328654
has comment: http://stackoverflow.com/comment/84247295
upvote count: 3

multi-gpu
type: Tag
tags question: http://stackoverflow.com/q/48496612
tag name: multi-gpu

http://stackoverflow.com/q/48626673
has answer: http://stackoverflow.com/a/58579651
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: python-2.7
answer count: 2
tagged with: snmp
score: 1
has body: I am using a Windows machine for Python development. When I try to pip install easysnmp It throws an error: Failed building wheel for easysnmp Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\infini~1\\appdata\\local\\temp\\pip-build-r_bb9x\\easysnmp\\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\infini~1\appdata\local\temp\pip-0jzdkr-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\infini~1\appdata\local\temp\pip-build-r_bb9x\easysnmp\ Has anyone faced the same issue?
downvote count: 0
has answer: http://stackoverflow.com/a/48627846
upvote count: 1
has title: Unable to install easysnmp in Python

command-line-interface
tags question: http://stackoverflow.com/q/48604754
tags question: http://stackoverflow.com/q/48580822
tags question: http://stackoverflow.com/q/48635649
tag name: command-line-interface
type: Tag
tags question: http://stackoverflow.com/q/48619517

http://stackoverflow.com/q/48509419
has answer: http://stackoverflow.com/a/48510497
tagged with: tensor
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/74345583
tagged with: tensorflow
favorite count: 0
type: Question
score: 1
has body: I try to apply a convolutional layer to a picture of shape [256,256,3] a have an error when I user the tensor of the image directly conv1 = conv2d(input,W_conv1) +b_conv1 #&lt;=== error error message: ValueError: Shape must be rank 4 but is rank 3 for 'Conv2D' (op: 'Conv2D') with input shapes: [256,256,3], [3,3,3,1]. but when I reshape the function conv2d work normally x_image = tf.reshape(input,[-1,256,256,3]) conv1 = conv2d(x_image,W_conv1) +b_conv1 if I must reshape the tensor what the best value to reshape in my case and why? import tensorflow as tf import numpy as np from PIL import Image def img_to_tensor(img) : return tf.convert_to_tensor(img, np.float32) def weight_generater(shape): return tf.Variable(tf.truncated_normal(shape,stddev=0.1)) def bias_generater(shape): return tf.Variable(tf.constant(.1,shape=shape)) def conv2d(x,W): return tf.nn.conv2d(x,W,[1,1,1,1],'SAME') def pool_max_2x2(x): return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,1,1,1],padding='SAME') #read image img = Image.open("img.tif") sess = tf.InteractiveSession() #convetir image to tensor input = img_to_tensor(img).eval() #print(input) # get img dimension img_dimension = tf.shape(input).eval() print(img_dimension) height,width,channel=img_dimension filter_size = 3 feature_map = 32 x = tf.placeholder(tf.float32,shape=[height*width*channel]) y = tf.placeholder(tf.float32,shape=21) # generate weigh [kernal size, kernal size,channel,number of filters] W_conv1 = weight_generater([filter_size,filter_size,channel,1]) #for each filter W has his specific bais b_conv1 = bias_generater([feature_map]) """ I must reshape the picture x_image = tf.reshape(input,[-1,256,256,3]) """ conv1 = conv2d(input,W_conv1) +b_conv1 #&lt;=== error h_conv1 = tf.nn.relu(conv1) h_pool1 = pool_max_2x2(h_conv1) layer1_dimension = tf.shape(h_pool1).eval() print(layer1_dimension)
tagged with: reshape
tagged with: python
has title: why I must reshape one image to [n,height,width,channel] in CNN
accepted answer: http://stackoverflow.com/a/48510497
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74345583
answer count: 2
tagged with: conv-neural-network

http://stackoverflow.com/comment/84016293
comment on: http://stackoverflow.com/q/48510641
type: QuestionComment
has text: provide a more testable, extended input string which covers all the conditions. Then, post the expected result
score: 0
type: Comment

http://stackoverflow.com/comment/84077067
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48540642
has text: Thanks for the answer. But I do not quite fit this. I edited the question, because I did not set it clear. I need exactly json with the same keys

http://stackoverflow.com/a/48533504
has body: Use head(...) after reindex(...). cap10 = cap.head(10).reindex(index=cap['id']) means you extract the first 10 rows then apply the full length of index later. Change them to cap10 = cap.reindex(index=cap['id']).head(10).
type: Answer
score: -1
answers question: http://stackoverflow.com/q/48533286
upvote count: 0
accepted answer of: http://stackoverflow.com/q/48533286
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/84158844
has text: what happens if you do fig.savefig instead of plt.savefig?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48579947

http://stackoverflow.com/comment/83979343
type: Comment
score: 0
type: AnswerComment
has text: This actually does not solve my issue. Would you be able to use the stackoverflow chat to discuss this? If not no biggie. But if I change my df df = pd.DataFrame({'rate': [100, 104.9,105, 99, 110, 130, 120, 98]}) to then it doesn't show that 3 is the big_change for 1. Does that make sense?
comment on: http://stackoverflow.com/a/48491963

http://stackoverflow.com/comment/84029996
comment on: http://stackoverflow.com/q/48517437
type: Comment
has text: What error message did you get when using `lxml`? Would you mind showing your codes?
score: 0
type: QuestionComment

http://stackoverflow.com/a/48525334
has comment: http://stackoverflow.com/comment/84047440
has comment: http://stackoverflow.com/comment/84047487
type: Answer
has comment: http://stackoverflow.com/comment/84046997
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48524920
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84047545
answers question: http://stackoverflow.com/q/48524920
has comment: http://stackoverflow.com/comment/84046550
has body: class AddSubnet(CreateView): site_id = self.kwargs['site_id'] site = get_object_or_404(SiteData, pk=site_id) You can't access self like this in the class definition. This code runs when the module is loaded. There isn't a request yet, so self.kwargs does not exist. You could move the code into the dispatch method instead: @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(AddSubnet, self).dispatch(*args, **kwargs) Then use self.site_id and self.site in other methods.
has comment: http://stackoverflow.com/comment/84047694
has comment: http://stackoverflow.com/comment/84047457
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/84046686

http://stackoverflow.com/q/48632580
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84262362
has title: map dictionary value to the value in another dictionary in the same data file
downvote count: 1
favorite count: 0
has body: I'm working with a data set that contains multiple dictionaries. I want to map the value of one dictionary to the value of another dictionary. They both have the same key name. I have tried: df_file['dict_name1']['name_of_key'].map(df_file['dict_name_2] I have also substituted 'name_of_key' with its index. Thanks in advance
type: Question
has comment: http://stackoverflow.com/comment/84262365
has comment: http://stackoverflow.com/comment/84262372
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84262363
has answer: http://stackoverflow.com/a/48637450
tagged with: python
score: -1
tagged with: dictionary
tagged with: mapping

http://stackoverflow.com/q/48515746
has answer: http://stackoverflow.com/a/48515935
possible better answer: http://stackoverflow.com/a/48515975
answer count: 4
has body: I want to get the max() nubmer in a list and then pop it to another list, (list1). x = [66,1,4,3,6,55] list1 = [] for i in x: x.pop(max(x)) #poped item saved to list1 print(list1) This is my approach but i get the error " pop index out of range". What am i doing wrong ? And i really dont know how to further pop() an item and return it to an empty list.The result should be a list1 with numbers from highest to lowest. Please, dont post any other algorithm with built in functions like sort(). Thanks.
has answer: http://stackoverflow.com/a/48515975
has answer: http://stackoverflow.com/a/48515794
has title: Pop a largest number in a list to another list, python
upvote count: 3
tagged with: max
accepted answer: http://stackoverflow.com/a/48515779
favorite count: 0
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48515779
tagged with: list
has comment: http://stackoverflow.com/comment/84025697
downvote count: 3
tagged with: python

http://stackoverflow.com/a/48578575
answers question: http://stackoverflow.com/q/48570602
type: AcceptedAnswer
has body: I prefer not to use text-based commands. Instead, you can assign callbacks. One option to try is using lambda (since you want to pass your own argument): cmds.button(label='Click me', command=lambda x:printTxtField(whatUSay))
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48570602

http://stackoverflow.com/q/48579238
has body: to the dataframe df1 df1=pd.DataFrame(data=[[1,2,3],[2,4,5],[3,6,7],[1,2,3],[1,4,5],[2,6,7]],columns=['day','d','c'],index=[32,32,32,44,55,55]) print(df1) day d c 32 1 2 3 32 2 4 5 32 3 6 7 44 1 2 3 55 1 4 5 55 2 6 7 I would like to add as many rows as necessary in order to have for each index the column days that goes from 1 to 5. The other columns should be filled with NaN starting from day 1 df2=pd.DataFrame(data=[[1,np.nan,np.nan],[2,np.nan,np.nan],[3,2,3],[4,4,5],[5,6,7], [1,np.nan,np.nan],[2,np.nan,np.nan],[3,np.nan,np.nan],[4,np.nan,np.nan],[5,2,3], [1,np.nan,np.nan],[2,np.nan,np.nan],[3,np.nan,np.nan],[4,4,5],[5,6,7]], columns=['day','d','c'],index=[32,32,32,32,32,44,44,44,44,44,55,55,55,55,55]) print(df2) day d c 32 1 NaN NaN 32 2 NaN NaN 32 3 2.0 3.0 32 4 4.0 5.0 32 5 6.0 7.0 44 1 NaN NaN 44 2 NaN NaN 44 3 NaN NaN 44 4 NaN NaN 44 5 2.0 3.0 55 1 NaN NaN 55 2 NaN NaN 55 3 NaN NaN 55 4 4.0 5.0 55 5 6.0 7.0
downvote count: 0
has title: pandas dataframe filling missing rows with nan
upvote count: 1
answer count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/48579281
accepted answer: http://stackoverflow.com/a/48579281
type: Question

http://stackoverflow.com/q/48619547
possible better answer: http://stackoverflow.com/a/48620708
has title: Concatenate arrays
has answer: http://stackoverflow.com/a/48620708
linked to: http://stackoverflow.com/q/45927263
downvote count: 3
has comment: http://stackoverflow.com/comment/84239206
tagged with: python
tagged with: numpy
answer count: 2
has body: I have the following arrays with shape (53248, 1) and (2,1). array1 = data["Acceleration"].values.reshape((-1,1)) array2 = np.matlib.repmat(0,2,1) I want to concatenate them like twf=np.concatenate(array1,array2) Where data["Acceleration"] is a panda series. The reason why I apply the reshape function is to obtain a (53248,1) array shape instead of (53248,). TypeError: only integer scalar arrays can be converted to a scalar index Thanks
tagged with: concatenation
upvote count: 0
score: -3
accepted answer: http://stackoverflow.com/a/48627550
has comment: http://stackoverflow.com/comment/84238379
has comment: http://stackoverflow.com/comment/84237580
has answer: http://stackoverflow.com/a/48627550
favorite count: 0
tagged with: series
type: Question
has comment: http://stackoverflow.com/comment/84236221
type: AnsweredQuestion

http://stackoverflow.com/q/48571918
answer count: 3
has comment: http://stackoverflow.com/comment/84141202
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84140706
has answer: http://stackoverflow.com/a/48572001
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48573114
tagged with: pandas
linked to: http://stackoverflow.com/q/20461165
score: 1
tagged with: python
has body: I have a feeling this is very simple but I am having a major issue with this. Say I have the following dataframe in pandas. price ordersize 0 0.139664 6.051679 1 0.139665 2.358634 2 0.139665 2.618828 3 0.139665 27.240000 4 0.139665 0.040661 5 0.140060 3.000000 6 0.140100 1.463016 7 0.140128 0.020000 8 0.140418 85.000000 9 0.140427 7.000000 This is an orderbook for BCHBTC As you can see starting at index 1 to index 5 we see a number of orders at the same price. I need to take this input and get it to bin the data so it outputs another dataframe like this. price ordersize 0 0.139664 6.051679 1 0.139665 32.258123 2 0.140060 3.000000 3 0.140100 1.463016 4 0.140128 0.020000 5 0.140418 85.000000 6 0.140427 7.000000 I have tried using groupby and other things but It is not giving me the correct output, or gives it in a very weird formating that is hard to work with. If I could get some help with this that would be much appreciated.
has answer: http://stackoverflow.com/a/48572098
has title: Pandas Bining and Group By

imap
tags question: http://stackoverflow.com/q/48560084
type: Tag
tag name: imap
tags question: http://stackoverflow.com/q/48562935

http://stackoverflow.com/q/48513802
has comment: http://stackoverflow.com/comment/84022300
has comment: http://stackoverflow.com/comment/84022726
tagged with: python
has answer: http://stackoverflow.com/a/48514536
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48514160
type: Question
tagged with: numpy
has body: Given my nested for loops that computes an array as shown, how can I write this out in Numpy without using any loops? for i in range(self.output): for j in range(self.input): for k in range(self.hidden): #self.delta_wh[i, j, k] = -self.output_deltas[i]*self.wo[k, i] * self.dsigneth[k] * self.outi[j]
tagged with: for-loop
has title: Numpy. Multiply multiple arrays to make 3D array
type: UnansweredQuestion

http://stackoverflow.com/q/48612379
has body: I am trying to use numba recently to speedup parts of my code in python. I was trying to run function 1 from inside function 2 while they are both compiled with numba but it is not working. Here is my code: import numba as nb from math import acos from time import time @nb.jit("void()") def myfunc(): s = 0 for i in range(10000000): s += acos(0.5) print('The sum is: ', s) @nb.jit("void()") def myfunc2(): myfunc() tic = time() myfunc2() toc = time() print(toc-tic) When I call myfunc() the code works and I get a result much faster than when I am not using numba. However, when I call the myfunc2 I see this error: File "~/.spyder-py3/temp.py", line 22, in &lt;module&gt; myfunc2() RuntimeError: missing Environment Anybody has any ideas why calling a function from insdie another is not working in this case?
score: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48612579
accepted answer: http://stackoverflow.com/a/48612579
upvote count: 11
favorite count: 0
type: Question
tagged with: jit
has title: Running nested functions using numba
tagged with: numba
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/a/48580380
answers question: http://stackoverflow.com/q/48580201
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/84157147
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48580201
downvote count: 0
has body: Do not try and dynamically name variables. This is bad practice, will make your code intractable. A better alternative is to use dictionaries, as so: v = {} for vec in ['country', 'seg']: v[vec] = temp[vec].values
has comment: http://stackoverflow.com/comment/84157081

http://stackoverflow.com/a/48594313
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48592572
answers question: http://stackoverflow.com/q/48592572
type: AcceptedAnswer
downvote count: 0
score: 6
has body: Try the below code to populate the result, if you considered to select view all stores option. import requests from bs4 import BeautifulSoup FormData={ 'submitAllStores':'View All Stores' } with requests.Session() as s: s.headers = {"User-Agent":"Mozilla/5.0"} res = s.post("http://www.health.state.mn.us/divs/cfh/wic/wicstores/index.cfm",data=FormData) soup = BeautifulSoup(res.text, 'lxml') for item in soup.select(".info"): shopname = item.select_one(".info-service").text print(shopname) Partial output: 1st Quality Market 33rd Meat &amp; Grocery 52 Market And Trading 75 Market And Deli 7th Grocery 9th Ave X-Press
type: Answer

http://stackoverflow.com/comment/84005556
has text: `read_lock` and `write_lock` are the same Lock instance.
comment on: http://stackoverflow.com/q/48505658
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/48505354
answers question: http://stackoverflow.com/q/48505013
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84006847
has body: Let's try this, using apply and rebuild series with date_range, then resample to fill missing time populated with NaN from asfreq: df.apply(lambda x: pd.Series(index=pd.date_range(x['start'], x['end'], freq='S'), data=x['status']), axis=1)\ .T\ .stack().reset_index(level=1, drop=True)\ .resample('S').asfreq() Output: 2017-01-01 13:09:01 OK 2017-01-01 13:09:02 OK 2017-01-01 13:09:03 OK 2017-01-01 13:09:04 OK 2017-01-01 13:09:05 OK 2017-01-01 13:09:06 NaN 2017-01-01 13:09:07 ERROR 2017-01-01 13:09:08 ERROR 2017-01-01 13:09:09 ERROR 2017-01-01 13:09:10 NaN 2017-01-01 13:09:11 NaN 2017-01-01 13:09:12 OK 2017-01-01 13:09:13 OK 2017-01-01 13:09:14 OK Freq: S, dtype: object
type: Answer

http://stackoverflow.com/comment/84023896
comment on: http://stackoverflow.com/q/48514673
score: 0
type: Comment
type: QuestionComment
has text: It may seem laborious, but have you tried converting the letters to numbers, subtracting the value from list 2, then converting back to letters?

threadpool
tags question: http://stackoverflow.com/q/48532301
type: Tag
tag name: threadpool

http://stackoverflow.com/a/48550868
type: Answer
upvote count: 3
has body: This way is a pretty fool-proof way to install pip for a specific python interpreter, when you have a big mess of them on the machine: $ curl https://bootstrap.pypa.io/get-pip.py &gt; /tmp/get_pip.py $ my_python_interpreter /tmp/get_pip.py Then: $ my_python_interpreter -m pip install some_dist
score: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48550689
accepted answer of: http://stackoverflow.com/q/48550689

http://stackoverflow.com/comment/84027090
type: AnswerComment
has text: That's like saying *"I want `"foo" = "bar"` to succeed"*
comment on: http://stackoverflow.com/a/48515962
type: Comment
score: 0

http://stackoverflow.com/comment/84049569
type: QuestionComment
comment on: http://stackoverflow.com/q/48523773
has text: `for i in range(arr.shape[0]):` is the preferred way of looping over a range of indices. No difference in speed, just cleaner code.
score: 1
type: Comment

http://stackoverflow.com/a/48554580
has comment: http://stackoverflow.com/comment/84106787
answers question: http://stackoverflow.com/q/48554247
score: 0
has comment: http://stackoverflow.com/comment/84106899
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84115242
type: Answer
accepted answer of: http://stackoverflow.com/q/48554247
has body: if your requirement is : The length of the list should be 8629 and write a for loop such that it only contains numbers between 1 and 7. shouldn't it be like this? from random import * random_list = [] while len(random_list) &lt; 5: random_list.append(randint(1, 7)) print(random_list)

http://stackoverflow.com/a/48583253
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48582862
has body: You can use a hashmap when the key is a word you wish to find and the value is a boolean that says if was found in the sentence or not. if one of the words was not found or a word in the sentence does not exist return false; other wise its true: public class Main { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(scanTheWords("want i pizza") ); System.out.println(scanTheWords("i want pizza") ); System.out.println(scanTheWords("i want a pizza on monday") ); } public static boolean scanTheWords (String sentence) { HashMap&lt;String, Boolean&gt; words = new HashMap&lt;&gt;(); words.put("i", false); words.put("want", false); words.put("pizza", false); String [] senteceWord = sentence.split(" "); for(String s: senteceWord) { if(!words.containsKey(s)) return false; else words.put(s, true); } for ( boolean b : words.values()) { if(b==false) return false; } return true; } } Output true true false

http://stackoverflow.com/comment/84113768
type: Comment
type: QuestionComment
has text: just added an example of the data
comment on: http://stackoverflow.com/q/48558918
score: 0

http://stackoverflow.com/comment/84105687
type: QuestionComment
score: 0
has text: @Wen thanks Wen! but sorry i don't really get your point...dataset click has only two columns click_date and click_count, ofcourse each column has duplicate values...
comment on: http://stackoverflow.com/q/48554588
type: Comment

http://stackoverflow.com/a/58943697
answers question: http://stackoverflow.com/q/48517774
has body: import cv2 start_time_ms = 120000 stop_time_ms = 150000 vidcap = cv2.VideoCapture('/content/Players Hunting on Neymar Lionel Messi Cristiano Ronaldo ● Horror Fouls &amp;amp Tackles HD.mp4') count = 0 success = True vidcap.set(cv2.CAP_PROP_POS_MSEC,start_time_ms) while success and vidcap.get(cv2.CAP_PROP_POS_MSEC) &lt;= stop_time_ms: success, image = vidcap.read() print('Read a new frame: ', success) cv2.imwrite("/content/image/frame%d.jpg" % count, image) count += 1
has comment: http://stackoverflow.com/comment/104152094
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/48567511
type: Answer
has body: Tell your buddy the whole point of .csv files is that they are unstructured apart from the commas separating fields and the newlines demarcating new records. A clue to how useful the .tscv file extension may be at some future point in time is in the title given by the person on github (your link) experimenting with them: "Simpler, streamable, more compact, easier to read, gzip friendlier than JSON. Hopefully..." If your buddy insists on a more human-readable form of data he can transform them pretty easily into xml, or even JSON, and he'll very likely have more joy than following that github post's apparently aborted experiment. That tcsv stuff doesn't look easier to read than well-formatted JSON to me. Though xml seems to win hands-down if written with readability in mind. See http://json.org/example.html.
has comment: http://stackoverflow.com/comment/84132582
score: 0
answers question: http://stackoverflow.com/q/48567355

http://stackoverflow.com/q/48498824
has comment: http://stackoverflow.com/comment/83991163
tagged with: colors
has body: I'd like a quick visual cue when printing a numpy array of floats to console. How can I use colors to indicate positivity/negativity? I've found this hacky way of changing the color of the console, but I'm not sure it's helpful in my case: &gt;&gt;&gt;YELLOW = '\033[93m' &gt;&gt;&gt;ENDCOLOR = '\033[0m' &gt;&gt;&gt;print(YELLOW+'hello'+ENDCOLOR) hello # &lt;-- this is yellow &gt;&gt;&gt;this is in your regular console color but if you leave out the last string: &gt;&gt;&gt;YELLOW = '\033[93m' &gt;&gt;&gt;ENDCOLOR = '\033[0m' &gt;&gt;&gt;print(YELLOW+'hello') hello #&lt;-- it's yellow &gt;&gt;&gt;this is yellow as well, until you print ENDCOLOR
has title: Can I print a numpy array's values in green if positive and red if negative?
accepted answer: http://stackoverflow.com/a/48501440
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48498982
has answer: http://stackoverflow.com/a/48501440
upvote count: 3
tagged with: python
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/48498982
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/48545999
linked to: http://stackoverflow.com/q/2672326
type: AnsweredQuestion
has body: this is my first post on here so please excuse me if I have made any mistakes. So, I was browsing around on the Metasploit page, and I found these strange types of codes. I tried searching it on google and on here, but couldn't find any other questions and answers like I had. I also noticed that Elliot used the method in "Mr. Robot" while programming in Python. I can see that the code is usually used in viruses, but I need to know why. This is the code that I found using this method: buf += "\x5b\x4d\x6f\x76\x69\x65\x50\x6c\x61\x79\x5d\x0d\x0a\x46\x69\x6c\x65\x4e\x61\x6d\x65\x30\x3d\x43\x3a\x5c"
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/48546050
linked to: http://stackoverflow.com/q/261638
has title: What does the "\x5b\x4d\x6f etc.." mean in Python?
has answer: http://stackoverflow.com/a/48546527
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48546527
has comment: http://stackoverflow.com/comment/84087937
has comment: http://stackoverflow.com/comment/84087709
favorite count: 0
type: Question
tagged with: metasploit
has answer: http://stackoverflow.com/a/48546198
tagged with: buffer
has answer: http://stackoverflow.com/a/48546050
tagged with: python

http://stackoverflow.com/q/48580673
accepted answer: http://stackoverflow.com/a/48584905
score: 6
tagged with: aws-lambda
favorite count: 0
has title: How to access file in /tmp directory of AWS Lambda
tagged with: alexa-skills-kit
type: Question
has comment: http://stackoverflow.com/comment/84175598
answer count: 3
has answer: http://stackoverflow.com/a/73642693
tagged with: python
has body: I have downloaded a file from a URL into the /tmp directory of AWS Lambda(as this was the only writable path in Lambda). My motive is to create an Alexa Skill which will download file from an URL. Hence I created a lambda function. How can I access the downloaded file from /tmp folder in lambda? My code is : - #!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import xml.etree.ElementTree as etree from datetime import datetime as dt import os import urllib import requests from urllib.parse import urlparse def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ print('event.session.application.applicationId=' + event['session' ]['application']['applicationId']) # if (event['session']['application']['applicationId'] != # "amzn1.echo-sdk-ams.app.[unique-value-here]"): # raise ValueError("Invalid Application ID") if event['session']['new']: on_session_started({'requestId': event['request']['requestId' ]}, event['session']) if event['request']['type'] == 'LaunchRequest': return on_launch(event['request'], event['session']) elif event['request']['type'] == 'IntentRequest': return on_intent(event['request'], event['session']) elif event['request']['type'] == 'SessionEndedRequest': return on_session_ended(event['request'], event['session']) def on_session_started(session_started_request, session): """ Called when the session starts """ print('on_session_started requestId=' + session_started_request['requestId'] + ', sessionId=' + session['sessionId']) def on_launch(launch_request, session): """ Called when the user launches the skill without specifying what they want """ print('on_launch requestId=' + launch_request['requestId'] + ', sessionId=' + session['sessionId']) # Dispatch to your skill's launch return get_welcome_response() def on_intent(intent_request, session): """ Called when the user specifies an intent f…
upvote count: 6
has answer: http://stackoverflow.com/a/48584905
has answer: http://stackoverflow.com/a/76516656
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/73642693
has comment: http://stackoverflow.com/comment/84164238
downvote count: 0

http://stackoverflow.com/q/48598324
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84193255
has comment: http://stackoverflow.com/comment/84193437
favorite count: 0
tagged with: networkx
type: Question
has comment: http://stackoverflow.com/comment/84193924
possible better answer: http://stackoverflow.com/a/54467310
has body: I'm trying to generate random edges between random nodes but the line of code ab=choice(G.nodes()) is generating errors. import networkx as nx import matplotlib.pyplot as plt from random import choice G=nx.Graph() city_set=['a','b','c','d','e','f','g','h'] for each in city_set: G.add_node(each) ab=choice(G.nodes()) print(ab) Errors C:\Users\DELL\Anaconda2\envs\untitled\python.exe C:/Users/DELL/Documents/PythonPrograms/Beginning/ntwxproject.py Traceback (most recent call last): File "C:/Users/DELL/Documents/PythonPrograms/Beginning/ntwxproject.py", line 10, in ab=choice(G.nodes()) File "C:\Users\DELL\Anaconda2\envs\untitled\lib\random.py", line 259, in choice return seq[i] File "C:\Users\DELL\Anaconda2\envs\untitled\lib\site-packages\networkx\classes\reportviews.py", line 178, in getitem return self._nodes[n] KeyError: 1 Process finished with exit code 1 I'm new to python, help me with it.
accepted answer: http://stackoverflow.com/a/48598649
has answer: http://stackoverflow.com/a/54467310
has comment: http://stackoverflow.com/comment/84193358
has title: g.nodes() from networkx is not working with random.choice()
has answer: http://stackoverflow.com/a/48598649
has answer: http://stackoverflow.com/a/61921055
has comment: http://stackoverflow.com/comment/84193313
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/a/62370262
answers question: http://stackoverflow.com/q/48527267
has body: Although this is an old post, the following could be relevant to someone looking for an answer. My solution is teststring='he was trying to snatch the token from a guy standing on an escalator in the mall' re.findall(r'( the | a | an )', teststring) [' the ', ' a ', ' an ', ' the '] The leading and trailing spaces provide the unique sequence, which is required for the the search so that it can avoid the 'an' embedded inside the word 'standing' for example. You can strip the spaces off from the result set later on for further processing. Thanks
score: 0
type: Answer

http://stackoverflow.com/comment/84204958
comment on: http://stackoverflow.com/a/48604036
has text: @NoticeMeSenpai, not so. Run the code. It works fine. `enumerate()` copies nothing. If you're the one who down-voted this answer, you should retract it ;-)
type: Comment
type: AnswerComment
score: 2

http://stackoverflow.com/comment/84279541
type: QuestionComment
score: 0
has text: Can you show us what the file contains?
type: Comment
comment on: http://stackoverflow.com/q/48641282

http://stackoverflow.com/q/48507679
has answer: http://stackoverflow.com/a/48519005
tagged with: python
has comment: http://stackoverflow.com/comment/84009952
downvote count: 0
has body: I was trying to print the model summary of VGG16 model and also plot the model and save it in a .png file. from keras.applications.vgg16 import VGG16 from keras.utils.vis_utils import plot_model #Creating the object of VGG16 model model=VGG16() print(model.summary()) plot_model(model,to_file='vgg.png') I also installed the below packages as suggested here. pip install pydot pip install graphviz pip install pydot-ng This was run on Python3.5 on a Windows10 machine. Below is the error: Traceback (most recent call last): File "&lt;ipython-input-4-d5d9b64127c4&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Mohanakrishna/Desktop/Work/ObjectDetection.py', wdir='C:/Users/Mohanakrishna/Desktop/Work') File "c:\users\mohanakrishna\appdata\local\programs\python\python35\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "c:\users\mohanakrishna\appdata\local\programs\python\python35\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Mohanakrishna/Desktop/Work/ObjectDetection.py", line 14, in &lt;module&gt; plot_model(model,to_file='vgg.png') File "c:\users\mohanakrishna\appdata\local\programs\python\python35\lib\site-packages\keras\utils\vis_utils.py", line 135, in plot_model dot = model_to_dot(model, show_shapes, show_layer_names, rankdir) File "c:\users\mohanakrishna\appdata\local\programs\python\python35\lib\site-packages\keras\utils\vis_utils.py", line 56, in model_to_dot _check_pydot() File "c:\users\mohanakrishna\appdata\local\programs\python\python35\lib\site-packages\keras\utils\vis_utils.py", line 31, in _check_pydot raise ImportError('Failed to import pydot. You must install pydot' ImportError: Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work.
linked to: http://stackoverflow.com/q/16683390
upvote count: 1
score: 1
answer count: 1
tagged with: keras
linked to: http://stackoverflow.com/q/36886711
has comment: http://stackoverflow.com/comment/84010064
favorite count: 0
type: Question
has title: Failed to import pydot
has comment: http://stackoverflow.com/comment/84013697
has comment: http://stackoverflow.com/comment/84010295
type: UnansweredQuestion

http://stackoverflow.com/a/48583089
downvote count: 0
has comment: http://stackoverflow.com/comment/84193866
upvote count: 17
type: Answer
accepted answer of: http://stackoverflow.com/q/48582986
score: 17
has body: The spectral resolution is determined by the number of points used in the FFT, which is controlled by the nperseg parameter. To increase the resolution you would increase the number of input points per FFT computation. For example, increasing the number of points from the default 256 to double the resolution (i.e. 512 points) you would call scipy.signal.spectrogram like so: f, t, Sxx = signal.spectrogram(x, fs, nperseg=512) Note that you could also use: f, t, Sxx = signal.spectrogram(x, fs, nfft=512) to use more points in the FFT, but not more input point per segment (i.e. zero padding each segment). This would essentially produce a spectrogram where the additional frequency points are interpolated. It wouldn't increase the resolution (i.e. two tones with very similar frequencies wouldn't be any more distinguishable), but the additional points would make the result appear more smooth.
answers question: http://stackoverflow.com/q/48582986
type: AcceptedAnswer

http://stackoverflow.com/q/48506619
tagged with: python
tagged with: numpy
has body: When I run: hist_2d_i = np.histogram2d(df.feature1.iloc[0], df.feature2.iloc[0], bins=\ [binsx, binsy],weights=df.weights.iloc[0]) I get an error: The dimension of bins must be equal to the dimension of the sample x. But if I run: hist_2d_i = np.histogram2d(df.feature1.iloc[0:1], df.feature2.iloc[0:1], bins=\ [binsx, binsy],weights=df.weights.iloc[0:1]) It works as expected. What is the difference? The index runs through the number of samples in the pandas dataframe dataset. isn't [0] == [0:1] as index ?
tagged with: histogram2d
type: AnsweredQuestion
score: 0
has title: numpy 2D Histogram
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48506700
tagged with: pandas
has answer: http://stackoverflow.com/a/48506700

http://stackoverflow.com/a/48596079
has body: If several new windows/tabs might be opened after you navigate to new URL, you might need to use below code to close each window/tab except the base window: # Define the base window current = driver.current_window_handle # Naviagte through list of URLs. No while loop needed for link in links: driver.get(link) time.sleep(6) driver.find_element_by_id("skip_bu2tton").click() # Check each window for window in driver.window_handles: # If window is not a base window if window != current: # ...switch to that window... driver.switch_to.window(window) # ...close it... driver.close() # ...switch back to base window driver.switch_to.window(current)
accepted answer of: http://stackoverflow.com/q/48595792
answers question: http://stackoverflow.com/q/48595792
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83993078
has text: It is not working either. I have tried every single code on the internet but it is not working. I want to write these columns into a excel file after extracting from json. Do you have any idea about that brahh!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48488544
type: Comment

http://stackoverflow.com/a/52732858
answers question: http://stackoverflow.com/q/48531006
downvote count: 0
has body: wxPython on Mac within a virtual environment throws this error, as explained by wxPython website here: https://wiki.wxpython.org/wxPythonVirtualenvOnMac If you are not running it in a virtual environment and still receive this error, try running your script that uses wxpython with "pythonw" instead of "python". Ex: pythonw hello.py ^See section "4.1.2 Running Scripts with a GUI" (on MacOS) from the following page in the Python Docs to see this python quirk explained: https://docs.python.org/3/using/mac.html
score: 18
upvote count: 18
type: Answer

http://stackoverflow.com/comment/84111952
comment on: http://stackoverflow.com/q/48556651
score: 0
type: Comment
type: QuestionComment
has text: Please specify exactly what's not working. And what is `class_='w170 alignL'`? Which part of the page? Read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)

http://stackoverflow.com/a/48553932
has body: Below example should illustrate what's happening. The Loan_Status values are aggregated by Credit_History according to the logic "add up number of Y's and divide by total number of observations". import pandas as pd df = pd.DataFrame([['Y', 'A'], ['N', 'B'], ['Y', 'C'], ['N', 'A'], ['Y', 'C']], columns=['Loan_Status', 'Credit_History']) df.pivot_table(values='Loan_Status', index=['Credit_History'], aggfunc=lambda x: x.map({'Y':1,'N':0}).mean()) # Loan_Status # Credit_History # A 0.5 # B 0.0 # C 1.0
answers question: http://stackoverflow.com/q/48553854
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48553854

http://stackoverflow.com/q/48523138
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/84041695
has body: Could someone translate the following polish notation to its SQL counterpart: ['|', '&amp;amp;', ('is_company','=', True),('parent_id', '=', False),('company_name', '!=', False),('company_name', '!=', '')] My guess is : is_company = True OR parent_id = False AND company_name &lt;&gt; False AND company_name &lt;&gt; '' I could not get the concept of this notation no matter how hard I tried to understand it. Please help. UPDATE I was trying to extend the above notation to be: ((is_company = True AND parent_id = False) OR company_name &lt;&gt; False) AND company_name &lt;&gt; '' AND customer_type_id &lt;&gt; False
upvote count: 6
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
tagged with: odoo-10
has comment: http://stackoverflow.com/comment/84041536
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84041175
has answer: http://stackoverflow.com/a/48525758
favorite count: 0
accepted answer: http://stackoverflow.com/a/48525758
type: Question
has comment: http://stackoverflow.com/comment/84048485
has comment: http://stackoverflow.com/comment/84042689
tagged with: polish-notation
has title: I don´t understand Normal Polish Notation (NPN or PN). How to build a complex domain in Odoo?
has comment: http://stackoverflow.com/comment/84042467
tagged with: odoo
has comment: http://stackoverflow.com/comment/84043838
has comment: http://stackoverflow.com/comment/84066065

http://stackoverflow.com/comment/84330203
type: Comment
has text: Thanks for the input. I am talking about several people using the same physical terminal. I am trying to protect it from unproficient users, since there will be a lot of installing different kinds of programs etc. The thought was that I could install programs as an admin, and just delete and make new users to "clean" the machine after use. But know I see that what I need is probably to make an .iso/image from the entire OS and just redeploy that weekly.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48597930

http://stackoverflow.com/q/48488723
has title: Detecting the angle of a corner using opencv
has body: I have the following image of a corner: I'm trying to get the angle of the white corner, i.e. the following: So I went through the obvious route to remove the noise Converted the image to grayscale Added some gaussian blur Applied threshold And the result was as follows: Since I want the angle, I needed the lines that make-up this corner, so, of course, I ran canny + hough lines, but here lies the problem, I keep getting multiple false lines using Hough and I have no idea how to filter them out: Is there's any known way to get the confidence of each line so I can only get the correct vertical+horizontal parts of the corner?
has comment: http://stackoverflow.com/comment/83991184
has comment: http://stackoverflow.com/comment/83974762
has answer: http://stackoverflow.com/a/48489377
has answer: http://stackoverflow.com/a/48489958
tagged with: opencv
linked to: http://stackoverflow.com/q/47777585
type: AnsweredQuestion
score: 0
tagged with: hough-transform
possible better answer: http://stackoverflow.com/a/48489377
has comment: http://stackoverflow.com/comment/84588148
tagged with: python
has comment: http://stackoverflow.com/comment/106056174
has comment: http://stackoverflow.com/comment/83975248
type: Question
tagged with: corner-detection
accepted answer: http://stackoverflow.com/a/48489958
answer count: 2

http://stackoverflow.com/q/48495648
favorite count: 0
type: Question
tagged with: instagram-api
tagged with: instagram
has title: How do I get the next page of data from a instagram tag look up
tagged with: python
has answer: http://stackoverflow.com/a/66992482
has answer: http://stackoverflow.com/a/52274732
type: AnsweredQuestion
has body: I can enter the following url to get all the IG posts with the #losangeles tag in them by going/requesting the following endpoint: https://www.instagram.com/explore/tags/losangeles/?__a=1 In the json data returned from this url i can see the page_info attribute and within it there is the has_next_page attribute and that is set equal to true. My question is how do I ammend the above url to get to the next page, and the one after that, and so until I check has_next_page and it is false. It seemed intuitive to try https://www.instagram.com/explore/tags/losangeles/?__a=2 and https://www.instagram.com/explore/tags/losangeles/?__b=1 But neither seem to work. I suspect maybe the end_cursor attribute in the data returned from the original url may be a clue as to what url I need to go to to get to the next page but am not sure. Does anyone know how to do this?
answer count: 3
downvote count: 0
upvote count: 7
score: 7
has answer: http://stackoverflow.com/a/48739367
accepted answer: http://stackoverflow.com/a/48739367
possible better answer: http://stackoverflow.com/a/52274732
tagged with: python-requests

http://stackoverflow.com/comment/138745590
type: AnswerComment
score: 0
type: Comment
has text: No. Don't mess with `/usr/bin`. If you want this, put the symlink in `/usr/local/bin/python`
comment on: http://stackoverflow.com/a/78694878

http://stackoverflow.com/a/48549207
score: 1
answers question: http://stackoverflow.com/q/48548937
type: Answer
has body: import sys import io class MyStream(io.IOBase): def write(self, s): logger.error(s) sys.stderr = MyStream() print('This is an error', stream=sys.stderr) This make all call to sys.stderr go to the logger. The original one is always in sys.__stderr__
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48618905
has body: Pytest catches exceptions in order to know which tests pass and with fail. In order to run my tests inside any IDE I usually add sth. like this to my test script: if __name__ == '__main__': pytest.main() This way I can run my tests like any other script while PyTest specific stuff like fixtures and parametrized functions still work. But now exceptions (AssertionError in particular) are being catched by PyTest and won't let the debugger break for further investigation.. Is there a way to make PyTest not catch exceptions?
tagged with: exception
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84317768
has comment: http://stackoverflow.com/comment/84237175
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/84237528
answer count: 0
tagged with: pytest
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84261313
has comment: http://stackoverflow.com/comment/88746774
has title: How to let Pytest not catch Exceptions
favorite count: 0
type: Question

http://stackoverflow.com/q/48571886
has comment: http://stackoverflow.com/comment/84928564
downvote count: 0
has answer: http://stackoverflow.com/a/74702107
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48935483
answer count: 2
score: 5
type: UnansweredQuestion
has title: WebDriverException when starting chromedriver with user-data-dir argument
upvote count: 5
tagged with: python
tagged with: selenium-chromedriver
has body: My code: from selenium.webdriver.chrome.options import Options from selenium import webdriver opts = Options() opts.add_argument("user-data-dir=/path/to/profiles_dir/user_id") browser = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver", chrome_options=opts) When I start Chromium for user with id = 1 it starts fine and creates a profile directory /path/to/profiles_dir/1. Then I visit some arbitrary site and close the browser. When I execute the above code for the second time, it throws and exception. selenium.common.exceptions.WebDriverException: Message: unknown error: cannot parse internal JSON template: Line: 1, column: 1, Unexpected token. (Driver info: chromedriver=2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881),platform=Linux 4.4.0-112-generic x86_64) Chromium 64.0.3282.119 Built on Ubuntu , running on Ubuntu 16.04 ChromeDriver 2.35 selenium 3.8.1 I googled a lot but could not find a solution for this issue. Why can't I load the browser with the existing user profile dir? What am I doing wrong?

http://stackoverflow.com/comment/83971254
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48489053
has text: I have updated the Question thanks
type: Comment

http://stackoverflow.com/q/48528537
has body: I have two lists, for example: a = [12, 0.2112, 0.2335, 4, 523, -0.55556, 0.212] # accepted value b = [10, -0.0222, 0.5534, 4, 522, -0.99922, 0.877] # experimental value I want to use this formula - |accepted value(a[i]) - experimental value(b[i])| \ accepted value(a[i]) x 100%, and get this result: c = [16.66, 110.51, 137.00, 0.00, 0.191, 78.59, 313.67] How is it possible to do this with the two lists without using numpy?
tagged with: python
has comment: http://stackoverflow.com/comment/84055117
tagged with: percentage
has answer: http://stackoverflow.com/a/48528621
score: -3
has comment: http://stackoverflow.com/comment/84053270
tagged with: list
linked to: http://stackoverflow.com/q/10271484
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84052256
upvote count: 0
downvote count: 3
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84052241
has comment: http://stackoverflow.com/comment/84052776
type: Question
has comment: http://stackoverflow.com/comment/84052328
has comment: http://stackoverflow.com/comment/84079911
has comment: http://stackoverflow.com/comment/84052252
tagged with: compare
has title: How calculate percentage error by comparing two lists for each list's element using Python
accepted answer: http://stackoverflow.com/a/48528621
has comment: http://stackoverflow.com/comment/84052668
has comment: http://stackoverflow.com/comment/84052431

http://stackoverflow.com/a/48572768
answers question: http://stackoverflow.com/q/48572562
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84143111
downvote count: 0
score: 2
has body: Your plotting function needs to accept an Axes object as a parameter. You then create the figure and axes outside of the function: import matplotlib.pyplot as plt import numpy as np def make_layout(data, ax): p, = ax.plot(data, 'o') p.set_markerfacecolor('g') return p So to plot everything on 1 Axes, you'd do: data = data = np.linspace(0,1) fig, ax = plt.subplots(nrows=1, ncols=1) p1 = make_layout(data, ax) p2 = make_layout(data**2, ax) p2.set_markerfacecolor('yellow') If you want separate axes, you'd do something like this: data = data = np.linspace(0,1) fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) p1 = make_layout(data, ax1) p2 = make_layout(data**2, ax2) p2.set_markerfacecolor('yellow')
type: Answer
accepted answer of: http://stackoverflow.com/q/48572562
has comment: http://stackoverflow.com/comment/84142696

http://stackoverflow.com/q/48572541
type: AnsweredQuestion
upvote count: 3
tagged with: spacy
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48590848
favorite count: 0
type: Question
score: 3
has body: Trying to use spacy sentence tokenization for Hebrew. import spacy nlp = spacy.load('he') doc = nlp(text) sents = list(doc.sents) I get: Warning: no model found for 'he' Only loading the 'he' tokenizer. Traceback (most recent call last): ... sents = list(doc.sents) File "spacy/tokens/doc.pyx", line 438, in __get__ (spacy/tokens/doc.cpp:9707) raise ValueError( ValueError: Sentence boundary detection requires the dependency parse, which requires data to be installed. For more info, see the documentation: https://spacy.io/docs/usage what to do?
tagged with: python
has answer: http://stackoverflow.com/a/48590848
has title: spacy sentence tokenization error on Hebrew

http://stackoverflow.com/a/48490621
type: AcceptedAnswer
has body: First, I believe it's not a really good idea to have user.teacher and user.student as a property for two reasons: 1. I assume that a user can be either a student or a teacher, but not both (please correct me if I'm mistaken). You are using get_or_create, so, for instance, if you'll try to access a user teacher property with user being already a student, you will end up in the situation when the user is both a student and a teacher. 2. Django ORM already does this for you: using OneToOneField you can reference Teacher or Student object from your User object as user.teacher or user.student as long as the corresponding User or Teacher exists. You can use hasattr to check if the given user is a teacher or a student: class User(AbstractUser): @property def is_teacher(self): return hasattr(self, 'teacher') @property def is_student(self): return hasattr(self, 'student') Then render your template accordingly: {% if user.is_teacher %} # Do teacher-related logic {% elif user.is_student %} # Do student-related logic {% else %} # This should not be the case, but you may want to display an error message or something {% endif %}
type: Answer
answers question: http://stackoverflow.com/q/48490192
has comment: http://stackoverflow.com/comment/84274056
score: 2
accepted answer of: http://stackoverflow.com/q/48490192
downvote count: 0
has comment: http://stackoverflow.com/comment/84318607
has comment: http://stackoverflow.com/comment/84299504
upvote count: 2

http://stackoverflow.com/q/48636413
type: Question
type: UnansweredQuestion
tagged with: oracle-database
tagged with: python
has title: I get "DPI-1047: 64-bit Oracle Client library cannot be loaded" if I run program in PyCharm using Vagrant(venv)
tagged with: vagrant
has body: I can't solve this problem when I run my test.py in Pycharm IDE previously configured to work with Vagrant machine and I get this error. I use Virtual Env there. Weird thing that I don't have problems when I run it manually into my machine via ssh (python test.py). Here's code of test.py: import cx_Oracle host = '10.210.1.15' port = 1521 sid = 'ORCL' user = 'repdb' password = 'rep1' sql = 'select id from db.device_group dg' dsn = cx_Oracle.makedsn(host, port,sid) conn = cx_Oracle.connect(user, password, dsn) cur = conn.cursor() cur.execute(sql) data = cur.fetchall() print(data)
score: 0
tagged with: cx-oracle
answer count: 1
tagged with: virtualenv
has answer: http://stackoverflow.com/a/48667815

http://stackoverflow.com/comment/84001375
comment on: http://stackoverflow.com/q/48503558
score: 2
has text: Since your are new at coding, I have to stress that debugging is a crucial skillset for any coder, and is something you need to learn early and often. If someone gives you this answer it will only be of limited value; being shown obvious mistakes are only a little instructive. But if you debug your way to a solution you get much more value from what you learn. https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84121212
score: 1
type: Comment
type: QuestionComment
has text: @GarvitJain Actually, sequences have to be independent from transactions as concurrent transactions can create records in the same table.
comment on: http://stackoverflow.com/q/48562582

http://stackoverflow.com/q/48516265
answer count: 2
tagged with: pandas
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84026886
downvote count: 0
has title: Split Names in column
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48516458
has answer: http://stackoverflow.com/a/48516464
has answer: http://stackoverflow.com/a/48516458
has comment: http://stackoverflow.com/comment/84027089
tagged with: python
tagged with: numpy
possible better answer: http://stackoverflow.com/a/48516464
type: AnsweredQuestion
has body: I'm fairly new to python and working with a DataFrame in pandas &amp; numpy from The Movie Database. One of the columns notes the main cast of each movie separated by the pipe symbol (|). I'm trying to find a way to split each individual cast member and list it in its own row with the movie title. I've attached a snippet below of the results I get. tmdb_data = pd.read_csv('tmdb-movies.csv') cast_split = tmdb_data'original_title', 'cast' df = pd.DataFrame(cast_split) df.head() Movie Title &amp; Cast Expected Output: original_title cast 0 Jursassic World Chris Patt 1 Jursassic World Bryce Dallas Howard 2 Jursassic World Irrfan Khan

http://stackoverflow.com/a/48489328
has comment: http://stackoverflow.com/comment/83973083
type: Answer
accepted answer of: http://stackoverflow.com/q/48489301
has body: If values of Month are unique use: df['perc'] = df["Amount"] / df["Amount"].sum() * 100 print (df) Month Amount perc 1 Jan 260 22.203245 2 Feb 179 15.286080 3 Mar 153 13.065756 4 Apr 142 12.126388 5 May 128 10.930828 6 Jun 116 9.906063 7 Jul 71 6.063194 8 Aug 56 4.782237 9 Sep 49 4.184458 10 Oct 17 1.451751 11 Nov 0 0.000000 12 Dec 0 0.000000 If values of Month are duplicated I believe is possible use: print (df) Month Amount 1 Jan 260 1 Jan 100 3 Mar 153 4 Apr 142 5 May 128 6 Jun 116 7 Jul 71 8 Aug 56 9 Sep 49 10 Oct 17 11 Nov 0 12 Dec 0 df = df.groupby('Month', as_index=False, sort=False)["Amount"].sum() df['perc'] = df["Amount"] / df["Amount"].sum() * 100 print (df) Month Amount perc 0 Jan 360 32.967033 1 Mar 153 14.010989 2 Apr 142 13.003663 3 May 128 11.721612 4 Jun 116 10.622711 5 Jul 71 6.501832 6 Aug 56 5.128205 7 Sep 49 4.487179 8 Oct 17 1.556777 9 Nov 0 0.000000 10 Dec 0 0.000000
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83973061
answers question: http://stackoverflow.com/q/48489301
has comment: http://stackoverflow.com/comment/83973002
type: AcceptedAnswer

http://stackoverflow.com/a/48549834
type: Answer
answers question: http://stackoverflow.com/q/48549711
score: 0
has body: Use python's split() function which splits, by default, on all whitespace characters and will give you list of numbers. ratio = input('ratio numbers: ').split() Then, your float conversion &amp; multiplication would work.
has comment: http://stackoverflow.com/comment/84096032

http://stackoverflow.com/q/48554902
downvote count: 0
tagged with: facebook-chatbot
has answer: http://stackoverflow.com/a/48556284
answer count: 1
tagged with: amazon-lex
favorite count: 0
tagged with: aws-lambda
has title: Hyperlink in response card button in Amazon Lex
has body: I am trying to make a response card in amazon lex to give out a response card that has a button that leads to another website. Below is the code that I have used in aws lambda python. I have published the chatbot on facebook messenger. But whenever I select the button in fb messenger, the link in the button does not seem to bring me to the website. Is there any way to make the response card button turn into hyperlink button? def location(intent_request): session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {} return { 'dialogAction': { 'type': 'Close', 'fulfillmentState': 'Fulfilled', 'message': { 'contentType': 'PlainText', 'content': 'Here is a map' }, 'responseCard': { 'version': '17', 'contentType': 'application/vnd.amazonaws.card.generic', 'genericAttachments': [ { 'title': 'Here is a list of hospitals', 'subTitle': 'Below is a map', "buttons":[ { "text":"Show Google Maps", "value":"https://www.google.com/maps/search/?api=1&amp;query=nearby+hospitals" } ] } ] } } }
type: Question
accepted answer: http://stackoverflow.com/a/48556284
tagged with: python
tagged with: amazon-web-services
linked to: http://stackoverflow.com/q/47639131
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/comment/84023192
has text: Your (posted) code also has no error. Have you copied the trace from somewhere else?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48514315

http://stackoverflow.com/comment/84123318
comment on: http://stackoverflow.com/q/48560572
score: 0
type: QuestionComment
has text: `fs.open` is unable to raise `FileNotFoundError`. Can you please post a complete stack trace
type: Comment

filter
tags question: http://stackoverflow.com/q/48512449
tags question: http://stackoverflow.com/q/48550324
type: Tag
tags question: http://stackoverflow.com/q/48503346
tags question: http://stackoverflow.com/q/48609891
tags question: http://stackoverflow.com/q/48549326
tag name: filter
tags question: http://stackoverflow.com/q/48598690
tags question: http://stackoverflow.com/q/48565990
tags question: http://stackoverflow.com/q/48546091

http://stackoverflow.com/comment/84300084
type: AnswerComment
comment on: http://stackoverflow.com/a/48589661
type: Comment
has text: As I wrote in my question and initial comment on your answer, I believe that creating a new sourcing using the Source API is not the answer here. Prior to asking my question, I'd studied the code for `AvroSource` and other examples, and I revisited them over the past few days. I still don't see how it applies in this case. I'll add an answer with the solution I eventually came to yesterday, and you're welcome to see if that seems more reasonable given my use case.
score: 0

http://stackoverflow.com/q/48522054
has comment: http://stackoverflow.com/comment/84038906
has body: I get a queryset from a model that saves the data to a charfield. The charfield is displayed on a form as MultipleChoiceField with a CheckboxSelectMultiple widget. The max amount of choices is 5. I want to count the number of elements in the queryset. Each queryset can vary in the amount of the elements in the list. Now, when I get len of the list, the value is 5 times the amount of elements. Is the list in the dict not a list but something else? When I create a list manually without the queryset and get len of said list, the value is correct. E.g. list with 3 elements returns 3. query = MyModel.objects.all().values('myvalue') print(query[0]) {'myvalue': "['3']"} print(query[1]) {'myvalue': "['1', '4']"} print(query[0]['myvalue'] ['3'] print(query[1]['myvalue'] ['1', '4'] print(len(query[0]['myvalue'])) 5 print(len(query[1]['myvalue'])) 10
tagged with: python
has title: Count elements of list from queryset
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/48522331
has answer: http://stackoverflow.com/a/48522309
has comment: http://stackoverflow.com/comment/84038736
possible better answer: http://stackoverflow.com/a/48522309
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/48522331

http://stackoverflow.com/q/48575425
has title: Can't list youtube videos from playlist
linked to: http://stackoverflow.com/q/14173428
answer count: 1
downvote count: 0
has body: I'm trying to get and store the videos from a youtube playlist into an list in python. I followed the instructions in the docs https://developers.google.com/youtube/v3/docs/playlistItems/list but it cant seem to retrieve the video ID. def list_playlist_localizations(youtube, playlist_id): results = youtube.playlists().list( part='snippet, contentDetails', id=playlist_id, maxResults=5 ).execute() #print results for playlist_item in results['items']: title = playlist_item['snippet']['title'] video_id = playlist_item['snippet']['resourceId']['videoId'] print video_id EDIT: from hyper import HTTPConnection import random import requests playlist_id = "PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG" links = [] token = '' # to get ID to next page CDIQAA # https://stackoverflow.com/questions/14173428/how-to-change-page-results-with-youtube-data-api-v3 - reference s = requests.Session() r = s.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&amp;maxResults=50&amp;playlistId=' + playlist_id + '&amp;key={MY_KEY}') data = r.json() while 'nextPageToken' in data and len(data) &lt; 200: token = data['nextPageToken'] r = s.get('https://www.googleapis.com/youtube/v3/playlistItems?pageToken=' + token + '&amp;part=snippet&amp;maxResults=50&amp;playlistId=' + playlist_id + '&amp;key=AIzaSyAglPb2-eVaoy1muXclkUrfPFtdYEaUcCw') data = r.json() for items in data['items']: links.append('https://www.youtube.com/watch?v=' + items['snippet']['resourceId']['videoId']) r = s.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&amp;maxResults=50&amp;playlistId=' + playlist_id + '&amp;key={MY_KEY}') data = r.json() # Add the remaining links for items in data['items']: links.append('https://www.youtube.com/watch?v=' + items['snippet']['resourceId']['videoId']) ''' for items in links: print items ''' print "num items: " + str(len(links)) print "Random link: " print links[random.randint(0, len(links) - 1)] This is my implementation to generate random youtube links from a playl…
tagged with: python
tagged with: youtube
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48576509
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48576509
upvote count: 2

http://stackoverflow.com/comment/84026224
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48515421
has text: Here is a small [tutorial](https://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html) for your problem

http://stackoverflow.com/comment/84095752
comment on: http://stackoverflow.com/a/48549861
type: AnswerComment
score: 0
has text: I know that , typo
type: Comment

http://stackoverflow.com/comment/84049440
comment on: http://stackoverflow.com/q/48527100
type: Comment
has text: @AmritSingh i am still figuring out the code to answer the second question
type: QuestionComment
score: 0

http://stackoverflow.com/q/48531006
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86149957
tagged with: wxpython
has comment: http://stackoverflow.com/comment/91637336
answer count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/91636993
has title: wxPython: This program needs access to the screen
has answer: http://stackoverflow.com/a/74999343
type: Question
possible better answer: http://stackoverflow.com/a/52732858
upvote count: 20
has comment: http://stackoverflow.com/comment/91636838
has comment: http://stackoverflow.com/comment/91637235
score: 20
has answer: http://stackoverflow.com/a/55893693
has answer: http://stackoverflow.com/a/48533589
has answer: http://stackoverflow.com/a/52732858
accepted answer: http://stackoverflow.com/a/48531638
tagged with: python
has answer: http://stackoverflow.com/a/48531638
has comment: http://stackoverflow.com/comment/91637586
tagged with: wxwidgets
has answer: http://stackoverflow.com/a/67111287
has answer: http://stackoverflow.com/a/66470363
has comment: http://stackoverflow.com/comment/84057449
has body: I'm trying to use the Python GUI wx (installable via pip install wxPython) in the following minimal app: import wx app = wx.App() Running this snippet returns the following: This program needs access to the screen. Please run with a Framework build of python, and only when you are logged in on the main display of your Mac. Does anyone know how to help wx gain "access to the screen", or what a "Framework build of Python" is? I'd be grateful for any help others can offer with these questions!
has comment: http://stackoverflow.com/comment/91636879

http://stackoverflow.com/q/48516371
downvote count: 1
has body: My goal with this script is to import a csv file. Then use the information to run a search query and scrape the results using beautiful soup 4, before export it the scraped info into a different csv file. I have 2 problems though 1st I can't get the While:True statement to work and 2nd and most important. I haven't been successful at increment the row variables. (i.e. Run1 (stl[0]+1) Run2 (stl[1])+1) Run3 (stl[2]+1). import mechanize import cookielib from bs4 import BeautifulSoup import csv While:True ifile = open('license.csv', "rb") reader = csv.reader(ifile) sl1 = [] sl2 = [] for row in reader: sl1.append((row[0])) sl2.append((row[1])) ifile.close() # Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh &gt; 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Want debugging messages? #br.set_debug_http(True) #br.set_debug_redirects(True) #br.set_debug_responses(True) # User-Agent (this is cheating, ok?) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] # Open some site, let's pick a random one, the first that pops in mind: r = br.open('https://secure.utah.gov/llv/search/index.html') html = r.read() # Show the source print html # or print br.response().read() # Show the html title print br.title() # Show the response headers print r.info() # or print br.response().info() # Show the available forms for f in br.forms(): print f # Select the first (index zero) form br.select_form(nr=1) # Let's search br.form['licenseNumberCore']=sl1[0]+1 br.form['licenseNumberFourDigit']=sl2[0]+1 br.submit() print br.response().read() # Looking at some results in link format for l in br.links(url_regex=sl1[0]+1): print l # Testing pr…
favorite count: 0
has answer: http://stackoverflow.com/a/48517960
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/84030291
type: Question
has comment: http://stackoverflow.com/comment/84027184
tagged with: mechanize
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84027104
has title: How do I use a while loop and increment a list variable each time the script is run using python?
tagged with: python
type: UnansweredQuestion
score: -1
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/48517921

http://stackoverflow.com/q/48594148
tagged with: pandas
has body: I have 4-level nested dictionaries and want to convert to pandas data frame or panel data form to extract csv. I want every cell to have information from nested dictionaries. I have nested dictionaries like below, but have more keys and values in actual data. {2008: {'Barack Obama': {1: {'Author': 'Barack Obama', 'City': [], 'Title': 'Keynote Address at the 2004 Democratic National Convention', 'Type': 'address', 'Year': 2008}, 2: {'Author': 'Barack Obama', 'City': ['Springfield'], 'Title': 'Remarks Announcing Candidacy for President in Springfield, Illinois', 'Type': 'remarks', 'Year': 2008}, 3: {'Author': 'Barack Obama', 'City': ['Chicago'], 'Title': 'Remarks at the AIPAC Policy Forum in Chicago', 'Type': 'remarks', 'Year': 2008}}, 'Bill Richardson': {1: {'Author': 'Bill Richardson', 'City': [], 'Title': 'Iraq Speech to New Hampshire Democratic State Party State Central Committee', 'Type': 'speech', 'Year': 2008}, 2: {'Author': 'Bill Richardson', 'City': [], 'Title': 'Address to the DNC Winter Meeting', 'Type': 'address', 'Year': 2008}, 3: {'Author': 'Bill Richardson', 'City': [], 'Title': 'Speech: The New Realism and the Rebirth of American Leadership', 'Type': 'speech', 'Year': 2008}}}, 2012: {'Barack Obama': {1: {'Author': 'Barack Obama', 'City': ['Parma'], 'Title': '535 - Remarks at a Campaign Rally in Parma, Ohio', 'Type': 'remarks', 'Year': '2012'}, 2: {'Author': 'Barack Obama', 'City': ['Sandusky'], 'Title': '534 - Remarks at a Campaign Rally in Sandusky, Ohio', 'Type': 'remarks', 'Year': '2012'}, 3: {'Author': 'Barack Obama', 'City': [], 'Title': '533 - Remarks at a Campaign Rally in Maumee, Ohio', 'Type': 'remarks', 'Year': '2012'}}} and I want to convert to like this data frame. Year Author1 No. Author City Title Type Year 2008 Barack Oabama 1 Barack Oabama [] .... address 2008 2008 Barack Oabama 2 Barack Oabama ['Springfield'] .... remarks 2008 2008 Barack Oabama 3 Barack Oabama ['Chicago'] .... remarks 2008 ....................... 2008 Bill Richardson …
accepted answer: http://stackoverflow.com/a/48594559
tagged with: nested
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/48594386
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48594386
upvote count: 2
score: 2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48594559
has comment: http://stackoverflow.com/comment/84185520
tagged with: python
tagged with: dictionary
has title: 4-level nested dictionaries convert to pandas dataframe python
type: AnsweredQuestion

http://stackoverflow.com/comment/84266120
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48633944
has text: I see. Thank you.

http://stackoverflow.com/a/48523908
has comment: http://stackoverflow.com/comment/84046232
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84047251
has body: The algorithm does not claim the minimum is at 100, it explicitly says that the minimum was not found (success: False), and indicates why: loss of precision. Observe that 1 + np.exp(-100), and even 1 + np.exp(-50), is exactly 1.0 when the computation is performed in double precision. You gave the optimizer a function that is identically equal to 1 as far as it can tell, it's no wonder that it has nowhere to go looking for smaller values. The solution is to review the situation in your real problem. It seems the terms are badly scaled if you are optimizing the sum of two things of such vastly different magnitudes. Numerical optimization methods have limited capability of dealing with such issues; human intervention is required to make the problem tractable for them.
score: 2
answers question: http://stackoverflow.com/q/48519363
accepted answer of: http://stackoverflow.com/q/48519363
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48576899
type: Answer
answers question: http://stackoverflow.com/q/48575709
downvote count: 0
upvote count: 1
score: 1
has body: Each line in your example file is a separate JSON structure. You probably want to make this clear in the extension of your filename, for example you could use lsjson to stand for line separated JSON. In this case, you have to read each one in as a string and the unmarshal to a python dict: import json with open('example.lsjson') as fh: data = [json.loads(line) for line in fh.readlines()] You'll end up with a list of dicts from pprint import pprint pprint(data) [{u'action': u'browse', u'timestamp': 1487271527, u'user': u'Dave'}, {u'action': u'navigate', u'timestamp': 1487271528, u'user': u'Dave'}, {u'action': u'browse', u'timestamp': 1487271529, u'user': u'Dave'}, {u'action': u'view', u'timestamp': 1487271530, u'user': u'Dave'}, {u'action': u'browse', u'timestamp': 1487271531, u'user': u'Dave'}, {u'action': u'browse', u'timestamp': 1487271532, u'user': u'Dave'}, {u'action': u'browse', u'timestamp': 1487271533, u'user': u'Dave'}, {u'action': u'navigate', u'timestamp': 1487271534, u'user': u'Dave'}]
has comment: http://stackoverflow.com/comment/84162871

http://stackoverflow.com/q/48536500
tagged with: pygal
type: Question
has comment: http://stackoverflow.com/comment/84071215
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: how to divide a world map based on local areas with python?
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84070070
has body: I want to divide a world map based on local areas of every country. but when I searched about it on the internet, I found a library called pygal that could make a world map. But I want a library to access all data about all continents and all countries into it and all local areas of a country and some data about its populations, its area and geolocation of it (for example: the center of the local area as latitude and longitude). i could show my data by pygal with the following code : show some countries : import pygal wm = pygal.maps.world.World() wm.title = "North, Central, and South America" wm.add("NOrth America", ["ca","mx","us"]) wm.add("Central America", ["bz","cr","gt","hn","ni","pa","sv"]) wm.render_to_file("americas.svg") show continets : import pygal supra = pygal.maps.world.SupranationalWorld() supra.add('Asia', [('asia', 1)]) supra.add('Europe', [('europe', 1)]) supra.add('Africa', [('africa', 1)]) supra.add('North america', [('north_america', 1)]) supra.add('South america', [('south_america', 1)]) supra.add('Oceania', [('oceania', 1)]) supra.add('Antartica', [('antartica', 1)]) supra.render_to_file("continents.svg")

http://stackoverflow.com/a/48505047
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84004150
accepted answer of: http://stackoverflow.com/q/48504963
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84004510
has body: Use the agg i.e df['C'] = df'A','B'.agg(lambda x : ([x[0]],[x[1]]),1).apply(list) index A B C 0 0 2.3 6.4 [[2.3], [6.4]] 1 1 5.6 2.8 [[5.6], [2.8]] 2 2 8.2 9.0 [[8.2], [9.0]] In case you need speed use numpy's expand dims i.e df['C'] = (df'A','B'.values[:,:,None]).tolist() df['C'] 0 [[2.3], [6.4]] 1 [[5.6], [2.8]] 2 [[8.2], [9.0]] Name: C, dtype: object
answers question: http://stackoverflow.com/q/48504963

http://stackoverflow.com/q/48562396
has title: Text Summarization with Gensim with short paragraph
has body: I am new in NLP. I am trying to extract the summary of the paragraphs using Gensim in python. I am facing a problem with a short paragraph, it is giving me a warning as given below and doesn't give me a summary of the short paragraph. Here is my code in Python: import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) from gensim.summarization import summarize text = "short paragraph" print ('Summary:') print (summarize(text)) It is giving me warning as follows: 2018-02-01 17:31:47,247 : WARNING : Input text is expected to have at least 10 sentences. 2018-02-01 17:31:47,253 : INFO : adding document #0 to Dictionary(0 unique tokens: []) 2018-02-01 17:31:47,258 : INFO : built Dictionary(52 unique tokens: ['clearli', 'adult', 'chang', 'member', 'visit']...) from 4 documents (total 70 corpus positions) 2018-02-01 17:31:47,262 : WARNING : Input corpus is expected to have at least 10 documents. 2018-02-01 17:31:47,285 : WARNING : Couldn't get relevant sentences. The output is(Printing only summary label not the actual summary of the short paragraph): Summary: Am I missing something? Is there any other library for the same.
answer count: 1
has answer: http://stackoverflow.com/a/48563744
downvote count: 0
tagged with: gensim
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: 5
upvote count: 5
tagged with: python

http://stackoverflow.com/comment/84015376
type: Comment
type: QuestionComment
has text: Please format your answer. It's pretty hard to read.
score: 5
comment on: http://stackoverflow.com/q/48510148

http://stackoverflow.com/q/48609401
has body: Amateur Developer, I have the following code that worked fine in Python 2.7, Django 1.10. But now as I upgraded to Django 2+ and Python 3+ it gives an error. View code: def get_class_name(request): class_name = ClassName.objects.get(pk = request.GET.get('class_name', None)) classes = Class.objects.filter(class_name = class_name) l = [[", ".join([s.subject for s in x.subject.all()]),s.id] for x in classes] The error message: NameError at /ajax/get_class_name/ name 's' is not defined Request Method: GET Request URL: http://localhost:8000/ajax/get_class_name/?class_name=1 Django Version: 2.0 Exception Type: NameError Exception Value: name 's' is not defined Model: class Class(models.Model): subject = models.ManyToManyField(Subject) How do I fix it?
tagged with: view
tagged with: list
answer count: 2
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: django
has title: Django NameError - Name 's' is not defined
has answer: http://stackoverflow.com/a/48609454
favorite count: 0
type: Question
tagged with: ajax
score: 1
has comment: http://stackoverflow.com/comment/84217541
tagged with: python
has answer: http://stackoverflow.com/a/48614350

http://stackoverflow.com/q/48508702
answer count: 1
has comment: http://stackoverflow.com/comment/84012711
has answer: http://stackoverflow.com/a/48509599
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/16424091
has body: For a school project i am designing an application in Tkinter. It will be an exam question browser that will allow students to view question papers. Currently i am trying to find a way to dynamically embed images from a list into a text widget. The following code is what i am currently using to find a solution. from tkinter import * from PIL import Image, ImageTk im = [] im.append("mary.jpg") im.append("sherm.jpg") im.append("bean.jpg") class Window(Frame): def __init__(self, master): Frame.__init__(self, master) self.master = master self.start_window() def start_window(self): self.master.title("question browser") self.pack(fill=BOTH, expand=1) D = Text(self) x = 0 for i in (im): imgs = Image.open(im[x]) mi = ImageTk.PhotoImage(imgs) D.image_create(END, image = mi) x = x + 1 D.pack() D.config(state=DISABLED) root = Tk() app = Window(root) root.mainloop() no error message is being output, just a blank box. which i believe is due to the fact that i am not keeping a reference to the image. i am struggling to find a solution to this problem, since the actual program will be working with lots of images. therefore it is not possible to create a global variable to store a reference to each individual image (e.g: Global Variable = Image.open("image.jpg")). help would be greatly appreciated. I can install other modules if required.
has comment: http://stackoverflow.com/comment/84012247
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/84012829
has comment: http://stackoverflow.com/comment/84012625
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84013014
tagged with: tkinter
has title: Dynamically embed images from a list in Tkinter
type: UnansweredQuestion

http://stackoverflow.com/comment/84467776
type: Comment
comment on: http://stackoverflow.com/q/48508450
score: 0
has text: Thank you for all of your help. I ran "sudo apt-get upgrade" and ubuntu told me my all of my software is up to date. I'm not sure how that happens if i'm some 46 updates behind. I can't find a way to upload my .svg. Sorry for being so 'noob' at this.
type: QuestionComment

http://stackoverflow.com/a/49105522
has body: Just change this instruction: conda create -n tensorflow pip python=3.5 to: conda create -n tensorflow pip python=3.5 -spyder.
answers question: http://stackoverflow.com/q/48542418
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48542418
type: Answer
score: 0

http://stackoverflow.com/q/48596035
answer count: 1
has title: How can I fill pandas column with a function (sin,line)?
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48598048
has comment: http://stackoverflow.com/comment/84191547
has answer: http://stackoverflow.com/a/48598048
downvote count: 2
has comment: http://stackoverflow.com/comment/84188964
upvote count: 1
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84189536
tagged with: data-science
type: AnsweredQuestion
has body: I have a dataframe with some columns that i have been adding myself. There is one specific column that gathers the max and min tide levels. Pandas Column mostly empty but with some reference values import pandas as pd import numpy as np df = pd.DataFrame({'a':[1,2,3,4],'b':[np.nan,np.nan,3,4]},columns=['a','b']) df The problem is that the column is mostly empty because it only shows those peak values and not the intermediate ones. I would like to fill the missing values with a function similiar to the image shown below. I want to fill it with a function of this kind Thank you in advance.
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/84189763

http://stackoverflow.com/comment/84215786
type: AnswerComment
has text: Which line? This one `pro_id_query = "SELECT * FROM %s"%(pro_title)`?
comment on: http://stackoverflow.com/a/48608950
type: Comment
score: 0

http://stackoverflow.com/comment/84062694
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48508424
has text: @jp_data_analysis I added the question here: https://stackoverflow.com/questions/48533538/modify-value-of-pandas-dataframe-groups
type: AnswerComment

http://stackoverflow.com/a/52143887
type: Answer
accepted answer of: http://stackoverflow.com/q/48640623
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: You can do this in many ways, e.g.: for j in range(len(temp)): par0 = i[j] par1 = v [j] par2 = temp[j] # to check the output print('Iteration:', j, '\ni=', par0, '\nv=', par1, '\ntemp=', par2) or for j,par2 in enumerate(temp): par0 = i[j] par1 = v [j] # to check the output print('Iteration:', j, '\ni=', par0, '\nv=', par1, '\ntemp=', par2) If you need a tuple like in your example you can recast the parameters with tuple(parameter).
score: 3
answers question: http://stackoverflow.com/q/48640623

http://stackoverflow.com/q/48523469
tagged with: mysql
has body: i have following: from sqlalchemy import create_engine engine1 = create_engine('mysql://user:password@host1/schema', echo=True) engine2 = create_engine('mysql://user:password@host2/schema') connection1 = engine1.connect() connection2 = engine2.connect() table1 = connection1.execute("select * from table1") table2 = connection2.execute("select * from table2") Now i want to insert all entries from this table1 into an identical empty table table2 in connection2. How can i achive that? I could also create a dict out of table1 and insert it then into table2. As i learned from the documentation of sqlalchemy there is a way to do that, but the examples there assume that you create a whole new table in order to insert into it with new_table.insert(). It doesnt work for my existing tables. Thanks
type: Question
has comment: http://stackoverflow.com/comment/84049760
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84068829
tagged with: sqlalchemy
linked to: http://stackoverflow.com/q/44712049
has title: sqlalchemy python select and insert
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84068975

http://stackoverflow.com/a/55555541
answers question: http://stackoverflow.com/q/48620855
has comment: http://stackoverflow.com/comment/127602391
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48620855
has body: According to @n.m., -std=c++11 needs to be added to CFLAGS.

http://stackoverflow.com/comment/84063305
score: 0
has text: Possible duplicate of [How to sort a dataFrame in python pandas by two or more columns?](https://stackoverflow.com/questions/17141558/how-to-sort-a-dataframe-in-python-pandas-by-two-or-more-columns)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48533422

http://stackoverflow.com/q/48504676
answer count: 3
has comment: http://stackoverflow.com/comment/84003248
has comment: http://stackoverflow.com/comment/84003433
downvote count: 1
has body: I have some code that returns the last day of every month in 2017. Results: 2017-01-31 2017-02-28 2017-03-31 2017-04-30 2017-05-31 2017-06-30 2017-07-31 2017-08-31 2017-09-30 2017-10-31 2017-11-30 2017-12-31 However, I would like to make it include the years 2014 through 2017 and not just 2017. I have not been able to find anything online that would accomplish this and have not been able to figure it out myself. All help/advice would be much appreciated. Here is my code: import arcpy import datetime from datetime import timedelta import time import calendar #returns last day of each month def lastdayofmonth(anyday): nextmonth = anyday.replace(day=28) + datetime.timedelta(days=4) return next_month - datetime.timedelta(days=nextmonth.day) for month in range(1, 13): print (lastdayofmonth(datetime.date(2017, month, 1)))
favorite count: 0
score: -1
accepted answer: http://stackoverflow.com/a/48504750
has answer: http://stackoverflow.com/a/48504833
has answer: http://stackoverflow.com/a/48504750
type: Question
has title: Return Last Day of Month for Range of Years - Python
upvote count: 0
has answer: http://stackoverflow.com/a/48504755
has comment: http://stackoverflow.com/comment/84006425
tagged with: python
tagged with: date
possible better answer: http://stackoverflow.com/a/48504755
linked to: http://stackoverflow.com/q/42950
type: AnsweredQuestion

system
tag name: system
type: Tag
tags question: http://stackoverflow.com/q/48640209

http://stackoverflow.com/q/48531876
tagged with: python-requests
type: Question
has title: How to parse a Json coming back as Bytes Literal in Python
type: UnansweredQuestion
tagged with: arrays
has comment: http://stackoverflow.com/comment/84061350
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84059355
answer count: 0
has body: I am making a simple call to an API and getting what appears to me as a bytes array as Json returning from the call. When I try to get a field from the Json object I get the following error message: TypeError: byte indices must be integers or slices, not str. What am I doing wrong and how do I fix it? I am using the requests package: response = requests.post(myUrl, json=myJson, headers=myHeaders) foo = response.content foo is a Json object: {"aaa": { "bbb":"bbb content", "ccc":"ccc content" } } calling foo['aaa'] results in the following error: error message: TypeError: byte indices must be integers or slices, not str. How do I fix this?
tagged with: http://stackoverflow.com/tag/json

qt5
tags question: http://stackoverflow.com/q/48622395
tag name: qt5
type: Tag

http://stackoverflow.com/q/48606817
answer count: 1
tagged with: node.js
type: AnsweredQuestion
downvote count: 0
tagged with: websocket
favorite count: 0
accepted answer: http://stackoverflow.com/a/48612031
has body: I'm trying to send data from python to nodejs via websockets. Js: var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); server.listen(3000, () =&gt; console.log('running on 3000')); io.sockets.on('connection', function(socket) { io.sockets.on('msg', function(data) { console.log(data); }); }); Python: import asyncio import websockets async def sendData(uri, data): // FAILS ON THE FOLLOWING LINE: async with websockets.connect(uri) as websocket: await websocket.send(json.dumps(data)) def main(): text = "sample data" asyncio.get_event_loop().run_until_complete( sendData("ws://localhost:3000", {"msg": text}) ) main() I'm getting "Malformed HTTP message" errors (websockets.exceptions.InvalidMessage: Malformed HTTP message) I'm concerned python websockets may not be designed to interface with socket.io. Thoughts?
has title: Communicate Between Nodejs and Python via Websockets
score: 8
upvote count: 8
has answer: http://stackoverflow.com/a/48612031
type: Question
tagged with: python

http://stackoverflow.com/comment/84195575
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48599511
has text: This doesn't seem to be a python question since you state that the issue is due to query time. In that case, the python code makes no difference; it's a micro optimisation.
type: Comment

http://stackoverflow.com/q/48624415
favorite count: 0
has answer: http://stackoverflow.com/a/49479143
type: Question
has title: how to fix CMake Error in CMakeLists.txt: Generator NMake Makefiles does not support platform specification, but platform x64 was specified
answer count: 8
has answer: http://stackoverflow.com/a/54233002
has answer: http://stackoverflow.com/a/54679115
upvote count: 28
has answer: http://stackoverflow.com/a/61173301
has answer: http://stackoverflow.com/a/53164923
tagged with: windows
has body: I want to install dlib using pip install dlib using cmd in windows 10 But it is showing following three errors: CMake Error in CMakeLists.txt: Generator NMake Makefiles does not support platform specification, but platform x64 was specified. CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage INFORMATION: pip 9.0.1 from d:\python36\lib\site-packages (python 3.6) cmake 0.9.0 windows 10 pro(64-bit) Version: 10.0.16299 Build 16299
tagged with: python
has answer: http://stackoverflow.com/a/55732003
accepted answer: http://stackoverflow.com/a/52803626
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92420756
has answer: http://stackoverflow.com/a/52803626
has comment: http://stackoverflow.com/comment/84245681
has answer: http://stackoverflow.com/a/54215119
downvote count: 0
has comment: http://stackoverflow.com/comment/84246851
linked to: http://stackoverflow.com/q/43512889
linked to: http://stackoverflow.com/q/41912372
possible better answer: http://stackoverflow.com/a/54233002
tagged with: cmake
score: 28

http://stackoverflow.com/q/48514105
has title: How to find the type of a complicated object
tagged with: tensorflow
linked to: http://stackoverflow.com/q/2225038
type: Question
has comment: http://stackoverflow.com/comment/84023010
upvote count: 2
tagged with: types
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/48514472
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48514472
has body: Given any python object, is there a way to print out its structure so you can understand how to replace it with an object of equivalent structure? Context: I've been trying to customise this Tensorflow example code so it works with my own data. I seem to be falling down on line 163 at the point where batch[0] and batch[1] are passed to the accuracy.eval() function. I think that batch will be a tuple of two different data types, but I'm really not sure what the data types of these two items are, nor how they relate to basic python types (e.g. I think they should both be numpy ndarray types of different sizes, but does that make them equivalent to lists of lists...?) I imagine I could sprinkle several print(type(batch[0])) statements to find the answer... across as many edits as my data types are deep. Is there code that will reveal this structure in a single hit, regardless of the data types involved?

http://stackoverflow.com/q/48511370
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84190348
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84158514
tagged with: apache2
score: 0
has title: Django 404 via wsgi.py
answer count: 0
has comment: http://stackoverflow.com/comment/84018668
has body: I'm using a baremetal server on scaleway and I'm trying to write the first django app from django tutorial. Since I'm using a remote server I can't use manage.py startserver than i trying to use wsgi.py. this is my apache conf file: WSGIScriptAlias /test-app /usr/local/django-apps/testApp/testApp/wsgi.py WSGIPythonPath /usr/local/django-apps/testApp &lt;Directory /usr/local/django-apps/testApp/testApp&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; the project it's been created with django-admin as the example. If I use curl http://127.0.0.1:8000 from console, I can see "It worked! Congratulations...". I added the server IP (and 127.0.0.1) to ALLOWED_HOST, as suggested the first time I tried to browse http://myserverip/test-app Now curl to loopback still work, but the browser via public IP report: Page not found (404) Request Method: GET Request URL: http://mypublicip/test-app/ Using the URLconf defined in testApp.urls, Django tried these URL patterns, in this order: admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Any suggestion? thanks. @Laurynas Tamulevičius: TestApp -> urls.py: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] I don't understand why the generated html differs from runserver to wsgi. Update: Searching the web, seems that manage.py startserver automagically create some alias for the correct management of the script and the code. One alias should be /static/ that points to a particular directory under django installation. Other alias cold be created in same way. Thats in my opinion is a simple way for dummies, but is a perver system to understand what is need to deploy a django site. Update 2: @Graham Dumpleton Yes. With http://mypublicip/test-app/admin i can see the administration login page without css. …
tagged with: mod-wsgi
has comment: http://stackoverflow.com/comment/84190335
has comment: http://stackoverflow.com/comment/84159211
has comment: http://stackoverflow.com/comment/84160312

http://stackoverflow.com/q/48592572
tagged with: beautifulsoup
type: Question
has title: Can I use requests.post to submit a form?
has comment: http://stackoverflow.com/comment/84182822
tagged with: python
has comment: http://stackoverflow.com/comment/84182449
accepted answer: http://stackoverflow.com/a/48594313
has comment: http://stackoverflow.com/comment/84182742
has comment: http://stackoverflow.com/comment/84182665
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84182503
has answer: http://stackoverflow.com/a/48594313
score: 1
downvote count: 0
answer count: 1
tagged with: web-scraping
upvote count: 1
has body: I am trying to get the list of stores from this site: http://www.health.state.mn.us/divs/cfh/wic/wicstores/ I'd like to get the list of stores that is produced when you click on the button "View All Stores". I understand that I could use Selenium or MechanicalSoup or ... to do this but I was hoping to use requests. It looks like clicking on the button submits a form: &lt;form name="setAllStores" id="setAllStores" action="/divs/cfh/wic/wicstores/index.cfm" method="post" onsubmit="return _CF_checksetAllStores(this)"&gt; &lt;input name="submitAllStores" id="submitAllStores" type="submit" value="View All Stores" /&gt; But I have no idea how to write the requests query (or indeed if this is even possible). Why I have tried so far is variations on: SITE = 'http://www.health.state.mn.us/divs/cfh/wic/wicstores/' data = {'name': 'setAllStores', 'form': 'submitAllStores', 'input': 'submitAllStores'} r = requests.post(SITE, data) But this doesn't work. Any help / advice would be welcome.
tagged with: python-requests
favorite count: 0

http://stackoverflow.com/a/48550663
answers question: http://stackoverflow.com/q/48549007
type: Answer
has comment: http://stackoverflow.com/comment/84102451
score: 0
has body: Pandas have it all. title_principals["all"] = title_principals["Actor1"].astype(str)+','+title_principals["Actor2"].astype(str)+','+title_principals["Actor3"].astype(str)+','+title_principals["Actor4"].astype(str)+','+title_principals["Actor5"].astype(str)+','+title_principals["Actor6"].astype(str)+','+title_principals["Actor7"].astype(str)+','+title_principals["Actor8"].astype(str)+','+title_principals["Actor9"].astype(str)+','+title_principals["Actor10"].astype(str) and then, from the string, make the count and drop the other variables. title_principals["GreaterEuropean"] = title_principals["all"].str.contains(r'GreaterEuropean').sum()

http://stackoverflow.com/comment/84057603
comment on: http://stackoverflow.com/a/48530897
type: Comment
has text: I'm so confused. What way is it supposed to look?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48634490
has answer: http://stackoverflow.com/a/48652301
tagged with: pyomo
type: AnsweredQuestion
tagged with: constraints
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I want to input many constraints at once. My constraints are as follows. def ss1_rule(model): return model.ss[1,1] - model.sss[1,1] &lt;= 0.0 model.ss1 = Constraint(rule=ss1_rule) def ss2_rule(model): return model.ss[1,1] - model.sss[2,1] &lt;= 0.0 model.ss2 = Constraint(rule=ss2_rule) def ss3_rule(model): return model.ss[1,1] - model.sss[3,1] &lt;= 0.0 model.ss3 = Constraint(rule=ss3_rule) Is there any way to enter the regular constraint at once? Thank you.
score: 3
accepted answer: http://stackoverflow.com/a/48652301
tagged with: python
has title: How to put multiple constraints at once in pyomo?

http://stackoverflow.com/a/48544099
score: 2
upvote count: 2
downvote count: 0
has body: You can decode it first: ord('é'.decode('utf-8')) # outputs 233
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48544059
type: Answer
answers question: http://stackoverflow.com/q/48544059

http://stackoverflow.com/comment/84119215
type: QuestionComment
score: 0
has text: Try giving full permission to the script chmod 777 newfinal.py
comment on: http://stackoverflow.com/q/48561120
type: Comment

http://stackoverflow.com/q/48547172
has answer: http://stackoverflow.com/a/48547260
type: Question
tagged with: python-3.x
has title: Search for username in textfile
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48547258
has comment: http://stackoverflow.com/comment/84090198
has body: I need help with looking for a username in a text file so that the user should enter a username that is not already stored in the file. The text file looks like this: aaa12 aaa12 aaa16 aaa16 iii12 iii12 Code: username=input("Enter a username:") with open("users.txt") as openfile: for line in openfile: for part in line.split(): if username in part: print("Try again") I don't think it works. Is there any other solutions I could use?
score: 0
has comment: http://stackoverflow.com/comment/84090468
answer count: 3
has answer: http://stackoverflow.com/a/48547543
tagged with: python
has comment: http://stackoverflow.com/comment/84090242

http://stackoverflow.com/comment/83980021
comment on: http://stackoverflow.com/q/48493370
score: 0
type: Comment
type: QuestionComment
has text: I can't tell what your expected output is. Could you clarify?

http://stackoverflow.com/a/65794329
has comment: http://stackoverflow.com/comment/116329220
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48492079
has body: In my experience, Tensorflow only uses the dedicated GPU memory as described below. At that time, memory_limit = max dedicated memory - current dedicated memory usage (observed in the Win10 task manager) from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) Output: physical_device_desc: "device: XLA_CPU device" , name: "/device:GPU:0" device_type: "GPU" memory_limit: 2196032718 To verify this , I tried to use for a single task (Tensorflow 2 benchmark from https://github.com/aime-team/tf2-benchmarks), it gives "Resource exhausted" error as below on a GTX1060 3GB with Tensorflow 2.3.0. 2021-01-20 01:50:53.738987: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties: pciBusID: 0000:01:00.0 name: GeForce GTX 1060 3GB computeCapability: 6.1 coreClock: 1.7085GHz coreCount: 9 deviceMemorySize: 3.00GiB deviceMemoryBandwidth: 178.99GiB/s Limit: 2196032718 InUse: 1997814016 MaxInUse: 2155556352 NumAllocs: 1943 MaxAllocSize: 551863552 Reserved: 0 PeakReserved: 0 LargestFreeBlock: 0 2021-01-20 01:51:21.393175: W tensorflow/core/framework/op_kernel.cc:1767] OP_REQUIRES failed at conv_ops.cc:539 : Resource exhausted: OOM when allocating tensor with shape[64,256,56,56] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc Traceback (most recent call last): I have tried to do the same with multiple small tasks. It tries to use the shared GPU memory for multiple tasks with different Juypter kernels, but the newer task ultimately fails. For an example with two similar Xception models : Task 1: runs without an error Task 2: fails with below error UnknownError: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above. [[node xception/block1_conv1/Conv2D (defined at <ipython-input-25-0c5fe80db9f1>:3) ]] [Op:__inference_predict_function_5303] Function call stack: predict_function GPU Memory us…

http://stackoverflow.com/comment/84281913
comment on: http://stackoverflow.com/a/48584901
type: Comment
has text: @JeffC thank you, your explanation is well understandable.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84176395
comment on: http://stackoverflow.com/a/48589029
type: Comment
type: AnswerComment
has text: OK, it was a problem with the final check. I fixed it.
score: 0

http://stackoverflow.com/comment/84228255
comment on: http://stackoverflow.com/q/48613231
type: Comment
type: QuestionComment
has text: I was making a counter that added to a variable every time any of the values within the range got intercepted by a 'line' across the x-axis and the y-axis and so I was using the line distance and dividing the values in the variables by it
score: 0

http://stackoverflow.com/q/48627255
tagged with: list
answer count: 3
possible better answer: http://stackoverflow.com/a/48627328
has title: Creating dictionary from list in Python - dict key omits Identical items in the list
downvote count: 1
accepted answer: http://stackoverflow.com/a/48627356
has body: While creating a dictionary from the list, the keys of the dictionary neglects the identical items in the List and stores the last item as the key. For example in this: lst1 = [["Apple",20.00,"Swiss"], ["Banana",5.00,"Brazil"], ["Strawberry",25.00,"Swiss"], ["Pear",12.00,"Greece"], ["Mango",3.00,"Peru"], ["Avacado",7.00,"Peru"]] my_dict = {val[2]:val[:2] for val in lst1} print (my_dict) Prints this {'Swiss': ['Strawberry', 25.0], 'Brazil': ['Banana', 5.0], 'Greece': ['Pear', 12.0], 'Peru': ['Avacado', 7.0]} As far as I understand it does so because the keys can't be identical, then why doesn't it group the values of identical keys in to one list. Like this { 'Swiss': [["Apple",20.00],['Strawberry', 25.0]], 'Brazil': ['Banana', 5.0], 'Greece': ['Pear', 12.0], 'Peru': [["Mango",3.00],['Avacado', 7.0]] } Is there any way I could do this in pure Python?
has answer: http://stackoverflow.com/a/48627353
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48627328
has answer: http://stackoverflow.com/a/48627356
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 2
upvote count: 3

http://stackoverflow.com/comment/84129025
type: Comment
has text: It is really complicated, need [this](https://stackoverflow.com/a/39600120/2901002) and [this](https://stackoverflow.com/a/15441779/2901002)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48558213

http://stackoverflow.com/comment/84058233
comment on: http://stackoverflow.com/q/48530886
score: 0
has text: No I just need one image to be displayed at one time. So only the first subplot needs to have the image.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84030349
has text: You are breaking only one loop, however, you have 2. The outer loop triggers your inner loop on next iteration
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/48517912

http://stackoverflow.com/comment/84204432
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48603490
has text: UNIT ENTRIESn_hourly R001 0.0 R001 217.0 R001 890.0 R001 2451.0 R001 4400.0 R001 3372.0 R002 0.0 R002 42.0 R002 50.0 R002 316.0 R002 633.0 R002 639.0 R003 0.0 R003 0.0 R003 0.0 R003 0.0 after the mapper. so the reducer should get this and sum by unit
score: 0

http://stackoverflow.com/a/53200336
type: Answer
score: 0
has body: ^ (caret) is regex (regular expressions) for matching the start of a string. However, the way it's displayed in angular's 404 page is a little strange. You'll often see "^ ^" or caret space caret, and otherwise repeated carets in the urlpatterns listed. On the face of it, that makes it utterly impossible to match any string since, as has been pointed out, a string can't start in two different places. What's going on is django is matching things in hierarchical order, and the pattern that's displayed as: "^blog ^time/$" above is actually TWO patterns: "^blog" and then: "^time/$" This is completely normal, if confusingly displayed, and is the expected way to process an "include" statement here. It's just not getting displayed with a visible delimiter. To test this, notice that any include directive that wasn't matched in the first part doesn't get expanded in the 404 page. I noticed this when trying to get the rest-auth package to work: url(r'admin/', admin.site.urls, name='admin'), url(r'^$', views.api_root, name='api_root'), url(r'^auth/', include('rest_auth.urls')), url(r'^auth/', include('rest_auth.registration.urls')), If I entered a url begining with "admin" then the admin block is shown expanded in the 404 page, but I can't see what urls might be valid if starting with "auth", and the 'auth' urls are displayed as bare (though repeated, 'cause there's two of them). If I enter an invalid URL begining with "auth/" then the opposite happens. You may need to have more than one child urlpattern to see that effect though. Django will remove the matching portion of the url before attempting to match child urlpatterns. This is why the seemingly impossible URL pattern given above CAN match a valid string. If I have to guess why it wasn't working, it's probably because the first pattern there ("^blog") doesn't have a trailing "/", and so the correct URL would be "blogtime/". (This doesn't match the source you gave, did you change something?) That probably isn't what you w…
answers question: http://stackoverflow.com/q/48534047

http://stackoverflow.com/a/48554992
downvote count: 0
upvote count: 1
has body: You shouldn't use map or a list comprehension just for the side effects of the function you're applying. You should only use it when the resulting list contains meaningful data. In your case, you'd be creating a big nested list of lists containing a whole bunch of repeated references to the same words list you created at the global level. That's not useful at all. Furthermore, your entire reason for making the change seems to be based on the premise that using map or a comprehension is sure to be faster. That's probably not true. They may be about the same speed, or may be slower. I think it's very unlikely that anything you can do will make the comprehension/map version faster than the explicit loop. The main reason is that function calls in Python are pretty slow, and so the need to pack some of the loop logic into a function makes that part slower than it was with the explicit loops. What often can be faster is using builtin functions or types to do the iteration for you in C without ever reaching back out to Python code. In your example, you want to be counting the words in your list of lists, so using collections.Counter is probably a good idea. I'd probably do something like this, eliminating the inner loop while keeping the outer one: from collections import Counter word_counts = Counter() for sentence in sentences_wiki: word_counts.update(sentence) words = list(word_counts) # get a list of keys, if you really need it separate from the count As Patrick Haugh commented, it's even possible to eliminate both loops using itertools if you want to create the counter in one line: import itertools from collections import Counter word_counts = Counter(itertools.chain.from_iterable(sentences_wiki)) words = list(word_counts)
type: Answer
answers question: http://stackoverflow.com/q/48554495
score: 1

http://stackoverflow.com/comment/84155791
comment on: http://stackoverflow.com/q/48579680
score: 0
type: Comment
type: QuestionComment
has text: Starting `0x` are the values hex?

http://stackoverflow.com/comment/84145583
has text: Well anyway, yes, your function wouldn't do anything that could possible cause python to re-read and load a module. I've never even considered a case of a module importing itself, so I'll wait for those with more arcane knowledge than myself..
type: QuestionComment
comment on: http://stackoverflow.com/q/48574385
score: 1
type: Comment

http://stackoverflow.com/q/48595625
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48617889
accepted answer: http://stackoverflow.com/a/48617889
has body: I'm working in a model that contains 5 sub-models which are identical and their only difference is on their weights. I trained each of them separately but now that I have to use them together I build the 5 of them and I get the message RuntimeError: The name "predictions" is used 5 times in the model. All layer names should be unique. I would like to know if there is a way to change the names of the layers inside my model without using the name property because there are more than 100 layers and I cannot do it manually. And if I change the name I would also like to know how to load the weights, because they are saved with the previous layer names.
linked to: http://stackoverflow.com/q/49550182
tagged with: python
type: AnsweredQuestion
answer count: 2
score: 1
tagged with: models
has title: Copy the same model multiple times in keras
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/72909880
tagged with: keras
possible better answer: http://stackoverflow.com/a/72909880

http://stackoverflow.com/comment/84228693
score: 0
type: Comment
has text: Ahh, I see now, I'd forgotten that the char primitive doesn't exisit in Python, which is why nothing is getting changed, thank you.
type: QuestionComment
comment on: http://stackoverflow.com/q/48615870

http://stackoverflow.com/comment/84053739
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48519740
has text: Thank you! This worked. But one thing is I realized your solution only works on abbrevs like `e.g.`, but not abbrevs like `Mr.`, even when I put `Mr.` in my exception list it still does not work. Namely `Mr.` still got separated as `Mr . `. Do you have any suggestion how to quick fix that?
score: 0

package
tags question: http://stackoverflow.com/q/48491649
tags question: http://stackoverflow.com/q/48501898
tag name: package
type: Tag
tags question: http://stackoverflow.com/q/48528477
tags question: http://stackoverflow.com/q/48645003
tags question: http://stackoverflow.com/q/48589216
tags question: http://stackoverflow.com/q/48542418
tags question: http://stackoverflow.com/q/48554256

http://stackoverflow.com/q/48565995
upvote count: 0
has answer: http://stackoverflow.com/a/48566055
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84127897
type: AnsweredQuestion
has title: Python - Not recognizing Exception Handling
possible better answer: http://stackoverflow.com/a/48566055
has body: So I am having problems with exception handling, I am running Python 3.6.3. this is my code: txt = "" txtFile = input("gimme a file.") f = open(txtFile, "r") try: for line in f: cleanedLine = line.strip() txt += cleanedLine except FileNotFoundError: print("!") So if I try and get an error with a bad input Instead of printing ! I still get the error: Traceback (most recent call last): File "cleaner.py", line 11, in &lt;module&gt; f = open(txtFile, "r") FileNotFoundError: [Errno 2] No such file or directory: 'nonexistentfile' I have tried swapping in OSError, I have also tried just except:, which tells me that I am doing something wrong(because I shouldn't do that in the first place) and since I understand that except: should catch all of the exceptions.
accepted answer: http://stackoverflow.com/a/48566064
has answer: http://stackoverflow.com/a/48566064
tagged with: python
score: -1
type: Question
tagged with: python-3.x
answer count: 2

http://stackoverflow.com/q/48524846
tagged with: python
has title: Why doesn't Visual Studio Code recognize my WSL bash python?
tagged with: windows-subsystem-for-linux
type: Question
has body: I am running Visual Studio Code on Windows 10 with WSL bash as its terminal: "terminal.integrated.shell.windows": "C:/Windows/sysnative/bash.exe" In WSL bash I have both python (v2.7) and python3 (v3.6) installed. I have installed the Python extension for VS Code. Unfortunately VS Code fails to recognize either version of Python in WSL bash. For example when I try to discover tests, I get the following error in the Python Test Log output window: Test Discovery failed: Error: spawn python ENOENT How can I configure VS Code to work with Python form WSL bash? Note: I'm pretty sure I need to configure a path to Python in the "python.pythonPath" key in VS Code's user settings file. I am unsure of which path to put as the value though.
has answer: http://stackoverflow.com/a/48529954
tagged with: bash
tagged with: visual-studio-code
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84055626
upvote count: 7
score: 7
accepted answer: http://stackoverflow.com/a/48529954
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84055332
has comment: http://stackoverflow.com/comment/84055668

http://stackoverflow.com/q/48491168
tagged with: python
linked to: http://stackoverflow.com/q/37253534
tagged with: django-mssql
tagged with: sql-server
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/49665117
accepted answer: http://stackoverflow.com/a/48509156
linked to: http://stackoverflow.com/q/9944204
has answer: http://stackoverflow.com/a/48509156
has title: Error connecting Django 2.0 with sql server 2014 using python 3.6
favorite count: 0
linked to: http://stackoverflow.com/q/15146100
type: Question
has comment: http://stackoverflow.com/comment/84003432
linked to: http://stackoverflow.com/q/21908190
has comment: http://stackoverflow.com/comment/83989139
answer count: 2
has body: I am new in Django and I am trying to connect it with Sql server. As I read there is a third party connector for this. Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 978, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 961, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 950, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 655, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 205, in _call_with_frames_removed File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\models.py", line 2, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\base_user.py", line 47, in &lt;module&gt; class AbstractBaseUser(models.Model): File "C:\Program Files\Python36\lib\site-packages\django\db\models\base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label…
possible better answer: http://stackoverflow.com/a/49665117
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/108327763
score: 0
type: Comment
has text: @AdamGriffiths The error I had was printed directly to the console. What version of Qt and PyQt do you use?
comment on: http://stackoverflow.com/a/61198797
type: AnswerComment

http://stackoverflow.com/comment/84176278
type: Comment
type: QuestionComment
score: 0
has text: You, and your code, should pay attention to the shape and dimensions of the loaded array. Usually `loadtxt` is used to load a table like csv file, not a single string. In that case it returns a 2d array (or 1d structured array). You don't need `unpack` here, though that isn't causing problems.
comment on: http://stackoverflow.com/q/48581080

http://stackoverflow.com/a/48632237
has comment: http://stackoverflow.com/comment/84264397
upvote count: 2
has comment: http://stackoverflow.com/comment/84264833
type: Answer
has body: There are some questions and answers about defining a midpoint on a colorscale. Especially this one, which is also now part of the matplotlib documentation. The idea is to subclass matplotlib.colors.Normalize and let it take a further argument midpoint. This can then be used to linearly interpolate the two ranges on either side of the midpoint to the ranges [0,0.5] and [0.5,1]. To have a midpoint on a logarithmic scale, we can in principle do the same thing, just that we subclass matplotlib.colors.LogNorm and take the logarithm of all values, then interpolate this logarithm on the ranges [0,0.5] and [0.5,1]. In the following example we have data between 0.001 and 10. Using the usual LogNorm this results in the middle of the colormap (white in the case of the RdBu colormap) to be at 0.1. If we want to have white at 1, we specify 1 as the midpoint in the MidPointLogNorm. import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm x,y = np.meshgrid(np.linspace(-3,0,19), np.arange(10)) f = lambda x,y : 10**x*(1+y) z = f(x,y) fig, (ax,ax2) = plt.subplots(ncols=2, figsize=(12,4.8)) im = ax.pcolormesh(x,y,z, cmap="RdBu_r", norm=LogNorm(vmin=z.min(), vmax=z.max())) fig.colorbar(im, ax=ax) ax.set_title("LogNorm") class MidPointLogNorm(LogNorm): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): LogNorm.__init__(self,vmin=vmin, vmax=vmax, clip=clip) self.midpoint=midpoint def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [np.log(self.vmin), np.log(self.midpoint), np.log(self.vmax)], [0, 0.5, 1] return np.ma.masked_array(np.interp(np.log(value), x, y)) im2 = ax2.pcolormesh(x,y,z, cmap="RdBu_r", norm=MidPointLogNorm(vmin=z.min(), vmax=z.max(), midpoint=1)) fig.colorbar(im2, ax=ax2) ax2.set_title("MidPointLogNorm") plt.show() Updated solution which works for nan values: You need to replace the nan values by some value (best one outside the range of val…
accepted answer of: http://stackoverflow.com/q/48625475
has comment: http://stackoverflow.com/comment/84264434
score: 2
has comment: http://stackoverflow.com/comment/84264384
answers question: http://stackoverflow.com/q/48625475
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48635190
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48635236
type: Question
tagged with: pythoninterpreter
has title: Using Python 3.6 with Visual Studio Code
has answer: http://stackoverflow.com/a/48635494
tagged with: python
has comment: http://stackoverflow.com/comment/84267163
answer count: 2
tagged with: visual-studio-code
has body: I'm trying to use the Pool.starmap() function with multiprocessing, but it is only available in Python 3.3+. My Python default version is 2.7.10, but I also have installed Python 3.6. I've tried changing the selected Python interpreter in the command palette and even it says its now currently using the 3.6 interpreter it outputs the following: AttributeError: 'Pool' object has no attribute 'starmap' I've tried restarting VS Code but it didn't work. I've looked up to see if updating the default Python version in the OS might help but it seems that it is not a good idea. Any ideas? Edit: My OS is macOS HighSierra Version 10.13.2
score: 0

http://stackoverflow.com/q/48573989
has title: ipynb python file to executable exe file
has comment: http://stackoverflow.com/comment/99342922
has comment: http://stackoverflow.com/comment/84145071
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/48626144
has comment: http://stackoverflow.com/comment/99368526
tagged with: exe
tagged with: jupyter-notebook
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84145124
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84145166
has body: I am using jupyter notebook for coding, hence my file format is ipynb. I would like to turn this piece of code into an executable file .exe for later uses. So far I have managed to get the exe file by going to anaconda prompt, executed the following command ---> pyinstaller --name ‘name of the exe’ python_code.ipynb This gives me two folders build and dist, both contains .exe file. However, none of them worked. I would like to know why and how to fix it. by double click on the exe, it shows a black cmd pop up and then it went away. nothing else happens.
has comment: http://stackoverflow.com/comment/84145239

http://stackoverflow.com/comment/84186190
comment on: http://stackoverflow.com/q/48594522
score: 0
type: QuestionComment
has text: Threading module? Asyncio? https://docs.python.org/3/library/asyncio.html
type: Comment

http://stackoverflow.com/a/48525705
score: 6
type: Answer
answers question: http://stackoverflow.com/q/48525582
upvote count: 6
has comment: http://stackoverflow.com/comment/84046668
has comment: http://stackoverflow.com/comment/84046539
has body: To go with Sandeep's answer, you can build the two lists locally from the giant list of arguments: def compare_locality(p,p_loc,s0,s0_loc,s1,s1_loc,s2,s2_loc,s3,s3_loc,s4,s4_loc,s5,s5_loc,s6,s6_loc,s7,s7_loc,s8,s8_loc,s9,s9_loc,s10,s10_loc,s11,s11_loc,s12,s12_loc): locs = [] ss = [s0, s1, s2, ..., s12] s_locs = [s0_loc, ..., s12_loc] for s, s_loc in zip(ss, s_locs): if s == '': break locs.append(s_loc) if len(locs) == 0: return '' else: return compare(p_loc,*locs)
accepted answer of: http://stackoverflow.com/q/48525582
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84046592
downvote count: 0

http://stackoverflow.com/comment/84188847
has text: maybe output of `resultsDF.show()` will help me to understand.
score: 0
comment on: http://stackoverflow.com/a/48595074
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84116105
type: QuestionComment
comment on: http://stackoverflow.com/q/48560201
type: Comment
has text: Edited the question with code files and error message @Rawing
score: 0

http://stackoverflow.com/comment/84055557
type: QuestionComment
has text: Yes. Now the sublist of `list_b` has five elements (the five length-2 lists). You need to make it so that every sublist of `list_b` has two elements.
comment on: http://stackoverflow.com/q/48529957
score: 0
type: Comment

http://stackoverflow.com/q/48572819
upvote count: 1
tagged with: python
type: UnansweredQuestion
has title: Random choice from list at least once
has comment: http://stackoverflow.com/comment/84142591
tagged with: random
has answer: http://stackoverflow.com/a/48573513
score: 0
has comment: http://stackoverflow.com/comment/84142515
has answer: http://stackoverflow.com/a/48573325
downvote count: 1
has comment: http://stackoverflow.com/comment/84142502
favorite count: 0
answer count: 4
has comment: http://stackoverflow.com/comment/84142705
has answer: http://stackoverflow.com/a/48573183
type: Question
has body: I have 10 elements in a Python list. I want to select an item randomly from this list - multiple times (more than 1000 times...). And, I want to ensure that all 10 are elements chosen at least once. Is there a way to do it in Python? random.choice is not helping me...(or, at least, I do not know how to use it).
has answer: http://stackoverflow.com/a/48572948

http://stackoverflow.com/a/48584419
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48584208
has body: You will not have access to any /Users folders on a Google Cloud machine because they're running Linux, and that's commonly a Mac path. That link assumes your files are already on the server. There are several ways that can happen. Code was initially written there You checkout the code from version control. You scp the files using gcloud compute scp This problem does not apply to Python or Google's services. It's applicable to all remote SSH sessions
type: Answer
accepted answer of: http://stackoverflow.com/q/48584208
downvote count: 0

http://stackoverflow.com/q/48511416
tagged with: function
type: UnansweredQuestion
answer count: 1
tagged with: integral
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48511687
downvote count: 1
score: 0
has body: I have this code below, that print a matrix. Each Column of the matrix represent a beam, and each row represents the height of the beam in a speficic point. (See imagem). import numpy as np import sympy Fh = 3 E1 = 20 #(N/mm²) t = 1 L = 5 h_base = 2 h_min = 0 hx = [] for x in range(0, L): for height_in_x in range(h_min, h_base + 1): h = h_base - ((h_base - height_in_x) / L * x) hx.append(h) H_x = np.array(hx, dtype=np.float) matrix_H_x = np.reshape(H_x, (L, h_base - h_min + 1)) print (matrix_H_x) """ [[ 2. 2. 2. ] [ 1.6 1.8 2. ] [ 1.2 1.6 2. ] [ 0.8 1.4 2. ] [ 0.4 1.2 2. ]] Question: Now I need to do a integral using this values: The expression is: result = -1/E1 + sympy.integrate((-Fh * L + Fh * **x**) / (t * **H_x** / 12)) But I should keep 3 results independent, for each column (beam)see image Where: x is a integer that in this case goes from 0 to L Hx is the height of the beam in each x distance. I don't know if the for loop to get the heights was a good solution, maybe I can do everything using only SymPy functions.
tagged with: matrix
has title: Integration of expression with a function of two variables
favorite count: 0
type: Question
tagged with: sympy

http://stackoverflow.com/a/48550376
has body: This code will also satisfy all your conditions including duplicates and empty values. Code: if __name__ == '__main__': d = {} a = [] with open('sample.csv', 'r') as readf: enum_list = [line.rstrip('\n').split(',') for line in readf] for i,x in enumerate(enum_list): if i == 0: for val in x: d[val] = [] a.append(val) continue for val in x: i = x.index(val) if val and val not in d[a[i]]: d[a[i]].append(val) print(d) Output: {'first_name': ['alice', 'mark', 'bob', 'Chelsea', 'chester'], 'last_name': ['sparks', 'peters', 'stones'], 'skill': ['artist', 'sports', 'teacher']}
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48548372

http://stackoverflow.com/comment/84025353
comment on: http://stackoverflow.com/a/48515548
type: Comment
score: 0
type: AnswerComment
has text: Hi jezrael, thanks for trying to help! I'm trying to have a more generic way; using your method, for every csv file, i'd have to manually type out the column names. is there a more generic method that's more scalable?

http://stackoverflow.com/comment/84111989
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48557919
has text: if i quote the variable **Patt_search** like `'Patt_search'` with `input` then it did not worked but at the same time if i use this variable **Patt_search** without quotes with `input` function it works as expected taking the inputs from user.
type: Comment

http://stackoverflow.com/q/48541342
tagged with: seaborn
tagged with: data-visualization
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84078207
tagged with: python
accepted answer: http://stackoverflow.com/a/48541558
downvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48541558
has title: Matplotlib graph adjusment with big dataset
tagged with: pandas
has body: I have a big dataset of 83000 rows with dates and values. I want to generate a plot with a moving average value and time. But my graph is not clear as you may see in the images. How can I adjust the graph and make it clearer? Is there another way to plot such a big dataset like this? When I look at this graph so many lines are like put on each other and they don't mean a lot? (I generally use matplotlib and seaborn libraries for Python)
score: -5
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84077898

http://stackoverflow.com/a/48539146
has comment: http://stackoverflow.com/comment/84081754
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84081720
upvote count: 1
has comment: http://stackoverflow.com/comment/84076600
has body: You'll have to use a lambda-function to pass the additional parameter to the get_next_trading_date() function: backTestRecordAfterModified['createdAt']=backTestRecordAfterModified['createdAt'].apply(lambda date: get_next_trading_date(date=date, exchange='SZSE')) The pandas.Series.apply() function does in fact support additional keyword arguments for the function, but the first argument to the function is always the value from the pandas series. If get_next_trading_date() was defined differently, with the order of arguments reversed: get_next_trading_date_2(date='2017-05-01', exchange='SZSE') you could have used backTestRecordAfterModified['createdAt']=backTestRecordAfterModified['createdAt'].apply(func=get_next_trading_date, exchange='SZSE').
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84078298
has comment: http://stackoverflow.com/comment/84097074
has comment: http://stackoverflow.com/comment/84083001
accepted answer of: http://stackoverflow.com/q/48538788
has comment: http://stackoverflow.com/comment/84079598
has comment: http://stackoverflow.com/comment/84074804
answers question: http://stackoverflow.com/q/48538788

http://stackoverflow.com/q/48551528
tagged with: typescript
tagged with: protractor
has comment: http://stackoverflow.com/comment/84107646
tagged with: python
accepted answer: http://stackoverflow.com/a/48555019
has answer: http://stackoverflow.com/a/48555019
type: AnsweredQuestion
score: 0
answer count: 1
has title: Explicit wait in protractor serenity
type: Question
has body: I am trying to create a base class to add the explicit weights in click and select methods. This is the code I have tried so far but I am getting the error on Click.on(): import { Enter, Click } from "serenity-js/lib/screenplay-protractor"; import { by } from "protractor"; import { protractor, browser } from 'protractor'; var EC = protractor.ExpectedConditions; export class wait{ constructor() { } ElementVisibility(selector){ browser.driver.wait(function() { return browser.driver.isElementPresent(by.xpath(selector)); }); } Click(selector) { this.ElementVisibility(selector).Click.on() } } Also when I import to another page is this the right way to do it? Sorry i am new to typescript and it is giving error and not recognizing the Click method import { Task, step, PerformsTasks } from "serenity-js/lib/screenplay"; import { Enter, Click } from "serenity-js/lib/screenplay-protractor"; import { CheckoutPageMap } from "../interactions/element-mappings/CheckoutPageMap"; import { wait } from "../interactions/element-mappings/wait"; export class FillPaymentMethod implements Task { static called(): FillPaymentMethod { return new FillPaymentMethod(); } @step('{0} Select Shipping Method - Bruno selects for an item in men section') performAs(actor: PerformsTasks): PromiseLike&lt;void&gt; { return actor.attemptsTo( Click.on(CheckoutPageMap.radioCreditCard), Enter.theValue('Bruno Sacco').into(CheckoutPageMap.textCreditCardHolderName), Enter.theValue('4032039926075500').into(CheckoutPageMap.textCreditCardNumber), Enter.theValue('123').into(CheckoutPageMap.textCreditCardCvv), wait.Click('//*[@id="card_month"]/option[.=" 09"]'), //Click.on(CheckoutPageMap.dropDownCreditCardMonth), // TO-DO: optimize choosing option from dropdown from properties file Click.on(CheckoutPageMap.dropDownCreditCardYear) // TO-DO: optimize choosing option from dropdown from properties file ); } }; getting this error - [ts] Property 'Click' does not exist on type 'typeof wait'.

http://stackoverflow.com/comment/84137155
score: 0
type: Comment
has text: Well then you should use `distinct('website')` in the second query as well..
type: QuestionComment
comment on: http://stackoverflow.com/q/48570312

http://stackoverflow.com/a/48687349
type: Answer
has body: You cannot break up the tags__name (at least I don't know a way). From your examples, I can assume 2 possible solutions (1st solution is not strictly using Django): Not everything needs to pass strictly through Django We have Python powers, so let's use them: Let us compose the query first: from difflib import SequenceMatcher from django.db.models import Q def create_query(fulltext): illustration_names = Illustration.objects.values_list('name', flat=True) tag_names = Tag.objects.values_list('name', flat=True) query = [] for name in illustration_names: score = SequenceMatcher(None, name, fulltext).ratio() if score == 1: # Perfect Match for name return [Q(name=name)] if score &gt;= THRESHOLD: query.append(Q(name=name)) for name in tag_names: score = SequenceMatcher(None, name, fulltext).ratio() if score == 1: # Perfect Match for name return [Q(tags__name=name)] if score &gt;= THRESHOLD: query.append(Q(tags__name=name)) return query Then to create your queryset: from functools import reduce # Needed only in python 3 from operator import or_ queryset = Illustration.objects.filter(reduce(or_, create_query(fulltext))) Decode the above: We are checking every Illustration and Tag name against our fulltext and we are composing a query with every name that it's similarity passes the THRESHOLD. SequenceMatcher method compares sequences and returns a ratio 0 &lt; ratio &lt; 1 where 0 indicates No-Match and 1 indicates Perfect-Match. Check this answer for another usage example: Find the similarity percent between two strings (Note: There are other strings comparing modules as well, find one that suits you) Q() Django objects, allow the creation of complex queries (more on the linked docs). With the operator and reduce we transform a list of Q() objects to an OR separated query argument: Q(name=name_1) | Q(name=name_2) | ... | Q(tag_name=tag_name_1) | ... Note: You need to define an acceptable THRESHOLD. As you can imagine this will be a bit slow but it is to be expected when you…
has comment: http://stackoverflow.com/comment/84403008
has comment: http://stackoverflow.com/comment/84411898
upvote count: 12
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48603190
has comment: http://stackoverflow.com/comment/84503710
score: 11
answers question: http://stackoverflow.com/q/48603190
has comment: http://stackoverflow.com/comment/84410013
has comment: http://stackoverflow.com/comment/84495165

http://stackoverflow.com/comment/84263940
type: Comment
type: QuestionComment
has text: I think you want `== "Toyota"`. Also, you have a typo in "filter"
comment on: http://stackoverflow.com/q/48633194
score: 0

http://stackoverflow.com/a/48623446
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48604128
has body: Here is the official list of GrovePi Sensors supported.

http://stackoverflow.com/q/48600165
has comment: http://stackoverflow.com/comment/84197330
answer count: 0
has title: Python list slicing issues
has body: I just observed a behavior with python lists and wanted why and how it works. If I have a list say my_list = [5] Why does my_list[1:] give me [] as the output but my_list[1] give me an IndexError
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/9490058
type: UnansweredQuestion
tagged with: python
tagged with: data-structures
duplicate of: http://stackoverflow.com/q/9490058
has comment: http://stackoverflow.com/comment/84197556
has comment: http://stackoverflow.com/comment/84197371
score: 0

http://stackoverflow.com/comment/84067171
type: QuestionComment
has text: Why don't you write your script `update_db_from_ftp.py` as a management command. https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/
comment on: http://stackoverflow.com/q/48535895
score: 2
type: Comment

http://stackoverflow.com/comment/84171907
has text: @filemonczyk no, because the `/` would be perfectly fine in Python 2. Try a few test cases for yourself and see what happens.
comment on: http://stackoverflow.com/a/48573203
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84209151
type: Comment
type: AnswerComment
has text: Very useful explanation: "I" through "N" default to integer. Thank you!
comment on: http://stackoverflow.com/a/48606380
score: 1

http://stackoverflow.com/a/48505233
upvote count: 1
answers question: http://stackoverflow.com/q/48505015
has comment: http://stackoverflow.com/comment/84004397
type: Answer
accepted answer of: http://stackoverflow.com/q/48505015
score: 1
has body: I believe the issue is with cur.executemany(sql, flight_obs). The docs say: executemany(sql, vars_list) Execute a database operation (query or command) against all parameter tuples or mappings found in the sequence vars_list. so it's effectively doing the equivalent of: for i in flight_obs: cur.execute(sql, i) Since flight_obs is a list of strings, not tuples/mappings, you end up with something like: cur.execute(sql, '2016-07-01 16:42:21') cur.execute(sql, 'A319') cur.execute(sql, 'EDDB') Simple fix - just replace cur.executemany with cur.execute and it should all work.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48552812
score: 21
type: Answer
has comment: http://stackoverflow.com/comment/103448075
has comment: http://stackoverflow.com/comment/103448293
has comment: http://stackoverflow.com/comment/102232585
downvote count: 0
has comment: http://stackoverflow.com/comment/104914974
has comment: http://stackoverflow.com/comment/103447628
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/104915660
accepted answer of: http://stackoverflow.com/q/48552458
has body: return_value is for callables, just write: with patch('__main__.MyClass') as MockClass: instance = MockClass.return_value instance.a = 'test1' instance.b = 'test2' myFunc() # test1 test2 And you have to patch the class in the with-statement, note the capital letter of Class in '__main__.MyClass'.
has comment: http://stackoverflow.com/comment/103448836
answers question: http://stackoverflow.com/q/48552458
upvote count: 21

http://stackoverflow.com/comment/103759137
has text: this will not work if yourcode.py creates a subprocess, I think. You also need to fiddle with $PATH, as explained in monitorius' answer.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51919568
score: 3

http://stackoverflow.com/comment/84290950
score: 0
comment on: http://stackoverflow.com/q/48640495
type: Comment
type: QuestionComment
has text: the number of the columns of the lines are different. Thus, the workaround in the other questions is not working here.

http://stackoverflow.com/a/48590258
type: AcceptedAnswer
has body: You can't really know in advance what self.id will be until the corresponding database row is created and Django extracts it from there. If you aren't planning on filtering on the column, you can just turn it into a property that's computed when you look it up on a model instance: class Thing(db.Model): id = models.AutoField(primary_key=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) @property def ticket_number(self): return '{}-{}'.format(self.brand.shortname.upper(), self.id)
has comment: http://stackoverflow.com/comment/84177962
answers question: http://stackoverflow.com/q/48590180
type: Answer
has comment: http://stackoverflow.com/comment/84178223
score: 0
accepted answer of: http://stackoverflow.com/q/48590180

http://stackoverflow.com/q/48580506
accepted answer: http://stackoverflow.com/a/48580850
has title: Check if a index value exists in a list
has answer: http://stackoverflow.com/a/48580884
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84157784
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48580884
has body: I have a pandas dataframe. My dataframe as an index import pandas as pd df=pd.DataFrame(data=['a','b','c']).T df.columns='myvar' df.set_index(['myvar']) Then I have some lists containing some or none of the index values list_of_interest_1=['b','c','d','z'] list_of_interest_2=['a'] list_of_interest_3=['duck'] I would like to add to my dataframe a few boolean columns which mark whether the corresponding index value was in one of the lists In the example: df= wasinlist1 wasinlist2 wasinlist3 a False True False b True False False c True False False
type: Question
has answer: http://stackoverflow.com/a/48580850
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/48619163
has body: My application is to use an link(url) to invoke lambda function ,then I want to know public IP of lambda and get page source. How could I get lambda public IP by using python? Thanks a lot.
tagged with: python
tagged with: ip-address
tagged with: lambda
score: 10
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51216578
has answer: http://stackoverflow.com/a/70376382
downvote count: 0
has comment: http://stackoverflow.com/comment/84239080
upvote count: 10
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/84234988
tagged with: aws-lambda
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48626262
possible better answer: http://stackoverflow.com/a/65924071
has answer: http://stackoverflow.com/a/48626262
has answer: http://stackoverflow.com/a/65924071
has title: How could I retrieve AWS Lambda public IP address by using Python?

http://stackoverflow.com/a/48539475
type: Answer
answers question: http://stackoverflow.com/q/48539344
type: AcceptedAnswer
downvote count: 0
upvote count: 7
accepted answer of: http://stackoverflow.com/q/48539344
has body: No, the shapes are different, you have to pay attention to the square brackets: &gt;&gt;&gt; np.zeros((2, 1, 3)) array([[[ 0., 0., 0.]], [[ 0., 0., 0.]]]) versus: &gt;&gt;&gt; np.zeros((1, 2, 3)) array([[[ 0., 0., 0.], [ 0., 0., 0.]]]) as you can see, in the first call, we have two times a pair of square brackets for the second dimension, whereas in the latter, we only have one such pair. The shape is also different: &gt;&gt;&gt; np.zeros((2, 1, 3)).shape (2, 1, 3) &gt;&gt;&gt; np.zeros((1, 2, 3)).shape (1, 2, 3) So in the former we have a list that contains two sublists. Each of these sublists contains one element: a list of three elements. In the latter we have a list with one element: a sublist with two elements, and these two elements are lists with three elements. So a vanilla Python list equivalent would be: [ [ [0, 0, 0] ], [ [0, 0, 0] ] ] versus: [ [ [0, 0, 0], [0, 0, 0] ] ]
score: 7

http://stackoverflow.com/q/48584755
score: 1
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
accepted answer: http://stackoverflow.com/a/48584846
upvote count: 1
has answer: http://stackoverflow.com/a/48584846
favorite count: 0
tagged with: parsing
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48584865
tagged with: python
has body: this is my code that gives a list of particular news links from HTML page, it contains only resource name and parameters, I want to include main domain name so that link can be operatable. import requests from bs4 import BeautifulSoup def get_cric_info_articles(): cricinfo_article_link = "http://www.espncricinfo.com/ci/content/story/news.html" r = requests.get(cricinfo_article_link) cricinfo_article_html = r.text soup = BeautifulSoup(cricinfo_article_html, "html.parser") # print(soup.prettify()) cric_info_items = soup.find_all("h2", {"class": "story-title"}) cricinfo_article_dict = {} for div in cric_info_items: cricinfo_article_dict[div.find('a').string] = div.find('a')['href'] return cricinfo_article_dict print(get_cric_info_articles()) what I'm getting {'Bell-Drummond leads MCC in curtain-raiser': '/ci/content/story/1135157.html', 'Scotland pick Brad Wheal, Chris Sole for World Cup qualifiers': '/scotland/content/story/1135152.html', 'Newlands working to be water independent': '/southafrica/content/story/1135120.html'} I'm trying to attach this '/ci/content/story/1135157.html'to http://www.espncricinfo.com/ so the final link will be http://www.espncricinfo.com/ci/content/story/1135157.html', how can I do this? sorry for the long post changes I did for div in cric_info_items: a = div.find('a')['href'] b = 'http://www.espncricinfo.com/' c = urljoin(b,a) cricinfo_article_dict[div.find('a').string] = c
has answer: http://stackoverflow.com/a/48584865
type: AnsweredQuestion
has title: how can I add main link to sublink html, so that link can be called?
answer count: 2

http://stackoverflow.com/q/48610136
tagged with: python
has answer: http://stackoverflow.com/a/48610172
has title: How to conditionally select elements in numpy array
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48610172
downvote count: 0
has body: Can someone help me with conditionally selecting elements in a numpy array? I am trying to return elements that are greater than a threshold. My current solution is: sampleArr = np.array([ 0.725, 0.39, 0.99 ]) condition = (sampleArr &gt; 0.5)` extracted = np.extract(condition, sampleArr) #returns [0.725 0.99] However, this seems roundabout and I suspect there's a way to do it in one line?
favorite count: 0
tagged with: numpy
upvote count: 8
score: 8
type: Question
has answer: http://stackoverflow.com/a/48610171
accepted answer: http://stackoverflow.com/a/48610171
answer count: 2
tagged with: arrays

http://stackoverflow.com/comment/84202648
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48602882
score: 0
has text: Can I send that 'ret' val into the second process by pickling it ?

http://stackoverflow.com/comment/84083641
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48544024
type: QuestionComment
has text: on a side note please do take a read about [MCVE](https://stackoverflow.com/help/mcve), following it is a benefit for all of us. thanks.

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/48614463
tags question: http://stackoverflow.com/q/48509902
tags question: http://stackoverflow.com/q/48609081
tags question: http://stackoverflow.com/q/48616216
tags question: http://stackoverflow.com/q/48565774
tags question: http://stackoverflow.com/q/48515214
tags question: http://stackoverflow.com/q/48641769
tag name: kivy-language
tags question: http://stackoverflow.com/q/48506842
tags question: http://stackoverflow.com/q/48564220
tags question: http://stackoverflow.com/q/48596277

http://stackoverflow.com/comment/84310613
score: 0
has text: @kinderchan Do you mean subdiagonal (for example i==j+1) or triangle (for example i > j)? If you mean triangle you can't use `einsum` or any view-based approach because triangles cannot be expressed as a product of strided intervals.
comment on: http://stackoverflow.com/a/48633379
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84244930
has text: Yes I know, hence Martin's comments that they've likely shadowed `type` but you haven't answered the question here I'm afriad
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48623796

http://stackoverflow.com/comment/84127944
has text: I unfortunately dont know any file sharing (and stackoverflows policy on that) but maybe you can try to reproduce the error with just a few lines (try the critical line plus/minus 2). If that works, you can post the lines and we can try to verify it. Edit: Googled for a second, some SO post says try http://filedropper.com - but you should try to reproduce it with a few lines first, nonetheless.
comment on: http://stackoverflow.com/q/48565562
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/48527267
possible better answer: http://stackoverflow.com/a/48527374
has comment: http://stackoverflow.com/comment/84050589
tagged with: nltk
has comment: http://stackoverflow.com/comment/84050559
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84050613
has answer: http://stackoverflow.com/a/62370262
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84049962
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/84050652
downvote count: 2
has answer: http://stackoverflow.com/a/48527374
has title: Why does the regular expression r'[a|(an)|(the)]+' detect 'h' and 'he' separately instead of 'the' as a whole?
accepted answer: http://stackoverflow.com/a/48527282
has comment: http://stackoverflow.com/comment/84050532
has body: I am trying to find 'a', 'an', 'the' in a given text. And the expression r'[a|(an)|(the)]+' recognizes only 'a' but not 'an' and 'the'. nltk.re_show(r'[a|(an)|(the)]+', 'sdfkisdfjstdskfhdsklfjkhe an skfjkla') This gives me the output sdfkisdfjs{t}dskf{h}dsklfjk{h}{e} {a}{n} skfjkl{a} I also tried nltk.re_show(r'[a|&lt;an&gt;|&lt;the&gt;]+', 'sdfkisdfjstdskfhdsklfjkhe an skfjkla') I get an output sdfkisdfjs{t}dskf{h}dsklfjk{he} {an} skfjkl{a} I don't understand why 'h' and 'he' are recognized. What could be the right regular expression in this case to recognize 'a', 'an' and 'the' in a given text?
has answer: http://stackoverflow.com/a/48527282
favorite count: 0
type: Question
score: 0

http://stackoverflow.com/comment/84128105
comment on: http://stackoverflow.com/q/48554855
score: 1
type: Comment
type: QuestionComment
has text: I just noticed this was `multi_line` your data is not in the right format at all for `multi_line`. Since it draws *multiple lines* the data provided has to be a *list of lists* (or arrays) where each sublist is for one of the separate lines. You are just giving one 1-d pandas series. I'd suggest just making separate calls to `line` for each subset you want to plot. If you really want to use `multi_line` the docs have an example of that data format: https://bokeh.pydata.org/en/latest/docs/user_guide/plotting.html#multiple-lines

http://stackoverflow.com/comment/84123148
has text: hm... tried to use query, but seems not helping.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48560811
type: QuestionComment

http://stackoverflow.com/comment/84229259
comment on: http://stackoverflow.com/a/48615936
score: 0
type: Comment
type: AnswerComment
has text: almost there. do you please have any idea what to do for this warning? I am new in odoo. Warning! Sender email is missing or empty after template rendering. Specify one to deliver your message

http://stackoverflow.com/q/48526101
tagged with: linear-algebra
has body: I have a linear space represented by a matrix, and their rows are not orthogonal. I would like to find the vector in another set of vectors with the shortest projection onto this linear space. I have a few algorithms for this, such as calculating the coefficients of projection as a linear combination of matrix vectors by solving a linear equation, or maximize the coefficients of projection, but what is the fastest way of doing this calculation?
has comment: http://stackoverflow.com/comment/84052846
answer count: 0
has comment: http://stackoverflow.com/comment/84094494
score: 1
downvote count: 0
upvote count: 1
has title: Fastest Way of Calculating The Length of Projection of Vector on Linear Space in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/84047275
type: Question
tagged with: numpy
tagged with: projection
has comment: http://stackoverflow.com/comment/84054274
has comment: http://stackoverflow.com/comment/84047252
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48533046
tagged with: python
has comment: http://stackoverflow.com/comment/84083844
score: 0
has comment: http://stackoverflow.com/comment/84103636
tagged with: bokeh
has title: Some data series extend beyond axis limits in bokeh graph
type: Question
has body: The figure below shows a portion of a plot created with the Bokeh plotting library (version 0.12.13 running under Python 3.6.4), using the bokeh.plotting interface. The graph was created by adding various time series glyphs to a figure, as in the following pseudo-code: p1 = Figure(...) # create the axes and so on p1.segment(...) # add the red line segments p1.line(...) # the dark blue line p1.quad(...) # the green rectangles p1.quad(...) # the light purple rectangles The dark blue time series line is correctly clipped to the limits of the axis frame. But the other glyphs extend beyond the horizontal axis limits (e.g. in the plot above, the red, green and purple segments and quads drawn in the axis label area). The horizontal axis is set to show only a portion of the data (10 s of 120 s worth of data). On figure creation, the axes run from t = 0: 10 s, and the out of bounds glyphs occur only on the right (there is no data for t &lt; 0), but following scrolling, glyphs appear out of bounds to the left as well, presumably because data now exists that is below the minimum axis value. Is this a bug in the latest bokeh release, or is there some parameter to explicitly control whether data series extend beyond the axis limits?
answer count: 0
has comment: http://stackoverflow.com/comment/84099664
type: UnansweredQuestion

nested
tags question: http://stackoverflow.com/q/48628860
tags question: http://stackoverflow.com/q/48593786
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/48533849
tags question: http://stackoverflow.com/q/48517177
tags question: http://stackoverflow.com/q/48626313
tags question: http://stackoverflow.com/q/48530728
tags question: http://stackoverflow.com/q/48592863
tags question: http://stackoverflow.com/q/48620892
tags question: http://stackoverflow.com/q/48594148

http://stackoverflow.com/comment/84138222
comment on: http://stackoverflow.com/a/48570724
type: Comment
has text: For that number of operations, `pandas` would be a more viable candidate. I'm assuming you have a `DataFrame` object with addresses in a column? If so you can try a `str.extract()` and it should work. I'll update the answer in a minute.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48640747
tagged with: cgi
type: Question
has answer: http://stackoverflow.com/a/48640815
tagged with: http://stackoverflow.com/tag/html
tagged with: datalist
tagged with: python
type: UnansweredQuestion
has title: Datalist in HTML form read all values with python
has answer: http://stackoverflow.com/a/48642786
has body: Is there a method to read all the values of a datalist with python? &lt;form action="/cgi-bin/file.py" method="post"&gt; &lt;div&gt; &lt;label for="name"&gt; Name &lt;/label&gt; &lt;input type="text" name="name" list="namelist" id="name"&gt; &lt;datalist id="namelist"&gt; &lt;option value="1"&gt; &lt;option value="2"&gt; &lt;option value="3"&gt; &lt;option value="4"&gt; &lt;/datalist&gt; &lt;/div&gt; with python i am able to read the selected value through the command import cgi form = cgi.FieldStorage() name=form.getvalue("name") but is there a way to put all the values in a list? ['1','2','3','4'] Thanks
score: 0
answer count: 2

http://stackoverflow.com/comment/84109036
score: 0
type: QuestionComment
has text: @juanpa.arrivillaga you should consider just answering since all your comments are pieces of the solution. Also wasn't aware `float('nan')` was a thing, that makes more sense than my `0.0` default.
type: Comment
comment on: http://stackoverflow.com/q/48556287

http://stackoverflow.com/q/48555964
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48559289
has body: I have a tensorflow graph with several modules and I would like to reuse the previous network state from one of them (before parameter update) to evaluate an input at the next state (after parameter update). Example Consider the toy example where I would like to essentially duplicate network_B at timestep t, to use at the next training step t+1: def network_A(x): A1 = tf.matmul(x, A_W1) + A_b1 return tf.nn.relu(A1) def network_B(x): B1 = tf.matmul(x, B_W1) + B_b1 Z1 = tf.nn.relu(B1) B2 = tf.matmul(Z1, B_W2) + B_b2 return B2 x = tf.placeholder(tf.float32, shape=[None, x_dim]) x_2 = network_A(x) # Evaluate input x_2 with current state of network y_hatB_current = network_B(x) # Evaluate same input x_2 with past state of network y_hatB_past = network_B_past(x) # # Get some loss loss = ... Then, once both have been evaluated, save the current state of network as the new past state, and optimize only the current state: # Save state of parameters network_B_past = network_B # (How do I do this efficiently?) # Optimize the current state train = tf.train.AdamOptimizer().minimize(loss, var_list=current_vars) Details So, at each training step there should exist two versions of network_B available to evaluate inputs: network_B at timestep t-1(past state) network_B at timestep t(current state) In between the two training steps there was a parameter update, so the weights should be slightly different between the two, but they should be identical otherwise. Then, after the new inputs are evaluated, the current state replaces the past state, and another training step occurs updating the network. I know I can save and reload checkpoints in tensorflow, but this seem too inefficient for my use case since it needs to occur at every training step. What is an effective way to achieve this network cloning step so that I maintain a copy that persists across states? Tensorflow Version: 1.5
tagged with: python
has title: How to duplicate tensorflow network state in memory for retrieval after parameter update?
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48601985
has answer: http://stackoverflow.com/a/48602304
favorite count: 0
type: Question
upvote count: 2
tagged with: peewee
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84201750
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/24048298
has body: When I use Peewee to join two tables and select attributes from both which have the same name, the last one overwrites any others. For example, with the following tables: from peewee import * db = SqliteDatabase(":memory:") class BaseModel(Model): class Meta: database = db class Module(BaseModel): name = CharField() class Student(BaseModel): name = CharField() member = ForeignKeyField(Module, related_name="members", null=True) db.create_tables([Module, Student], safe=True) And data like this: history_id = Module.create(name="History") science_id = Module.create(name="Science") Student.create(name="Tim", member=history_id) Student.create(name="Mike", member=science_id) And a Select like this: modules = Module.select( Student.name, Module.name ).join( Student, on=(Module.id == Student.member) ).group_by(Module).dicts() I get: {'name': 'History'} {'name': 'Science'} Or this, if I reverse the order in the Select: {'name': 'Tim'} {'name': 'Mike'} Does Peewee provide a way to work around this?
has title: How can I avoid overwritten attributes when joining tables with Peewee?
downvote count: 0
answer count: 1

scikit-learn
tags question: http://stackoverflow.com/q/48504914
tags question: http://stackoverflow.com/q/48511048
tags question: http://stackoverflow.com/q/48527435
tags question: http://stackoverflow.com/q/48508036
tags question: http://stackoverflow.com/q/48599923
tags question: http://stackoverflow.com/q/48641290
tag name: scikit-learn
tags question: http://stackoverflow.com/q/48631131
tags question: http://stackoverflow.com/q/48547160
tags question: http://stackoverflow.com/q/48490411
tags question: http://stackoverflow.com/q/48535829
tags question: http://stackoverflow.com/q/48566821
tags question: http://stackoverflow.com/q/48598122
tags question: http://stackoverflow.com/q/48610611
tags question: http://stackoverflow.com/q/48631907
tags question: http://stackoverflow.com/q/48552121
tags question: http://stackoverflow.com/q/48489339
tags question: http://stackoverflow.com/q/48600684
tags question: http://stackoverflow.com/q/48604845
tags question: http://stackoverflow.com/q/48593563
type: Tag
tags question: http://stackoverflow.com/q/48540401
tags question: http://stackoverflow.com/q/48587784
tags question: http://stackoverflow.com/q/48556353
tags question: http://stackoverflow.com/q/48604004
tags question: http://stackoverflow.com/q/48613394
tags question: http://stackoverflow.com/q/48541671
tags question: http://stackoverflow.com/q/48645846
tags question: http://stackoverflow.com/q/48614321
tags question: http://stackoverflow.com/q/48544522
tags question: http://stackoverflow.com/q/48588361
tags question: http://stackoverflow.com/q/48582925
tags question: http://stackoverflow.com/q/48567012
tags question: http://stackoverflow.com/q/48490792
tags question: http://stackoverflow.com/q/48570417
tags question: http://stackoverflow.com/q/48528933
tags question: http://stackoverflow.com/q/48573169
tags question: http://stackoverflow.com/q/48567861
tags question: http://stackoverflow.com/q/48634391
tags question: http://stackoverflow.com/q/48490157
tags question: http://stackoverflow.com/q/48581155
tags question: http://stackoverflow.com/q/48504029
tags question: http://stackoverflow.com/q/48527321
tags question: http://stackoverflow.com/q/48560817
tags question: http://stackoverflow.com/q/48493322
tags question: http://stackoverflow.com/q/48571985
tags question: http://stackoverflow.com/q/48561247
tags question: http://stackoverflow.com/q/48495722
tags question: http://stackoverflow.com/q/48508127
tags question: http://stackoverflow.com/q/48519470
tags question: http://stackoverflow.com/q/48639106
tags question: http://stackoverflow.com/q/48502667
tags question: http://stackoverflow.com/q/48505435
tags question: http://stackoverflow.com/q/48625353
tags question: http://stackoverflow.com/q/48578339
tags question: http://stackoverflow.com/q/48507651
tags question: http://stackoverflow.com/q/48643212
tags question: http://stackoverflow.com/q/48578235
tags question: http://stackoverflow.com/q/48549635
tags question: http://stackoverflow.com/q/48491566
tags question: http://stackoverflow.com/q/48502153
tags question: http://stackoverflow.com/q/48601420
tags question: http://stackoverflow.com/q/48503816
tags question: http://stackoverflow.com/q/48586022
tags question: http://stackoverflow.com/q/48560022

http://stackoverflow.com/q/48539562
tagged with: temperature
tagged with: python
has body: I have a temperature and humidity sensor connected to my RPi via 3.3v power, GND and SDA and SCL. I am trying to get a temperature reading from it but I keep getting a "OSerror: [Errno 121] Remote I/O error". The i2c interface is enabled and everything is up to date. I can see the address of the device using sudo i2cdetect -y 1. Could it be possible that i should be sending some data to it first so that the sensor "knows" that i am about to read from it and it should be sending data ? This is my code import smbus TEMP = 0x40 bus = smbus.SMbus(1) state = 1 while (state): print("1.Read temperature") print("2.Exit") choice = input("") if choice =='1': Ctemp = bus.read_byte(TEMP) print ("%d" %Ctemp) elif choice == '2': state = 0
has title: RaspberryPi 3 temperature sensor remote I/O error (python)
score: 1
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50889312
tagged with: raspberry-pi3
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: i2c

audacity
type: Tag
tags question: http://stackoverflow.com/q/48642216
tag name: audacity

http://stackoverflow.com/a/48523821
has body: For me working removing axis=1: print (df) A B 0 NaN NaN 1 2.0 7.0 2 3.0 8.0 3 NaN 7.0 df.fillna({'A': 'not existed'}, inplace=True) print (df) A B 0 not existed NaN 1 2 7.0 2 3 8.0 3 not existed 7.0 df.fillna({'A': 'not existed', 'B':'nwwww'}, inplace=True) print (df) A B 0 not existed nwwww 1 2 7 2 3 8 3 not existed 7
upvote count: 5
type: Answer
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48523762
downvote count: 0
has comment: http://stackoverflow.com/comment/84042618
accepted answer of: http://stackoverflow.com/q/48523762
score: 5
has comment: http://stackoverflow.com/comment/84042519

http://stackoverflow.com/comment/84165792
type: Comment
type: QuestionComment
has text: Show I must upload my source code on GCP to run the python script. However it seems that I can run it with the python I installed on my laptop and it is not required to install python anew in the virtual machine. Am I right? (So I must upload my .py files on GCP but I can use the programs of my own laptop on it like the python I installed on my laptop??)
comment on: http://stackoverflow.com/q/48584208
score: 0

http://stackoverflow.com/q/48619044
favorite count: 0
type: Question
tagged with: django-templates
has body: I am working on a project which have various apps like protocol, prediction etc. to perform some calculation "protocol" and "prediction" apps requires user input in the form of file upload. I have implemented the bellow schema which uploads file successfully into the "media" directory which is present at the base project directory. I want to implement file upload in this way so that It can upload file for respective app directory rather a common media directory. My code was like this: Views.py def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) print uploaded_file_url return render(request, 'protocol/submit_job.html', {}) return render(request, 'protocol/main_protocol.html') urls.py url(r'^protocol/$', views.simple_upload, name='simple_upload'), html Machine Learning Modeling.. Upload CSV files .. {% csrf_token %} Upload file and submit job {% if uploaded_file_url %} File uploaded successfully. {% endif %} this schema work for me and upload all the file into media directory.. What changes should I make to upload file in app specific manner. for example: prediction/Input/uploaded_file_1.csv protocol/Input/uploaded_file_2.csv I don't want to save or upload any file into model or database. Appl will delete uploaded file just before the next user input.
answer count: 2
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has title: Django file upload for different apps within a project?
type: AnsweredQuestion
score: 1
tagged with: django-models
tagged with: django-forms
has answer: http://stackoverflow.com/a/48619213
possible better answer: http://stackoverflow.com/a/48619213
has answer: http://stackoverflow.com/a/48619423
accepted answer: http://stackoverflow.com/a/48619423

http://stackoverflow.com/a/48629803
answers question: http://stackoverflow.com/q/48629695
score: 7
type: Answer
has body: One straightforward way to do non-repeating 'random' (psudeorandom) whole numbers in a modest range is to create a list using range(1, n), then random.shuffle() the list, and then take as many numbers as you want from the list using pop() or a slice. import random max = 11 l = list(range(1, max)) # the cast to list is optional in Python 2 random.shuffle(l) Now every time you want a random number, just l.pop(). Another is to use random.sample() -- see https://docs.python.org/3/library/random.html
accepted answer of: http://stackoverflow.com/q/48629695
type: AcceptedAnswer
downvote count: 0
upvote count: 7

http://stackoverflow.com/q/48514027
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/84035597
score: 5
tagged with: windows
upvote count: 5
tagged with: spyder
tagged with: python
possible better answer: http://stackoverflow.com/a/51549759
has title: Spyder3 Python IDE does not start: "This Windows version does not support the required Bluetooth API"
has answer: http://stackoverflow.com/a/51549759
has comment: http://stackoverflow.com/comment/84036080
accepted answer: http://stackoverflow.com/a/48521636
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48521636
downvote count: 0
has body: Been using spyder3 IDE to play around with python. I reformatted my computer recently and then ran into this problem when starting sypder: My usual steps after a computer format are: 1) Install Python 3 from python.org windows .exe download. 2) Run these commands in command prompt. pip install PyQt5 pip install spyder 3) Using explorer, navigate to python/scripts/ and double clicked on spyder3.exe. 4) Usually spyder3 will start now, but recently I have been getting this error box: Windows Error Box "This Windows version (6.3.9600) does not support the required Bluetooth API. Consider updating to a more recent Windows (10.0.10586 or above)." I reformatted my computer again, reinstalled everything but the problem is persisting. I tried to load spyder3 by downloading the spyder .zip git-hub and using the following command: python bootstrap.py but this leads me to the same error message. Both these methods worked fine before, I am unsure what caused it and how to proceed. Kindly asking for your insights :)
favorite count: 0

http://stackoverflow.com/q/48566268
has answer: http://stackoverflow.com/a/48566405
type: Question
tagged with: python
has title: Applying age function to data-frame column
has body: I have a dataframe df with a column date of birth. The head looks like: Date of birth 0 1957-04-30 1 1966-11-10 2 1966-11-10 3 NOT KNOWN 4 1958-10-28 5 1958-06-04 I also have a variable called referencePeriodEndDate which is a date in a yyyy-mm-dd format and for example looks like 2017-03-31 I am trying to create a new column called Age which is the age of from the Date of birth upto the referencePeriodEndDate so the function to apply to each row would looks like: (`referencePeriodEndDate` - df["Date of birth"]) / 365.25 There is the potential for rows in the Date of birth column to be empty (null) or have the entry 'NOT KNOWN' so I need to return the value 'NOT KNOWN' to the effected column in the new Age column. I have come up with the following but it refuses to work (or return an error) df["Age"].apply(lambda row: TimeCalc(df,referencePeriodEndDate) if row.notnull() else "NOT KNOWN") def TimeCalc(rawDatabase,referencePeriodEndDate): Age = ((referencePeriodEndDate - rawDatabase["Date of birth"]) / 365.25) return Age The desired output would look like: Date of birth Age 30/04/1957 59.91786448 10/11/1966 50.38740589 10/11/1966 50.38740589 NOT KNOWN NOT KNOWN 28/10/1958 58.42299795 04/06/1958 58.82272416
type: AnsweredQuestion
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84128781
has comment: http://stackoverflow.com/comment/84128586
answer count: 1
accepted answer: http://stackoverflow.com/a/48566405

http://stackoverflow.com/q/48632346
has answer: http://stackoverflow.com/a/48632827
tagged with: python
has title: How to parse this XML to python array or dict?
has comment: http://stackoverflow.com/comment/84263783
has body: This is a snippet of the XML I am trying to parse: <Threshold name="MinNumEvents" value="5"/> <Threshold name="AbandonAfterSuccessiveFailures" value="3"/> <Threshold name="MinNumEvents" value="5"/> <Threshold name="AbandonAfterSuccessiveFailures" value="3"/> What I did so far (part of the code): ta_dsms = [] for level1 in root: if level1.tag == 'DSMs': for level2 in level1: ta_dsm = level2.attrib ta_dsms.append(ta_dsm) print ta_dsms The current output of ta_dsms is like: [{'class': 'ACE', 'order': '320'}, {'class': 'ACS', 'order': '1900'}, ...] My question is what the elegant way is to get Thresholds and Templates info and add them to my array. Only some DSMs have children. I've been stuck on this all day. Thank you for saving my life!
type: AnsweredQuestion
score: 3
tagged with: xml.etree
possible better answer: http://stackoverflow.com/a/48632827
has comment: http://stackoverflow.com/comment/84263141
upvote count: 3
tagged with: elementtree
accepted answer: http://stackoverflow.com/a/48632824
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48632824
has comment: http://stackoverflow.com/comment/84263459
downvote count: 0

http://stackoverflow.com/comment/84156743
comment on: http://stackoverflow.com/q/48574135
has text: Hi, are you running this on 32 bit linux machine?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84196746
type: Comment
has text: Thanks! Do you understand why the Delaunay `convex_hull` and the default `scipy.spatial.ConvexHull` function so differently?
type: AnswerComment
comment on: http://stackoverflow.com/a/48592328
score: 0

http://stackoverflow.com/comment/84216253
has text: In what situation do you need this? What is the context?
comment on: http://stackoverflow.com/q/48609626
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84175847
score: 0
type: Comment
type: QuestionComment
has text: @slalomchip. This is impossible to answer unless you provide a [mcve]. There are any number of ways that the keyboard focus could be stolen by other widgets when the program starts up. Obviously the code in your question will work perfectly fine in a simple example with only one button.
comment on: http://stackoverflow.com/q/48583776

http://stackoverflow.com/a/48604311
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48604141
has body: This piece of code in NumPy's definition of np.piecewise is list/ndarray-centric: # undocumented: single condition is promoted to a list of one condition if isscalar(condlist) or ( not isinstance(condlist[0], (list, ndarray)) and x.ndim != 0): condlist = [condlist] Thus, if X is a Series, then condlist = [X&lt;=x1, X&gt;=x2] is a list of two Series. Since condlist[0] is neither a list nor an ndarray, condlist is "promoted" to a list of one condition: condlist = [condlist] Since this is not what we want to happen, we need to make condlist a list of NumPy arrays before passing it to np.piecewise: X = X.values For example, import numpy as np import pandas as pd def model_b(X, x1, x2, m1, b1, m2, b2): def lo(x): return m1 * x + b1 def hi(x): return m2 * x + b2 def mid(x): y1 = m1 * x + b1 y2 = m2 * x + b2 # a, b, c, d = fit_cubic(x1, y1, x2, y2, m1, m2) a, b, c, d = 1, 2, 3, 4 return a * x * x * x + b * x * x + c * x + d X = X.values return np.piecewise(X, [X&lt;=x1, X&gt;=x2], [lo, hi, mid]) X = pd.Series(np.linspace(0, 100, 100)) x1, x2, m1, b1, m2, b2 = 30, 60, 10, 5, -20, 30 f = model_b(X, x1, x2, m1, b1, m2, b2)
downvote count: 0
answers question: http://stackoverflow.com/q/48604141
type: AcceptedAnswer
score: 6

http://stackoverflow.com/comment/84021655
comment on: http://stackoverflow.com/q/48513445
has text: "get my code to work" - please include your code.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84131558
has text: @Eric: I tested it, with numpy (`return s_[1:-1]`) it takes `2.986656811001012s` for 10M runs, for `return (slice(1, -1),)`, it takes 1.8174990950210486s.
comment on: http://stackoverflow.com/a/48559229
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84156907
comment on: http://stackoverflow.com/q/48578385
type: Comment
type: QuestionComment
has text: Sorry Jose A, i haven't try it. I just guess and i don't read your answer carefully. Sorry for that and Thanks for your answer too,
score: 0

http://stackoverflow.com/comment/84064059
has text: Possible duplicate of [jupyter notebook import error: no module named 'matplotlib'](https://stackoverflow.com/questions/43437884/jupyter-notebook-import-error-no-module-named-matplotlib)
type: QuestionComment
comment on: http://stackoverflow.com/q/48534303
score: 2
type: Comment

http://stackoverflow.com/a/49902543
upvote count: 1
downvote count: 1
has body: Vishal Khichadiya in the post above found the solution. However, I think you should start from understanding how it works. Two ways of fast learning would be: Download some simple apps and see the files, learn how they are built and try to replicate it. I would recommend starting with simple view edits. Activate the developer mode and make some front-end changes. If it is possible to save and things are working simply replace your front-end changes with a module. The easiest would be editing the list /tree views - add some stuff here and there. What version of Odoo should you use? Probably 11 is the only right version as it is using different Python version than 10 and older. Get familiar with official Odoo forum as you might get an instant help in there.
type: Answer
answers question: http://stackoverflow.com/q/48552182
score: 0

http://stackoverflow.com/q/48565353
answer count: 1
has comment: http://stackoverflow.com/comment/84126708
tagged with: pendulum
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84126599
has comment: http://stackoverflow.com/comment/84126890
type: AnsweredQuestion
has body: In physics, for a pendulum with length L and initial angle A, its horizontal >displacement X(T) at time T is given by the formula X(T) = L × cos(A × cos(T × √9.8/L)) - L × cos(A) Write a program which takes two lines of input; the first line is L and the >second line is A. The output should be ten lines, giving the values of X(0), >X(1), X(2), ..., X(9). For example, if the first line of input is 53.1 and the >second line of input is 0.8, then the first line of output is 0.0 and the second >line of output is 53.1*cos(0.8*cos(1*√9.8/53.1)) - 53.1*cos(0.8) ~ 2.6689. import math L = float(input()) A = float(input()) for T in range (0,9): print(L*math.cos(A*math.cos(T*math.sqrt(9.8/L))-L*math.cos(A))) i have written this and i cant understand what am i doing wrong ? input : 53.1 0.8 my output: 3.545012155898153 7.383727226708044 17.92714440725987 31.889478979714276 44.23118522394127 51.212404291669216 53.079364553814806 52.890770379027806 52.999922313121566 expected answer: 0.0 2.6689070487226805 9.021742145820763 14.794542557581206 15.73774678328343 11.124903835610114 4.423693604072537 0.27377375601245213 1.295906539090336 6.863309996333497
tagged with: python
score: -1
has title: Coding Exercise: Watch the Pendulum
type: Question
accepted answer: http://stackoverflow.com/a/48565527
upvote count: 0
has answer: http://stackoverflow.com/a/48565527
has comment: http://stackoverflow.com/comment/84126931

http://stackoverflow.com/q/48569341
tagged with: arrays
has title: Replace diagonals of a 2D array with python
tagged with: diagonal
has answer: http://stackoverflow.com/a/48569377
tagged with: python
downvote count: 0
has body: I have the following 2D array A=([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]) And I want to replace the main diagonal by the array a = ([0,2,15,20]) Therefore, the results must be A=([[0, 2, 3, 4], [5, 2, 7, 8], [9, 10, 15, 12], [13, 14, 15, 20]) I tried with np.diag(a, k=0) but it doesn't work because np.diag() creates a diagonal 2D array with the array "a". Is there a way to do that with numpy? The above example is the simplest one. I would like to be able to change not only the mail diagonal but all diagonals.
duplicate of: http://stackoverflow.com/q/9958577
has answer: http://stackoverflow.com/a/48569368
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
score: 5
upvote count: 5
linked to: http://stackoverflow.com/q/9958577
type: UnansweredQuestion

http://stackoverflow.com/comment/84100097
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48549018
score: 0
has text: `ipython` does a nice job of providing this kind of help, with tab complete, and `?` (docs) and `??` (code). You could play with that to see what kinds of signature you can access and for what.

http://stackoverflow.com/comment/84024750
type: Comment
type: QuestionComment
has text: code looks right, whats the problem? do you want to send the selected `checkbox` to the server to decide on it? then you need js code to send `ajax` requests.
score: 0
comment on: http://stackoverflow.com/q/48512055

http://stackoverflow.com/q/48571080
type: Question
has title: Failed to convert object of type <class 'zip'> to Tensor
tagged with: numpy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84140545
has comment: http://stackoverflow.com/comment/84138873
tagged with: python
has comment: http://stackoverflow.com/comment/84138993
has comment: http://stackoverflow.com/comment/84138937
has comment: http://stackoverflow.com/comment/84140540
has comment: http://stackoverflow.com/comment/108196416
score: 2
answer count: 0
upvote count: 2
downvote count: 0
tagged with: machine-learning
has body: I am implementing K-nearest algorithm in Tensorflow from the book "Getting started in Tensorflow" , But I am getting the error when I am setting the zipped variable as tensorflow constant . Here is my code: x_values = [] y_values = [] vector_values = [] for i in range(num_vectors): if np.random.random() &gt; 0.5: x_values.append(np.random.normal(0.4,0.7)) y_values.append(np.random.normal(0.2,0.9)) else: x_values.append(np.random.normal(0.1,0.3)) y_values.append(np.random.normal(0.15,0.6)) vector_values = zip(x_values,y_values) vectors = tf.constant(vector_values) The idle is showing the error : TypeError: Failed to convert object of type &lt;'class 'zip'> to Tensor. Contents: &lt;'zip object at 0x000001AE523EFE08>. Consider casting elements to a supported type
has comment: http://stackoverflow.com/comment/84138892
has comment: http://stackoverflow.com/comment/84139420
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/48510248
has comment: http://stackoverflow.com/comment/84015527
has answer: http://stackoverflow.com/a/48511633
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84015503
has comment: http://stackoverflow.com/comment/84042365
has comment: http://stackoverflow.com/comment/84061339
has comment: http://stackoverflow.com/comment/84015493
upvote count: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84015567
has comment: http://stackoverflow.com/comment/84015755
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84017985
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84042293
has comment: http://stackoverflow.com/comment/84017020
tagged with: python
has body: I am working on a tutorial which reads a csv file : # Read the data and append SENTENCE_START and SENTENCE_END tokens with open('data/reddit-comments-2015-08.csv', 'rb') as f: reader = csv.reader(f, skipinitialspace=True) reader.next() # Split full comments into sentences sentences = itertools.chain(*[nltk.sent_tokenize(x[0].decode('utf- 8').lower()) for x in reader]) # Append SENTENCE_START and SENTENCE_END sentences = ["%s %s %s" % (sentence_start_token, x, sentence_end_token) for x in sentences] print "Parsed %d sentences." % (len(sentences)) but get the following error: sentences = itertools.chain(*[nltk.sent_tokenize(x[0].decode('utf-8').lower()) for x in reader]) IndexError: list index out of range Can anyone help me with that. I am new in nltk.
accepted answer: http://stackoverflow.com/a/48511633
has title: How to read, clean and append START and END token to a csv-like file?

http://stackoverflow.com/q/48619011
type: UnansweredQuestion
tagged with: python
score: 0
has title: Tkinter Treeview get element calling function
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84234946
tagged with: treeview
answer count: 1
has comment: http://stackoverflow.com/comment/84234596
type: Question
has comment: http://stackoverflow.com/comment/84234703
has answer: http://stackoverflow.com/a/48619619
has body: I am generating my own Tkinter.Treeview and calling a function if a tag gets clicked. Inside those function I want to get the element of the Treeview that was clicked. Or being more precise i want to get the values of the element. Therefore I have tried the following but do just get back the name of the element as a string not as an item object. def element_clicked(event): item = event.widget.focus() value = item["values"] If the item which was clicked have been generated the following way ... ttk.Treeview(mainWindow).insert("", "end", iid, text="MyElement", values=["The value I want to pass to my function!!!"]) ... I do get back "MyElement" and values can't be read out of a string Any ideas how to get the item and its values calling the function element_clicked()?

http://stackoverflow.com/q/48620923
accepted answer: http://stackoverflow.com/a/48621632
tagged with: multidimensional-array
tagged with: python
has title: How to vectorize extraction in multidimensional numpy array
tagged with: vectorization
has comment: http://stackoverflow.com/comment/84238773
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84242040
has answer: http://stackoverflow.com/a/48621632
downvote count: 0
has comment: http://stackoverflow.com/comment/84238809
answer count: 1
linked to: http://stackoverflow.com/q/48191060
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy
duplicate of: http://stackoverflow.com/q/48191060
has body: I am struggling with a vectorization problem which seems to be simple at first glance: Let's say I have 100 images of size (7, 7) with 2 channels represented by a numpy array of size (100, 2, 7, 7). I would like to extract on all images small patches (let say of size (2, 3, 3)), but these patches are not located at the same place on every image. Locations of the patch are described by a matrix of size (2, 100) (one x and one y for each image). I am able to do that with a for loop over all images, but it takes time. Here is an example code : data = np.arange(9800).reshape((100, 2, 7, 7)) size = 3 pos = np.random.randint(0, 7-size, (2, 100)) for i in range(a.shape[0]): patch = data[i, :, pos[0,i]:(pos[0,i]+size), pos[1,i]:pos[1,i]+size] In other words, I'd like to reproduce this code without the for loop. Does anyone have a clue to do that?
tagged with: extract

http://stackoverflow.com/a/48588623
has body: If you are iterating over an multiindex, idx is a tuple, therefore you should use df.loc[list(idx)], this gives the expected result: In [22]: df.loc[list(idx)] Out[22]: 5_x 5_y _merge id_stock 1 3 0 1949 37,5 cl Château LAFITE ROTHSCHILD 759.0 798.0 both 35 Château LAFITE ROTHSCHILD 798.0 759.0 both 36 EDIT: You can also do the same with df.loc[slice(idx)], compare Multiindexing in the docs. EDIT2: Compare the following ones: In [38]: tuple(idx) Out[38]: (1949, '37,5 cl ', 'Ch\xc3\xa2teau LAFITE ROTHSCHILD ') In [39]: (idx) Out[39]: (1949, '37,5 cl ', 'Ch\xc3\xa2teau LAFITE ROTHSCHILD ') In [40]: list(idx) Out[40]: [1949, '37,5 cl ', 'Ch\xc3\xa2teau LAFITE ROTHSCHILD '] In [41]: [idx] Out[41]: [(1949, '37,5 cl ', 'Ch\xc3\xa2teau LAFITE ROTHSCHILD ')] The two first ones don't work while the last two does.
has comment: http://stackoverflow.com/comment/84218299
type: Answer
has comment: http://stackoverflow.com/comment/84192457
score: -1
has comment: http://stackoverflow.com/comment/84174802
upvote count: 0
has comment: http://stackoverflow.com/comment/84246363
downvote count: 1
has comment: http://stackoverflow.com/comment/84174721
answers question: http://stackoverflow.com/q/48588412
has comment: http://stackoverflow.com/comment/84178427

http://stackoverflow.com/q/48545534
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: import cv2 recognizer = cv2.createLBPHFaceRecognizer() AttributeError: 'module' object has no attribute 'createLBPHFaceRecognizer' can you guys please help me solve this error? I tried pip install opencv-contrib-python , but still the same error. I am using Python 2.7 and opencv3.
tagged with: python
tagged with: opencv
linked to: http://stackoverflow.com/q/43294668
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/84679937
has title: setting up createLBPHFaceRecognizer
favorite count: 0
type: Question

http://stackoverflow.com/a/48540810
has comment: http://stackoverflow.com/comment/84077237
has comment: http://stackoverflow.com/comment/84077154
has comment: http://stackoverflow.com/comment/84076945
has comment: http://stackoverflow.com/comment/84076855
type: Answer
has comment: http://stackoverflow.com/comment/84077095
has comment: http://stackoverflow.com/comment/84077608
upvote count: 0
score: -1
has body: This seems the most pythonic: csv_line = 'unknown_item1,old_item2,unknown_item3' old_index = 1 new_item = 'new_item2' goal = 'unknown_item1,new_item2,unknown_item3' items = csv_line.split(',') items[old_index] = new_item print(','.join(items)) print(goal) Output: unknown_item1,new_item2,unknown_item3 unknown_item1,new_item2,unknown_item3
downvote count: 1
answers question: http://stackoverflow.com/q/48540690

http://stackoverflow.com/a/48536382
downvote count: 0
has comment: http://stackoverflow.com/comment/84073372
has comment: http://stackoverflow.com/comment/84068256
answers question: http://stackoverflow.com/q/48536058
has comment: http://stackoverflow.com/comment/84073709
type: Answer
has comment: http://stackoverflow.com/comment/84070973
score: 2
has comment: http://stackoverflow.com/comment/84071565
upvote count: 2
has body: Here is a possible solution. Probably not the most beautiful one, so curious to see other solution approaches. df1 = data.frame(name = c("(CKMB)Creatinine Kinase Muscle &amp; Brain", "24 Hours Urine for Sodium", "Antistreptolysin O Titer", "Blood group O"), lonic_code = c("27816-8-O", "27816-8-B", "1869-7", "33914-3")) df2 = data.frame(Testcomponents = c("creatinine", "blood", "potassium")) result = lapply(sapply(df2$Testcomponents,function(x) { which(sapply(df1$name,function(y) {grepl(x,y,ignore.case = T)}))}),function(z) {df1$lonic_code[z]}) df2$Ionic_code= result Output: Testcomponents Ionic_code 1 creatinine 3 2 blood 4 3 potassium

http://stackoverflow.com/a/49472005
has comment: http://stackoverflow.com/comment/95495887
has body: From textmining package ,excerpt of TDM Class import re import csv import os ''' import stemmer ''' you can save the below code as a separate python file and import it as a regular module in your code e.g create_tdm.py import create_tdm X = create_tdm.TermDocumentMatrix("your Text ") ''' for Vocab ''' word2id = dict((v, idx) for idx, v in enumerate(" your text" )) ''' Make sure list of guided words should be there in your text else you will get key error , just to check import pandas as pd c = pd.DataFrame(list(word2id)) ''' class TermDocumentMatrix(object): """ Class to efficiently create a term-document matrix. The only initialization parameter is a tokenizer function, which should take in a single string representing a document and return a list of strings representing the tokens in the document. If the tokenizer parameter is omitted it defaults to using textmining.simple_tokenize Use the add_doc method to add a document (document is a string). Use the write_csv method to output the current term-document matrix to a csv file. You can use the rows method to return the rows of the matrix if you wish to access the individual elements without writing directly to a file. """ def __init__(self, tokenizer=simple_tokenize): """Initialize with tokenizer to split documents into words.""" # Set tokenizer to use for tokenizing new documents self.tokenize = tokenizer # The term document matrix is a sparse matrix represented as a # list of dictionaries. Each dictionary contains the word # counts for a document. self.sparse = [] # Keep track of the number of documents containing the word. self.doc_count = {} def add_doc(self, document): """Add document to the term-document matrix.""" # Split document up into list of strings words = self.tokenize(document) # Count word frequencies in this document word_counts = {} for word in words: word_counts[word] = word_counts.get(word, 0) + 1 # Add word counts as new row to sparse matrix self.sparse.append(word_counts) # Add to total docume…
type: Answer
answers question: http://stackoverflow.com/q/48594449
score: 0

http://stackoverflow.com/a/50744763
has body: I would recommend to use some Python SNMP library to ease parsing the output. You can use e.g. Net-SNMP Python Bindings. See docs for details. Simplified example of usage: import netsnmp session = netsnmp.Session(DestHost="SOME_DEVICE_NAME", Version=2, Community="public") session.UseLongNames = 1 session.UseNumeric = 1 oid=".1.3.6.1.4.1.2636.3.1" vars = netsnmp.VarList(oid) session.walk(vars) # to check errors: if len(session.ErrorStr) &gt; 0: # to get output values for item in vars: print item.val Then you can use some regex parsing etc.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48574086

http://stackoverflow.com/q/48632242
type: AnsweredQuestion
score: 1
tagged with: datetime
has comment: http://stackoverflow.com/comment/84262189
tagged with: python
linked to: http://stackoverflow.com/q/7588511
accepted answer: http://stackoverflow.com/a/48632487
has body: I have two datetime objects which are 02:49:01.210000 and 02:49:01.230000: RA_1 = datetime.datetime.strptime(obs_data['RA'][3], "%H:%M:%S.%f").time() RA_2 = datetime.datetime.strptime(pred_data['RA'][3], "%H:%M:%S.%f").time() How do I workout the difference between these two times in milliseconds? I tried doing RA_1 - RA_2 but got the error: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' I also tried using total_seconds() but got the error: 'datetime.time' object has no attribute 'total_seconds'
has comment: http://stackoverflow.com/comment/84261795
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84261650
has answer: http://stackoverflow.com/a/48632487
has comment: http://stackoverflow.com/comment/84261591
downvote count: 0
answer count: 1
upvote count: 1
has title: How do I find the difference in milliseconds between two datetime objects in Python?
favorite count: 0
type: Question

http://stackoverflow.com/a/48641381
has comment: http://stackoverflow.com/comment/84279446
has body: Probably if you do CTRL-C it'll stop running. About your data, your output it'll be still there, and if you created any log text file it's going to be there for sure.
type: Answer
answers question: http://stackoverflow.com/q/48641217
score: 0
has comment: http://stackoverflow.com/comment/84286874

http://stackoverflow.com/comment/84220938
type: QuestionComment
comment on: http://stackoverflow.com/q/48612170
score: 0
has text: 0.930193522906793 for validation, 0.9384887344199425 for train and 0.9331556082148499 for test
type: Comment

http://stackoverflow.com/q/48593029
tagged with: tensorflow
type: Question
has body: I'm trying to learn image classification in python using tensorflow, and I'm unsure of how to read in my folder of images. I have a training set of over 10,000 .jpeg images. I have been working with the MNIST tutorial and others, but I don't see any information on importing an entire folder without creating an array of all the images by each image path (which is not possible at this size). Any suggestions?
answer count: 2
has title: Python Import Folder of .jpeg files
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
tagged with: http://stackoverflow.com/tag/jpeg
has comment: http://stackoverflow.com/comment/84183419
has answer: http://stackoverflow.com/a/48593539
score: 0
has answer: http://stackoverflow.com/a/48593610
has comment: http://stackoverflow.com/comment/84183446

http://stackoverflow.com/q/48545726
has comment: http://stackoverflow.com/comment/84093688
has answer: http://stackoverflow.com/a/48545970
tagged with: python
has body: so, I'm trying to read a weird .csv files which has comma separated values, but since each pair of columns represent a different typology of data these are separated by two commas ',,'. On top of that there are missing values in some specific columns after a certain row (see following minimal example) row1: -2.418809,0.004107006,,359.896,1.86897E-07,,359.896,2.958411,,-2.419437,0.1012164,,359.9048,2.095844E-06,,359.9048,-2.049214 row2 -2.41644,0.004659269,,,,,,,,-2.417068,0.1013545,,,,,, I've tried to address the problem using the approach described in the answers here but without success because loadtxt can't handle missing values At the moment I'm trying to read it with numpy.loadtxt specifying only the columns which go on till the end: import numpy as np data = np.loadtxt(name, delimiter=',', unpack=True, usecols=(0,1,6,7)) but I'm obtaining an error: ValueError: could not convert string to float Does anyone have any idea if there is a simple way to solve this?
score: -1
type: Question
tagged with: text
tagged with: numpy
has answer: http://stackoverflow.com/a/48549055
upvote count: 0
type: UnansweredQuestion
has title: python: read complicated csv files
linked to: http://stackoverflow.com/q/25206016
has comment: http://stackoverflow.com/comment/84087178
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84090734
has answer: http://stackoverflow.com/a/48546106
linked to: http://stackoverflow.com/q/20007017
answer count: 3
linked to: http://stackoverflow.com/q/34097228
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/48526097
type: Answer
accepted answer of: http://stackoverflow.com/q/48525825
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: In group 'AB', the promoted variable 'x' is already connected to a source: self.add('x', IndepVarComp('x', val=0.0), promotes=['*']) self.connect('x', ['A.x', 'B.x']) In the top group 'ABC', that same 'x' variable is 'AB.x', but you try to connect it again to another indepvarcomp: self.add('x', IndepVarComp('x', val=0.0), promotes=['*']) self.connect('x', ['AB.x', 'C.x']) I would recommend removing the IndepVarComp and connection down inside of 'AB' to solve this problem. To be more clear, you can't connect a component input up to 2 different sources at the same time. If those two sources have 2 different values, then which one is correct? It is ambiguous, so we don't allow it.
answers question: http://stackoverflow.com/q/48525825
has comment: http://stackoverflow.com/comment/84050460
score: 2

http://stackoverflow.com/comment/84132706
score: 0
comment on: http://stackoverflow.com/q/48568022
type: Comment
has text: Thanks, there is no error message it just stops.....
type: QuestionComment

http://stackoverflow.com/comment/84193318
type: Comment
type: AnswerComment
has text: Also you might want to [watch this MIT OpenCourseWare video about SVMs](https://www.youtube.com/watch?v=_PwhiWxHK8o) to get the intuition.
comment on: http://stackoverflow.com/a/48528155
score: 0

http://stackoverflow.com/q/48552786
type: AnsweredQuestion
tagged with: odoo
has comment: http://stackoverflow.com/comment/84114572
tagged with: python
has comment: http://stackoverflow.com/comment/84114447
type: Question
score: 1
has title: Odoo 10 page reload
has body: I´m trying to reload the web page from custom js button after creating a record via calling a method from Python: @api.multi def create_period(self): self.create({ 'name': '11', 'code': '12', 'date_start': '2018-01-01', 'date_stop': '2018-12-31', }) return { 'type': 'ir.actions.client', 'tag': 'reload', } but it is not refreshing. What can i do?
accepted answer: http://stackoverflow.com/a/48561013
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48561013
has comment: http://stackoverflow.com/comment/84111302
favorite count: 0

http://stackoverflow.com/a/48506223
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48506130
has comment: http://stackoverflow.com/comment/90094468
type: Answer
has body: In Python, functions are first-class citizens. This means that you can assign functions to names just like you assign other values. In particular, you can add a function to a class like this: class Foo: def foo(self): print('foo') def bar(self): print('bar') Foo.bar = bar f = Foo() f.foo() f.bar() Note that even though bar() is declared globally, it still must take at least one parameter. Traditionally, the first parameter of member functions is called self but this is only a convention and is not enforced by the language.

http://stackoverflow.com/q/48572674
has title: list comprehension with if and break
has comment: http://stackoverflow.com/comment/84142636
has comment: http://stackoverflow.com/comment/84142230
upvote count: 3
has comment: http://stackoverflow.com/comment/84142432
has comment: http://stackoverflow.com/comment/84142881
has comment: http://stackoverflow.com/comment/84143547
has comment: http://stackoverflow.com/comment/84142451
has comment: http://stackoverflow.com/comment/84143570
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48573093
possible better answer: http://stackoverflow.com/a/48573093
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/84142482
tagged with: python
has comment: http://stackoverflow.com/comment/84142593
tagged with: list-comprehension
downvote count: 1
has body: Is it possible to do this trick with a list comprehension: queries = """watch movie online, sport news, movie poster, course of events, movie in this summer, python course, serials about sports, watch movie about training course""" keywords = ['movie','course'] all good with this method for x in queries.split(','): for y in keywords: if y in x: print(x) break when i used a list comprehension like this: r = [print(x) for x in queries.split(',') for y in keywords if y in x] I have 2-time result with a match on two 2 keywords watch movie about training course When i use method in this example i had an error 'list' object is not an iterator
has comment: http://stackoverflow.com/comment/84142417
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48573032
accepted answer: http://stackoverflow.com/a/48573032
linked to: http://stackoverflow.com/q/9014058

http://stackoverflow.com/comment/84079142
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48540716
has text: This worked! Thanks! Oddly, this is the first time that I am seeing this way of writing a list, and oddly, the other list 'columnNames' are just separated by parenthesis and they are also working. Is there a reason for this working and not the other ways? Thanks again!
type: Comment

http://stackoverflow.com/comment/84030622
type: QuestionComment
comment on: http://stackoverflow.com/q/48517244
type: Comment
has text: @GPhilo thank you, clarification added! As I said, the context is different for each batch, but same for every sample within one batch. What I mean is that I cannot store all the context arrays for all of the batches in the graph and then read from there, since storing all of them statically in the graph is prohibitive in terms of the memory required. The 2GB limit for a `GraphDef` is quickly exceeded and the graph cannot be store to disk anymore, for example. In contrast, what I *can* do is input a single context array for the current batch, and I want to include this in my input pipeline.
score: 0

http://stackoverflow.com/a/48597305
has comment: http://stackoverflow.com/comment/84205995
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48597234
score: 1
downvote count: 0
has body: You could use .format() whenever you need to insert variable name into string: execfile("/a/b/c/{0}".format(folder_name)) Note that {0} here corresponds to first argument that you pass to format function. Similarly, {1}, {2},... corresponds to second, third,.. arguments of format function respectively. You could also use % operator, but note that it is deprecated as of Python 3.1.

http://stackoverflow.com/a/48571595
has comment: http://stackoverflow.com/comment/84139929
has comment: http://stackoverflow.com/comment/84140446
upvote count: 1
has comment: http://stackoverflow.com/comment/84157734
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48571555
score: 1
has comment: http://stackoverflow.com/comment/84140915
type: Answer
has body: Something like: from collections import Counter cnt = Counter() with open('file.txt', 'r') as f: for line in f: cnt[line] += 1 for k, v in cnt.iteritems(): print v, k
accepted answer of: http://stackoverflow.com/q/48571555
downvote count: 0

http://stackoverflow.com/comment/84288646
type: QuestionComment
comment on: http://stackoverflow.com/q/48645531
score: 0
has text: @ Dalton well in the application only. For example if you right click on internet explorer, it will have the part sign in as different user. I want to automate that part with python IE webdriver, but I do not know how to do it.
type: Comment

http://stackoverflow.com/q/48507340
answer count: 0
score: 3
has body: I have a Flask (with Flask-restplus) app running locally on port 5000. When I launch the app locally and go below URL I can see the Swagger UI. http://localhost:5000/api/# But when I run it behind NGINX, gunicorn and go to http://localhost:81/api/# I get below error Can't read from server. It may not have the appropriate access-control-origin settings. When I look at the chrome error I see a request being made to http://localhost/api/swagger.json Colud this be the problem as the NGINX container is running on port 81? $(function () { window.swaggerUi = new SwaggerUi({ url: "http://localhost/api/swagger.json", validatorUrl: "" || null, dom_id: "swagger-ui-container", supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'], onComplete: function(swaggerApi, swaggerUi){ }, onFailure: function(data) { log("Unable to Load SwaggerUI"); // &lt;&lt;&lt;-- This is where it breaks }, }); window.swaggerUi.load(); However I am able to make a postman request to my through http://localhost:81/api/centres/1 and I get expected data After googling since last three days the options are: To send CORS headers on response. I dont prefer this as it is a security risk. To configure NGINX to redirect requests to correct url (http://flask.pocoo.org/snippets/35/) This is what my server config looks like server { listen 81; charset utf-8; # Configure NGINX to reverse proxy HTTP requests to the upstream server (Gunicorn (WSGI server)) location / { # Define the location of the proxy server to send the request to proxy_pass http://web:8000; proxy_redirect http://localhost/api http://localhost:81/api; # Redefine the header fields that NGINX sends to the upstream server proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; } } It still doesnt show me the swagger UI. I'm a newbie to this world of Docker, Nginx and gunicorn. How can fix this issue?
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: nginx
type: UnansweredQuestion
tagged with: python
has title: swagger UI not reachable while running on Docker proxied through Nginx and hosted by gunicorn
tagged with: swagger-ui
tagged with: docker
has comment: http://stackoverflow.com/comment/104772291
tagged with: flask-restplus

http://stackoverflow.com/comment/84119182
type: Comment
comment on: http://stackoverflow.com/q/48559509
has text: and another useful ressource may be is here : https://forum.predix.io/articles/24718/how-to-specify-a-python-version-for-your-app.html
score: 0
type: QuestionComment

http://stackoverflow.com/a/48602334
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84201507
has comment: http://stackoverflow.com/comment/84201349
has body: You shouldn't be trying to roll your own CSV writer. You should use the csv module's CSVWriter object: import csv with open('output.csv', 'w') as store: writer = csv.writer(store) for row in [i, j, k]: writer.writerow((np.array(row)).tolist())
has comment: http://stackoverflow.com/comment/84204810
has comment: http://stackoverflow.com/comment/84201475
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48602238
type: Answer
has comment: http://stackoverflow.com/comment/84201391
answers question: http://stackoverflow.com/q/48602238

http://stackoverflow.com/q/48615638
type: Question
tagged with: xpath
tagged with: selenium-ide
type: UnansweredQuestion
tagged with: python
has body: I am trying to automate instagram by using selenium and python. I went till login without any problem. But after logging in, instagram pops up a window saying "experience the best version of instagram by getting the app" which is a download link of instagram app. I want to ignore this download pop up window, and having trouble with it 1)no buttons to click, only close(❌) button. 2)xpath of close(❌) button not working Please help me And thank you
tagged with: selenium-chromedriver
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: selenium
has title: Handling app download window in selenium using python
has answer: http://stackoverflow.com/a/48617310
favorite count: 0

http://stackoverflow.com/q/48526062
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84054954
has comment: http://stackoverflow.com/comment/84089760
has comment: http://stackoverflow.com/comment/84069123
has comment: http://stackoverflow.com/comment/84049160
has comment: http://stackoverflow.com/comment/84047113
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
tagged with: save
downvote count: 0
has comment: http://stackoverflow.com/comment/84049132
score: 1
has comment: http://stackoverflow.com/comment/84048981
linked to: http://stackoverflow.com/q/16929056
favorite count: 0
has title: How to save changes of Pandas data frame into a new file using pd.to_csv?
has comment: http://stackoverflow.com/comment/84076609
type: Question
has comment: http://stackoverflow.com/comment/84089950
has body: Trying to use a small example to explain my case: df = pd.DataFrame([[1,1],[1,2],[1,3],[1,4]],columns=['A', 'B']) d1 = df['B'].apply(lambda x: '{0:0&gt;3}'.format(x)) df['B'] = d1 df.head() df.to_csv() I want to save changed df into a new csv file, which should be like: Out[28]: A B 0 1 001 1 1 002 2 1 003 3 1 004 But after saved it used df.to_csv(), the new data file has no changes: Out[32]: A B 0 1 1 1 1 2 2 1 3 3 1 4 Anyone could happy to tell how to fix it? many thanks!
duplicate of: http://stackoverflow.com/q/16929056
answer count: 0
has comment: http://stackoverflow.com/comment/84059014

http://stackoverflow.com/q/48614998
tagged with: python-2.7
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84227168
has title: Cannot figure out how to install and use io_funcs in Python 2.7
has body: I'm currently working through someone else's code and I cannot figure out what "io_funcs" are in Python. The import line is currently throwing an error that the packages cannot be found. I'm currently using Python 2.7 The original import line is: from io_funcs.binary_io import BinaryIOCollection And it is used under the context of loading in from a binary file, for example: io_funcs = BinaryIOCollection() io_funcs.array_to_binary_file(data, file_name) file_id = os.path.splitext(os.path.basename(file_name))[0] features, frame_number = io_funcs.load_binary_file_frame(file_name, 63) io_funcs.array_to_binary_file(gen_features, new_file_name) I've searched through StackOverflow and done a lot of Googling and I can't seems to find a reference to io_funcs anywhere.
type: Question
has comment: http://stackoverflow.com/comment/84227441
has comment: http://stackoverflow.com/comment/84227110
type: UnansweredQuestion
tagged with: io
tagged with: python

http://stackoverflow.com/q/48488998
tagged with: python-3.x
answer count: 2
tagged with: rotation
has comment: http://stackoverflow.com/comment/83970828
possible better answer: http://stackoverflow.com/a/48489165
upvote count: 2
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/48489165
type: AnsweredQuestion
has title: How can I speed-up a matrix rotation by 90 degrees clockwise?
has comment: http://stackoverflow.com/comment/83971083
tagged with: matrix
has body: Rotate a square matrix by 90 degree with O(1) extra space. I have used Python to solve it. I wanted to know if I can improve my code further. def rotate_by_90(m): # unpacking arguments with zip(*) in reverse with [ : :-1] tuples = zip(*m[::-1]) # flattening tuples to list with [list(i)] return [list(i) for i in tuples] def makeMatrix(array, size): # validating size of matrix for given array if (size**2!=len(array)): return -1 # make sub array of length size using array slicing else: matrix = [array[i:i+size] for i in range(0, len(array), size)] return rotate_by_90(matrix) arr = [1,2,3,4] dimension = 2 result = makeMatrix(arr, dimension) # Original Matrix: [[1, 2], [3, 4]] # Result: [[3, 1], [4, 2]]
tagged with: python
accepted answer: http://stackoverflow.com/a/51393247
favorite count: 0
type: Question
score: 2
has answer: http://stackoverflow.com/a/51393247

http://stackoverflow.com/q/48488781
tagged with: kivy
has body: I am trying to run this type of code on android but when i tap mobile back button, inspite of coming to the previous screen app is closed, i used this piece of code to stop the App for being closed: def __init__(self, **kwargs): super(MyApp, self).__init__(**kwargs) Window.bind(on_keyboard=self.BackButton) def BackButton(self, window, key, *args): if key==27: return True But how to return to the previous screen. and how to use ActionPrevious Button to come at previous screen? from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen Builder.load_string(""" &lt;MyAppGUI&gt;: orientation:'vertical' id: box ActionBar: ActionView: ActionPrevious: title: 'How to go back using this button???' with_previous: True ScreenManager: id: screenmanger Screen: name: 's1' Button: text: 'goto screen 2' on_release: screenmanger.current='s2' Screen: name: 's2' Button: text: 'goto screen 3' on_release: screenmanger.current='s3' Screen: name: 's3' Button: text: 'goto main screen' on_release: screenmanger.current='s1' """) class MyAppGUI(BoxLayout): pass class MyApp(App): def build(self): return MyAppGUI() if __name__=='__main__': MyApp().run()
has answer: http://stackoverflow.com/a/48491911
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
has title: Kivy ActionBar back Button to switch to previous screen
favorite count: 0
type: Question
tagged with: android-actionbar
tagged with: python

http://stackoverflow.com/a/48601166
downvote count: 0
answers question: http://stackoverflow.com/q/48601095
has body: Here's a solution that is based on regular expressions with a callback function: &gt;&gt;&gt; import re &gt;&gt;&gt; for s in subject: ... print(re.sub(r"(\d)bps?", lambda m: "%d%%" % (int(m.group(1))*100), s)) ... HYB option 1Y10Y STY L op in COP 4 2300% at 2 1200% (hu) HYB option 1Y10Y SOP Linked op in CHY 0 045% at 0 065% HYB option Lip 3M10Y SPX Linked op in BRR 0 0% at +0 2500% HYB option 2Y15Y NFU Linked op in JPY 0 0498% at 0 0975% (765) HYB option 1Y10Y SxX Lked op in USD 5 7500% at 2 3400% THYB optionSp 9M10Y SX5E Led op in COP 0 065% HYB option 1Y5Y DEE Likd op in EUR 2300% at 1 7600% (ba3) A brief explanation: re.sub() takes a regular expression and whenever there's a match (\d = any number), it is sent to a callback function (here: a lambda that does the job: convert to int, multiply by 100, add percent sign). The match is then replaced by the string returned by the callback function. So every time there's a number followed by bp or bps (the question mark makes s optional), the number is passed to a function that returns a string number*100%. The for loop iterates over strings in your list and applies re.sub() to each element.
type: Answer
score: 6
upvote count: 6

http://stackoverflow.com/a/48547399
score: 4
answers question: http://stackoverflow.com/q/48547355
accepted answer of: http://stackoverflow.com/q/48547355
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: Well, for this example, you could use list comprehension with slicing. a = [[1, 2], [1, 2, 3], [1, 2, 3, 4]] b = [x[1:] for x in a]
type: Answer

http://stackoverflow.com/a/48499142
score: 1
has comment: http://stackoverflow.com/comment/84019765
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48497795
has body: Your second option is more memory efficient. The reason is that you will end up with a multi-index and the actual text values are not duplicated in memory. They are only shown as duplicate in the output representation. You can see the lack of duplication if you look at the output of merge_2.index for your actual DataFrames. Demo: # I've added some extra dummy text to show how this works with larger strings extra_txt = ",".join([str(i) for i in range(5000)]) import pandas as pd id = range(0,5) texts = [ 'first sent' + extra_txt, 'another one' + extra_txt, 'I think you' + extra_txt, 'will like this' + extra_txt, 'will work' + extra_txt, ] df = pd.DataFrame({'txt':texts, 'id':id}) df2 = pd.DataFrame({'attr':['chem', 'dis', 'chem', 'chem', 'chem', 'dis', 'dis', 'dis', 'dis', 'chem'] ,'id':[0,0,1,1,2,2,3,3,4,4]}) merge_1 = df.merge(df2, on='id') merge_2 = df.merge(df2, on='id').set_index(['id', 'txt']) Version 1 memory usage: In []: merge_1.memory_usage(index=True, deep=True).sum() Out[]: 240335 Version 2 memory usage: In []: merge_2.memory_usage(index=True, deep=True).sum() Out[]: 120565
answers question: http://stackoverflow.com/q/48497795
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84208851
type: AnswerComment
comment on: http://stackoverflow.com/a/48599627
score: 2
has text: An extra information about why this is need: `create_user` uses `set_password` method (which does the hashing on the password) on `User` objects. The simple `create` will not working since the password will be stored as it is (no hashing) and then login using that password will try to match the hash of the entered password with the raw stored password which will obviously not going to match.
type: Comment

http://stackoverflow.com/q/48596726
has comment: http://stackoverflow.com/comment/84190323
tagged with: syntax
type: AnsweredQuestion
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/84190370
tagged with: data-structures
has comment: http://stackoverflow.com/comment/84190822
favorite count: 0
has answer: http://stackoverflow.com/a/48600594
has comment: http://stackoverflow.com/comment/84190312
has comment: http://stackoverflow.com/comment/84201085
type: Question
has comment: http://stackoverflow.com/comment/84193838
tagged with: python
possible better answer: http://stackoverflow.com/a/48596816
answer count: 5
score: -2
accepted answer: http://stackoverflow.com/a/48596876
has title: Output similarities found in two list
has answer: http://stackoverflow.com/a/48596905
has answer: http://stackoverflow.com/a/48596816
has answer: http://stackoverflow.com/a/48596876
has answer: http://stackoverflow.com/a/48596821
has comment: http://stackoverflow.com/comment/84192343
tagged with: list
has body: Two questions. 1.My code contain two list ListA = [[3, 5], [4, 4], [4, 5], [4, 6], [5, 3], [5, 4], [5, 5], [5, 6], [5, 7], [6, 4], [6, 5], [6, 6], [7, 5]] ListB =[[0, 4], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [3, 6], [3, 7], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [5, 2], [5, 3], [5, 4], [5, 5], [5, 6], [6, 4]] I want it to output the similarities found between the two list: [[3,5][4,4][4,5][4,6][5,3][5,4][5,5][5,6][6,4]] print(set(ListA]).intersection(ListB])) didn't work. Any other solutions? 2. I would also like it to output the numbers that are similar in index[0] of each brackets of two number found in both list. ListA contain [3,5][4,4][5,3][6,4] ListB contain [3,1][4,2][5,2][6,4] Since 3,4,5,6 is found in index[0] (Or first number) of each bracket, the output would be. [3,4,5,6] How would I do that?

http://stackoverflow.com/comment/84046052
comment on: http://stackoverflow.com/a/48511753
score: 0
type: AnswerComment
has text: You're a genius. Thank you for taking the time to help me. Accepted
type: Comment

http://stackoverflow.com/q/48603180
upvote count: 1
tagged with: python
has body: Here is my starting df: import numpy as np import pandas as pd df = pd.DataFrame(['alpha', 'beta'], columns = ['text']) df text 0 alpha 1 beta Here is the end result I want: text first second third 0 alpha alpha-first alpha-second alpha-third 1 beta beta-first beta-second beta-third I have written the custom function parse(), no issue there: def parse(text): return [text + ' first', text + ' second', text + ' third'] Now I try to apply parse() to the initial df, which is where errors arise: 1) If I try the following: df = df.reindex(columns = list(df.columns) + ['first', 'second', 'third']) # Create empty columns df'first', 'second', 'third' = df.text.apply(parse) I get: ValueError: Must have equal len keys and value when setting with an ndarray 2) Slightly different version: df = df.reindex(columns = list(df.columns) + ['first', 'second', 'third']).astype(object) # Create empty columns of "object" type df'first', 'second', 'third' = df.text.apply(parse) I get: ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (3,2) Where am I going wrong? EDIT: I should clarify that parse() itself is a much more complicated function in the real-world problem I'm trying to solve. (it takes a paragraph, finds 3 specific types of strings in it, and outputs those strings as a list of length 3). In my code above, I made up a somewhat random simple definition of parse() as a substitute to avoid getting bogged down in details unrelated to the two errors I'm getting.
favorite count: 0
has answer: http://stackoverflow.com/a/48603965
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48603250
tagged with: pandas
has answer: http://stackoverflow.com/a/48603250
score: 1
has answer: http://stackoverflow.com/a/48603315
answer count: 4
possible better answer: http://stackoverflow.com/a/48603246
type: Question
has answer: http://stackoverflow.com/a/48603246
downvote count: 0
has title: apply custom function to an existing column to output multiple columns

edward
tags question: http://stackoverflow.com/q/48623439
type: Tag
tag name: edward

http://stackoverflow.com/comment/84253767
type: Comment
type: QuestionComment
has text: @PatrickHaugh just wow
comment on: http://stackoverflow.com/q/48628302
score: 0

http://stackoverflow.com/q/48638838
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/84274150
has body: We are simulating a sedimentation in a French bay (Mont Saint Michel), for this, we are putting sediments (represented as numbers) in an array. The deposit is random in our 1000x1000 array, with an island in the middle. At the end of the program, we d like to smooth our bay everywhere apart from the island where the numbers are equal to zero. We did it, but it s far too long to run.. Can someone help us to find a way to accelerate our program ? for j in range (0,375): for decale in range (250): diff=M[749+decale][j]-M[749+decale+1][j] if diff&gt;=3: M[749+decale][j]-=floor(19*diff/20) M[749+decale+1][j]+=floor(19*diff/20) for j in range (625,1000): #for the S-W of the bay for decale in range (250): diff=M[749+decale][j]-M[749+decale+1][j] if diff&gt;=3: M[749+decale][j]-=floor(19*diff/20) M[749+decale+1][j]+=floor(19*diff/20) for i in range (800,1000): for decale in range (799): For the West of the bay diff=M[i][200+decale]-M[i][200+decale+1] if diff&gt;=3: M[i][200+decale]-=floor(19*diff/20) M[i][200+decale+1]+=floor(19*diff/20) for decale in range (799): #Idem diff=M[i][799-decale]-M[i][799-decale-1] if diff&gt;=3: M[i][799-decale]-=floor(19*diff/20) M[i][799-decale-1]+=floor(19*diff/20) for j in range (0,375): #Along the island for decale in range (350): diff=M[850-decale][j]-M[850-decale-1][j] if diff&gt;=3: M[850-decale][j]-=floor(19*diff/20) M[850-decale-1][j]+=floor(19*diff/20) for j in range(625,1000): #Idem for decale in range (350): diff=M[850-decale][j]-M[850-decale-1][j] if diff&gt;=3: M[850-decale][j]-=floor(19*diff/20) M[850-decale-1][j]+=floor(19*diff/20) for i in range (500,549): #Idem for decale in range (500): diff=M[i][499+decale]-M[i][499+decale+1] if diff&gt;=3: M[i][499+decale]-=floor(19*diff/20) M[i][499+decale+1]+=floor(19*diff/20) for decale in range (500): #Idem diff=M[i][500-decale]-M[i][500-decale-1] if diff&gt;=3: M[i][500-decale]-=floor(19*diff/20) M[i][500-decale-1]+=floor(19*diff/20) return M
has comment: http://stackoverflow.com/comment/84274154
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48639971
has title: How to smooth an array 1000x1000 quickly
answer count: 1
score: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/84039892
comment on: http://stackoverflow.com/a/48520288
type: Comment
score: 0
type: AnswerComment
has text: @ ImportanceOfBeingErnes, Thank you so much for your insight. This is what I was looking for. I appreciate your help.

http://stackoverflow.com/comment/84182966
score: 0
type: Comment
type: AnswerComment
has text: That solution works perfectly for the question asked thanks! How would I modify that approach if my array was like a set of unique numbers 0 to n*n in a shuffled order. Is there a way to wrap an array into a numpy matrix?
comment on: http://stackoverflow.com/a/48592830

http://stackoverflow.com/comment/84297379
score: 0
comment on: http://stackoverflow.com/a/48649701
type: AnswerComment
has text: Check HTML source again and you will find ` `
type: Comment

centos
tags question: http://stackoverflow.com/q/48579428
tag name: centos
type: Tag
tags question: http://stackoverflow.com/q/48640853
tags question: http://stackoverflow.com/q/48644281
tags question: http://stackoverflow.com/q/48541932

http://stackoverflow.com/comment/84214198
type: Comment
comment on: http://stackoverflow.com/a/48600606
type: AnswerComment
score: 0
has text: Sorry that wasn't the cause in your case -- often it is. Please post if you find the source of the problem.

http://stackoverflow.com/q/48546664
type: Question
tagged with: fasta
has title: Python: comparing two multi-fasta files of the same set of proteins with parser - to find and count mutations after treatment
upvote count: 2
tagged with: bioinformatics
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84094605
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48571155
tagged with: statistics
score: 2
answer count: 1
tagged with: parsing
has body: My task is to count the mutations occured in several proteins after a treatment. The sequences are all present in the two files in the same order. I opened both files with the fasta parser (SeqIO.parse) in biopython and I got all the proteins listed (separated before and after the treatment). My question: How can I zip the parsers together to count the mutations? from Bio import SeqIO for normal_samples in SeqIO.parse("/data/statistic/normal_samples", "fasta"): print(normal_samples.id) print(repr(normal_samples.seq)) print(len(normal_samples)) for treated_samples in SeqIO.parse("/data/statistic/with_treatment", "fasta"): print(normal_samples.id) print(repr(normal_samples.seq)) print(len(normal_samples)) dict_n_t = dict(zip(normal_samples &amp; treated_samples))
favorite count: 0

http://stackoverflow.com/comment/84065261
score: 0
type: Comment
has text: I ran it and now it rejects every character of the line. I'm thinking I am having issues with how my code iterates through my file that I am checking. The above code should shed some light. I am just trying to find a fix without having to completely rewrite everything.
type: AnswerComment
comment on: http://stackoverflow.com/a/48534631

http://stackoverflow.com/comment/84102684
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48548440
type: AnswerComment
has text: Sorry, this isn't all the code. I do have it at the end. This is just the snippet I was having trouble with.

http://stackoverflow.com/comment/84145025
score: 0
type: Comment
has text: That is, a minimal complete script, including dict?
type: QuestionComment
comment on: http://stackoverflow.com/q/48574003

http://stackoverflow.com/comment/84187491
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48595128
has text: Then use `iteritems`. Downvote removed though. I hadn't noticed that.
type: Comment

http://stackoverflow.com/a/48514175
has comment: http://stackoverflow.com/comment/84023250
has body: To create the example data frame import pandas as pd text = '''Col1 Col2 Col3 Col4 1 apple tomato banana 1 apple potato banana 1 apple tomato banana 1 apple tomato banana 1 apple tomato banana 1 apple tomato banana 1 grape tomato banana 1 pear tomato banana 1 lemon tomato banana''' count = 1 data = [] for line in text.split('\n'): if count == 1: headers = line.split() else: data.append(line.split()) count += 1 df = pd.DataFrame(data = data,columns=headers) The value_counts method produces a dict with unique column values as the keys and a count as the value. It is these keys I am assigning to k. value_counts returns a Pandas series object but it is like a dict This list comprehension has a filtering 'if' statement that ignores keys if the value associated with it isn't > 5 In this example, it returns a list with only one value, but it other cases it could be more. Col2_more_than_5 = [k for k in df['Col2'].value_counts().keys() if df['Col2'].value_counts()[k] &gt; 5] Col3_more_than_5 = [k for k in df['Col3'].value_counts().keys() if df['Col3'].value_counts()[k] &gt; 5] I now have two lists that contain the string/s that occur > 5 times in each column and now I create a selector that returns rows where both statements are true df[(df['Col2'].isin(Col2_more_than_5)) &amp; (df['Col3'].isin(Col3_more_than_5))] The 'isin' method works if there are more than 1 value in the list
type: Answer
has comment: http://stackoverflow.com/comment/84104494
answers question: http://stackoverflow.com/q/48513886
has comment: http://stackoverflow.com/comment/84023106
has comment: http://stackoverflow.com/comment/84026294
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/84057671
comment on: http://stackoverflow.com/a/48514376
score: 0
type: Comment
has text: Thanks! I hadn't thought of using break. I ended up defining network as a dictionary and using "if (x,y) in network". With this, the code ran in no-time. Converting from a dictionary to a list was straightforward.
type: AnswerComment

http://stackoverflow.com/q/48517133
has answer: http://stackoverflow.com/a/48517357
has body: I have this function for a neural network and it's the function to calculate the next layer from a list of inputs and a list of weights. Is there any way to make this faster or more efficient? the arguments inp is the input, weights are the weights, layerlength is the length of the next layer and rounds is just the length to round the output to. def output(inp,weights,layerlength,rounds): layer=[] count=0 lappend=layer.append for a in range(layerlength): total=0 for b in range(len(inp)): total+=inp[b]*weights[count] count+=1 lappend(round(total,rounds)) return layer
type: AnsweredQuestion
score: 0
tagged with: performance
has comment: http://stackoverflow.com/comment/84028780
accepted answer: http://stackoverflow.com/a/48517357
possible better answer: http://stackoverflow.com/a/48517362
tagged with: python
has answer: http://stackoverflow.com/a/48517362
type: Question
tagged with: python-3.x
answer count: 2
has title: how to make neural network function faster?

http://stackoverflow.com/comment/84291441
has text: Thanks this is great! The data used for the example is basically just `df.head()`. What I really want is to only show the year on the x-axis during the month of January, so it shows when a new year has begun. could I use something like `plt.xticks(df.index,df["year"].unique.values)` you think?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48633961

http://stackoverflow.com/q/48533849
favorite count: 0
has answer: http://stackoverflow.com/a/48534139
has title: Modifying keys and values in nested dictionaries in python
type: AnsweredQuestion
answer count: 9
has body: I'm working with a nested dictionary and I'm trying to figure out how to modify certain nested and non-nested keys/values effectively. In short, I'm trying to do the following: take a nested value and switch it with a non-nested key rename a nested key. Here's a basic example of a dictionary that I'm working with: pet_dictionary = {'Buford':{'color':'white', 'weight': 95, 'age':'3', 'breed':'bulldog'}, 'Henley':{'color':'blue', 'weight': 70, 'age':'2', 'breed':'bulldog'}, 'Emi':{'color':'lilac', 'weight': 65, 'age':'1', 'breed':'bulldog'}, } I want to take the non-nested key, which is name of each dog (i.e. Buford, Henley, Emi), switch it with nested value for the age (i.e. 3, 2, 1), and then change the nested key name from 'age' to 'name.' So the output should look like this: pet_dictionary = {'3':{'color':'white', 'weight': 95, 'name':'Buford', 'breed':'bulldog'}, '2':{'color':'blue', 'weight': 70, 'name':'Henley', 'breed':'bulldog'}, '1':{'color':'lilac', 'weight': 65, 'name':'Emi', 'breed':'bulldog'}, } I understand how to do this manually one-by-one, but I'm not sure what the best approach is for making all of these changes in a more elegant/optimal way.
has answer: http://stackoverflow.com/a/48533967
tagged with: nested
tagged with: python
accepted answer: http://stackoverflow.com/a/48533991
has answer: http://stackoverflow.com/a/48533973
has answer: http://stackoverflow.com/a/48534001
has answer: http://stackoverflow.com/a/48533991
type: Question
has answer: http://stackoverflow.com/a/48534044
has answer: http://stackoverflow.com/a/48534657
possible better answer: http://stackoverflow.com/a/48533967
has answer: http://stackoverflow.com/a/48533972
has comment: http://stackoverflow.com/comment/84064030
upvote count: 2
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48539464
tagged with: dictionary

http://stackoverflow.com/comment/84098427
type: QuestionComment
has text: I can only get the `.egg-info` install using pip 9.0.1 on Linux.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48550546

http://stackoverflow.com/comment/84168667
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48585899
has text: how can I write it in Python 2?
type: Comment

http://stackoverflow.com/comment/84115255
has text: @Jean-FrançoisFabre No I want to truncate the beginning of the string.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48559775
type: QuestionComment

http://stackoverflow.com/q/48585241
has comment: http://stackoverflow.com/comment/84167385
score: 2
upvote count: 2
has title: Add values to dictionary key using loop
has answer: http://stackoverflow.com/a/48585503
possible better answer: http://stackoverflow.com/a/48585503
answer count: 3
downvote count: 0
has body: I have a large database from the following type: data = { "2": {"overall": 172, "buy": 172, "name": "ben", "id": 2, "sell": 172}, "3": {"overall": 173, "buy": 173, "name": "dan", "id": 3, "sell": 173}, "4": {"overall": 174, "buy": 174, "name": "josh", "id": 4, "sell": 174}, ... and so on for about 10k rows. Then, I created a loop to find if inside this dict() there are specific names: I used the next loop items = ["ben","josh"] Database = dict() Database = {"Buying_Price": "", "Selling_Price": ""} for masterkey, mastervalue in data.items(): if mastervalue['name'] in items: Database["Name"] = Database["Name"].append(mastervalue['name']) Database["Buying_Price"] = Database["Buying_Price"].append(mastervalue['buy']) Database["Selling_Price"] = Database["Selling_Price"].append(mastervalue['sell']) However, I'm getting the next error: Database["Buying_Price"] = Database["Buying_Price"].append(mastervalue['buy_average']) AttributeError: 'str' object has no attribute 'append' My goal is to obtain a dict names Database with 2 keys: Buying_Price,Selling_Price where in each one I will have the following: Buying_Price = {"ben":172,"josh":174} Sellng_Price = {"ben":172,"josh":174} Thank you.
has answer: http://stackoverflow.com/a/48585443
tagged with: loops
has comment: http://stackoverflow.com/comment/84167331
has comment: http://stackoverflow.com/comment/84167481
favorite count: 0
has comment: http://stackoverflow.com/comment/84167256
type: Question
has comment: http://stackoverflow.com/comment/84259194
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84167351
has comment: http://stackoverflow.com/comment/84167394
has comment: http://stackoverflow.com/comment/84167424
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48585516
accepted answer: http://stackoverflow.com/a/48585516

http://stackoverflow.com/a/48598646
answers question: http://stackoverflow.com/q/48598508
upvote count: 2
has comment: http://stackoverflow.com/comment/84194474
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84193971
has comment: http://stackoverflow.com/comment/84194243
has comment: http://stackoverflow.com/comment/84194039
has comment: http://stackoverflow.com/comment/84194104
has comment: http://stackoverflow.com/comment/84194242
has comment: http://stackoverflow.com/comment/84194278
score: 2
has comment: http://stackoverflow.com/comment/84193928
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84193974
accepted answer of: http://stackoverflow.com/q/48598508
has comment: http://stackoverflow.com/comment/84194681
has comment: http://stackoverflow.com/comment/84194060
has body: Your system has an incorrect locale configured. On Linux, Python takes the filesystem codec from the locale. From the sys.getfilesystemencoding() documentation: Return the name of the encoding used to convert between Unicode filenames and bytes filenames. [...] On Unix, the encoding is the locale encoding. You have a filesystem that uses UTF-8 but Python is not reading the data correctly. As a result, the UTF-8 data can't correctly be decoded, there is an decoding error, and the surrogateescape error handler kicks in, and it has 'preserved' the bytes as low surrogate codepoints. You can reverse the issue by encoding to UTF-8 with the same error handler: &gt;&gt;&gt; '\udcd0\udc9e\udcd0\udc94 \udcd0\udc94.bmp'.encode('utf8', 'surrogateescape') b'\xd0\x9e\xd0\x94 \xd0\x94.bmp' The result happens to be the correct UTF-8 encoding for your filename: &gt;&gt;&gt; '\udcd0\udc9e\udcd0\udc94 \udcd0\udc94.bmp'.encode('utf8', 'surrogateescape').decode('utf8') 'ОД Д.bmp' You'll want to use LC_CTYPE=en_US.UTF-8 at the very least, to avoid this issue. In your case you appear to have LC_CTYPE=UTF-8, which is invalid (you could use LC_CTYPE=en_SG.UTF-8 instead). Another work-around is to use bytes paths: image_path = '/home/atin/test/ОД Д.bmp'.encode('utf8')
has comment: http://stackoverflow.com/comment/84194438

http://stackoverflow.com/comment/84288727
comment on: http://stackoverflow.com/q/48645531
score: 1
has text: That should be explained in your question, it is unclear what you are asking. Please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48526997
score: 2
has comment: http://stackoverflow.com/comment/84050385
has comment: http://stackoverflow.com/comment/84051559
downvote count: 0
answers question: http://stackoverflow.com/q/48504914
has body: No, I am not talking about binary classification. The y_true and y_predict you showed above will not be considered as classification targets, unless otherwise specified as such. First since they are probabilities so it can take any continuous values and hence it is detected as regression in scikit. Second, each element inside y_pred or y_true is a list of probabilities. That is detected as multi-output. Hence the error of "Multioutput targets". You need to supply the actual labels for log_loss and not probabilities for y_true (Ground truths). Why do you have probabilities in that, by the way?? Probabilities can be present for predicted data but why for actual data? For that you need to first convert the probabilities of y_true into labels by considering the highest probability as the winner class. This can be done by numpy.argmax by using the below code: import numpy as np y_true = np.argmax(y_true, axis=1) print(y_true) Output:- [0, 1] # We will not do this the above for y_predict, because probabilities are allowed in it. # We will use labels param to declare that we have actually 3 classes, # as evident from your probabilities. metrics.log_loss(y_true, y_predict, labels=[0,1,2]) Output:- 0.6931471805599458 As discussed with @Imran, here's an example having y_true with values other than 0 or 1. This example here uses log_loss for a 3-class classification in which y have values 0, 1 and 2 :- http://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_multiclass.html#sphx-glr-auto-examples-calibration-plot-calibration-multiclass-py Below example to simply check if other values are allowed or not: y_true = np.array([0, 1, 2]) y_pred = np.array([[0.5,0.5,0.0],[0.5,0.4,0.1], [0.4,0.1,0.5]]) metrics.log_loss(y_true, y_pred) Output:- 1.3040076684760489 (No error)
has comment: http://stackoverflow.com/comment/84049967
upvote count: 2
type: Answer

http://stackoverflow.com/comment/84068033
has text: I made a mistake in the last one.Last one is working.folder_2.script_b.py must be folder_2.script_b
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48536184

http://stackoverflow.com/a/48612868
answers question: http://stackoverflow.com/q/48612637
has comment: http://stackoverflow.com/comment/84222630
has comment: http://stackoverflow.com/comment/84222446
has body: You could use Item.objects.count() to automatically increment your field. Plug it in the save() method of your model so that your field is calculated each time you create an instance.
type: Answer
score: 0

http://stackoverflow.com/q/48632756
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: list
linked to: http://stackoverflow.com/q/4112265
has body: Let's say i have 2 lists in a list: List = [[1,2,3], [4,5,6]] If i wanted to transpose the two lists i would go like this: NewList = zip (List[0], List[1]) in this case if i export the lists to a csv file using this: with open("Transposed.csv", "wb") as f: writer = csv.writer(f) writer.writerows(NewList) I will get this: 1 4 2 5 3 6 Now in a case where i have a large number of lists in the main list, and i would like to avoid manually adding every single one of them into the zip function, is there a way i can do a for loop to transpose all the lists in the main list? instead of going like this: NewList = zip (List[0], List[1]), ......List[20])
type: Question
has answer: http://stackoverflow.com/a/48632804
possible better answer: http://stackoverflow.com/a/48632804
has title: How to transpose all the lists in a list at once?
answer count: 2
has answer: http://stackoverflow.com/a/48632852
accepted answer: http://stackoverflow.com/a/48632852
tagged with: transpose
tagged with: python
duplicate of: http://stackoverflow.com/q/4112265

http://stackoverflow.com/q/48496242
has comment: http://stackoverflow.com/comment/83988801
tagged with: c#
type: UnansweredQuestion
tagged with: .net
tagged with: python
has comment: http://stackoverflow.com/comment/84150176
has title: how to import python 3 libraries in iron python
score: 0
has comment: http://stackoverflow.com/comment/83988498
has comment: http://stackoverflow.com/comment/83988587
has comment: http://stackoverflow.com/comment/84149696
answer count: 0
has body: I am trying to call a python script on a button click of an exe built with C#. I installed the following dll's using System.Windows.Forms; using IronPython.Hosting; using Microsoft.Scripting.Hosting; and myscript.py is import sys sys.path.append("C:\ProgramData\Anaconda3\Lib") import os print (os.getcwd()) import pandas as pd print("hi") my c# code: private static void doPython() { ScriptEngine engine = Python.CreateEngine(); engine.ExecuteFile(@"test.py"); Console.WriteLine(); } I get unexpected token 'from' error when running my solution, please help. thanks in advance
has comment: http://stackoverflow.com/comment/83988752
tagged with: ironpython
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/48625927
answers question: http://stackoverflow.com/q/48623945
has body: Solved, kernel_size implies that both dimensions are equal, if i want to use different dimension for H and W should use kernel_w kernel_h.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48623945
score: 0

http://stackoverflow.com/q/48542211
has comment: http://stackoverflow.com/comment/84079450
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/84079486
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/84079544
has comment: http://stackoverflow.com/comment/84079616
favorite count: 0
type: AnsweredQuestion
has title: Django REST: 'Request' object has no attribute 'field_name'
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48542434
type: Question
has comment: http://stackoverflow.com/comment/84079704
has answer: http://stackoverflow.com/a/48542434
answer count: 1
has body: I'm trying to create a post request to add a job application to the list of applicants. This is done by POST /task-worker/&lt;task_id&gt; However, I get the error: 'Request' object has no attribute 'task' Models.py class Task_worker(models.Model): worker = models.ForeignKey(Worker) task = models.ForeignKey(Task) class Meta: unique_together = ('worker', 'task') class Task(models.Model): ... class Worker(models.Model): ... serializers.py class TaskWorkerSerializer(serializers.ModelSerializer): task = serializers.ReadOnlyField(source='task.id') worker = serializers.ReadOnlyField(source='worker.id') class Meta: model = Task_worker fields = ('id', 'task', 'worker', 'created', ) def create(self, validated_data): validated_data['task_id'] = self.context['request'].task return super(TaskWorkerSerializer, self).create(validated_data) views.py class TaskWorker(generics.ListCreateAPIView): serializer_class = TaskWorkerSerializer def get_queryset(self): task_id = self.kwargs.get('task_id', '') queryset = Task_worker.objects.filter(task__user=self.request.user, task_id=task_id).distinct() return queryset def perform_create(self, serializer): worker = Worker.objects.get(user=self.request.user) task = Task.objects.get(pk=self.kwargs.get('task_id', '')) serializer.save(task=task, worker=worker) #ALSO TRIED #serializer.save(task_id=self.kwargs.get('task_id', ''), worker=worker) Even if I don't have task explicitly in perform_create(), I still get the same error, saying request has no task attribute. urls.py url(r'^task-worker/(?P&lt;task_id&gt;[0-9]+)/$', views.TaskWorker.as_view()), EDIT: Full Traceback. Traceback: File "/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/rest_framework/request.py" in __getattr__ 410. return getattr(self._request, attr) During handling of the above exception ('WSGIRequest' object has no attribute 'task'), another exception occurred: File "/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/django/core/handlers/ex…
downvote count: 0

http://stackoverflow.com/a/48614590
score: 2
accepted answer of: http://stackoverflow.com/q/48614477
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48614477
has body: jq is perfect for this. Let's see what it can do. First, let's group the cars by color. group_by() takes an array and groups the elements by whatever sub-expression you want. $ jq 'group_by(.colour)' input.json [ [ {"car":[{"model":"Camry","make":"Toyota","year":2015}],"colour":"Blue"} ], [ {"car":[{"model":"Accord","make":"Honda","year":2000}],"colour":"Red"}, {"car":[{"model":"Ram", "make":"Dodge","year":1999}],"colour":"Red"} ] ] Then let's map each sub-array to a {color: [years]} object. The map() function takes an array and changes each input element into some new output element. We can use it to create the exact {color: [years]} objects we desire. Let's start with a partial mapping. We'll pull out the colors and see what that looks like. $ jq -c 'group_by(.colour) | map({(.[0].colour): []})' input.json [{"Blue":[]},{"Red":[]}] Perfect. We have the colors. Now to get the list of years we use map again, turn the sub-arrays of cars into arrays of years. $ jq -c 'group_by(.colour) | map({(.[0].colour): map(.car[].year)})' input.json [{"Blue":[2015]},{"Red":[2000,1999]}]

http://stackoverflow.com/q/48614244
tagged with: bash
has body: I want my makefile to setup a mysql database. This is my procedure: Retrieve user, host, password and database values from a config.json file with python, and store them in a config variable Get each value stored in the config variable with awk (each value is separated by two spaces) Run some mysql with these values This is my script: all: config=$(python3 -c 'import json; file = open("config.json"); config = json.load(file); file.close(); print(config["mysql"]["user"]+" "+config["mysql"]["host"]+" "+config["mysql"]["password"]+" "+config["mysql"]["database"])'); \ user=$(echo "$config" | awk -F " " '{print $1}'); \ host=$(echo "$config" | awk -F " " '{print $2}'); \ password=$(echo "$config" | awk -F " " '{print $3}'); \ database=$(echo "$config" | awk -F " " '{print $4}'); \ sudo mysql -e "CREATE DATABASE IF NOT EXISTS $database; GRANT ALL PRIVILEGES ON $database.* TO '$user'@'$host' IDENTIFIED BY '$password'" If I type this directly in my console it works fine. Why doesn't it work when running make? This is my console output: config=; config = json.load(file); file.close(); print(config["mysql"]["user"]+" "+config["mysql"]["host"]+" "+config["mysql"]["password"]+" "+config["mysql"]["database"])'); \ user=; \ host=; \ password=; \ database=; \ sudo mysql -e "CREATE DATABASE IF NOT EXISTS atabase; GRANT SELECT, INSERT, UPDATE, DELETE, INDEX, ALTER ON atabase.* TO 'ser'@'ost' IDENTIFIED BY 'assword'; USE atabase;" /bin/sh: -c: line 0: syntax error near unexpected token `(' /bin/sh: -c: line 0: `config=; config = json.load(file); file.close(); print(config["mysql"]["user"]+" "+config["mysql"]["host"]+" "+config["mysql"]["password"]+" "+config["mysql"]["database"])'); user=; host=; password=; database=; sudo mysql -e "CREATE DATABASE IF NOT EXISTS atabase; GRANT ALL PRIVILEGES ON atabase.* TO 'ser'@'ost' IDENTIFIED BY 'assword'"' make: *** [all] Error 2
tagged with: python
has title: Using variables in a makefile
tagged with: mysql
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48614406
score: 0
has answer: http://stackoverflow.com/a/48614406
tagged with: awk
tagged with: makefile
possible better answer: http://stackoverflow.com/a/48614417
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48614417

http://stackoverflow.com/q/48496720
tagged with: django-models
tagged with: python
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83986379
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: django
has body: My requirement is to create a form wizard using model form. For example, I have a number of dynamic models, one model has 10 fields and another model have 15 fields. the model form should be split into multiple forms automatically based on fields it contains. I have tried using django-form-tools, but in django-form-tools we need to predefine the form classes in form_list attribute. Is there any other alternative to achieve this without manually doing this
has title: Django create form wizard from model form
has comment: http://stackoverflow.com/comment/83986680
has comment: http://stackoverflow.com/comment/83986459

http://stackoverflow.com/q/48504247
answer count: 1
has comment: http://stackoverflow.com/comment/84008517
favorite count: 0
type: Question
has title: django - authenthicate - missing required potential argument 'self'
has answer: http://stackoverflow.com/a/48504968
type: UnansweredQuestion
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has body: I have a custom auth backend and I am trying to connect users with it. This is the backend import logging from .models import Users class OwnAuthBackend(object): def authenticate(self, email, password): try: user = Users.objects.get(email=email) if user.check_password(password): return user else: return None except Users.DoesNotExist: logging.getLogger("error_logger").error("user with login %s does not exists " % login) return None except Exception as e: logging.getLogger("error_logger").error(repr(e)) return None def get_user(self, user_id): try: user = Users.objects.get(sys_id=user_id) if user.is_active: return user return None except Users.DoesNotExist: logging.getLogger("error_logger").error("user with %(user_id)d not found") return None And this is in the view.py email = form.cleaned_data['email_field'] password = form.cleaned_data['password'] user = OwnAuthBackend.authenticate(email=email, password=password) if user is not None: messages.success(request, 'You logged in successfully!') return redirect('index') else: messages.warning(request, 'Credentials were wrong. Failed to log in!') return redirect('index') message.error(request, 'Something went wrong while logging you in..') return redirect('index') The import: from main.backends import OwnAuthBackend Error is in the title I really have no idea what self I have to make, tried placing the request there but that didn't work. According to: users.is_authenticated - custom user model, the user is logged in if I use user = OwnAuthBackend.authenticate(request, email=email, password=password) But the problem is, if I go to control panel, the user isn't logged in anymore, the session doesn't keep, probably because ACP uses user. instead of users.
score: 1

http://stackoverflow.com/a/48528621
accepted answer of: http://stackoverflow.com/q/48528537
score: 2
has comment: http://stackoverflow.com/comment/84086490
has comment: http://stackoverflow.com/comment/84086208
downvote count: 0
has comment: http://stackoverflow.com/comment/84087913
answers question: http://stackoverflow.com/q/48528537
type: Answer
has comment: http://stackoverflow.com/comment/84087726
has comment: http://stackoverflow.com/comment/84052915
has body: This can be accomplished with an ordinary loop c = [abs(i-j)/i*100 for i,j in zip(a,b)] print(c) If you have zeros in a, then you can skip these (while keeping the same length) by including an if-else statement: c = [abs(i-j)/i*100 if i != 0 else None for i,j in zip(a,b)] print(c)
upvote count: 2
has comment: http://stackoverflow.com/comment/84052866
type: AcceptedAnswer

http://stackoverflow.com/a/48561385
downvote count: 0
type: AcceptedAnswer
has body: I think you need concat with dict comprehension, if need change columns names of MultiIndex add rename_axis: df = pd.concat({k:pd.DataFrame(v) for k, v in d.items()}).rename_axis(('sample','run')) print (df) stat1 stat2 sample run sample1 0 a 98 1 z 13 sample2 0 y 1089 1 a 1015
accepted answer of: http://stackoverflow.com/q/48560857
answers question: http://stackoverflow.com/q/48560857
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/q/48489538
score: 1
tagged with: python
tagged with: object-detection
has body: I am using Tensoflow object detection API for detection of objects.Currently, I am using MobileNet pre-trained model. Now I need to evaluate pre-trained model results under different forms of the model.To do that I need to do some slit changes to the model architecture. Is it possible?. If then How to do that?.
favorite count: 0
tagged with: object-detection-api
answer count: 0
tagged with: deep-learning
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has title: Change and use pre-trained model architecture
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/48599298
tagged with: python
has comment: http://stackoverflow.com/comment/84195289
has body: I'll add another django-admin.py question, as none of the other questions seem to cover my issue: I've installed django via pip: $ pip install django My pip and Python versions are: $ pip -V pip 9.0.1 from /usr/lib/python2.7/dist-packages (python 2.7) Specifically, python is version 2.7.14. At this point I expected to run $ django-admin startproject myTestProject which would then create my project folders in the current directory. However, this returns Cannot find installed version of python-django or python3-django This confuses me, since when I ran $ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin Further, I checked where the file django-admin.py is located: $ find -iname "django-admin.py" ./.local/bin/django-admin.py ./.local/lib/python2.7/site-packages/django/bin/django-admin.py So it seems like django-admin.py is in my PATH. Why then can I not run it? (extra info: I do have python 3.6.3 installed, too. But I don't think this version has anything to do with pip or django.)
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48601329
has comment: http://stackoverflow.com/comment/84195721
tagged with: django
has comment: http://stackoverflow.com/comment/84195304
type: Question
has title: django-admin.py not running
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48599512
tagged with: path

http://stackoverflow.com/q/48622746
has title: convert a timetuple to a timestamp then convert the timestamp back ,the new timetuple is not the original timetuple
favorite count: 0
type: AnsweredQuestion
score: 0
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48623362
accepted answer: http://stackoverflow.com/a/48623362
type: Question
has comment: http://stackoverflow.com/comment/84243151
has body: Using time.mktime() convert a timetuple to a timestamp then using time.gmtime() convert the timestamp back to a new timetuple. The new timetuple is not the original timetuple. tmp = datetime.datetime.strptime('130701 00:00:00', '%y%m%d %H:%M:%S').timetuple() tmp # time.struct_time(tm_year=2013, tm_mon=7, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=182, tm_isdst=-1) time.gmtime(time.mktime(tmp)) # time.struct_time(tm_year=2013, tm_mon=6, tm_mday=30, tm_hour=16, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=181, tm_isdst=0)
has comment: http://stackoverflow.com/comment/84241928
has comment: http://stackoverflow.com/comment/84242443
tagged with: time
upvote count: 1
answer count: 1

image
tags question: http://stackoverflow.com/q/48590565
tags question: http://stackoverflow.com/q/48628394
tags question: http://stackoverflow.com/q/48496223
tags question: http://stackoverflow.com/q/48556110
tags question: http://stackoverflow.com/q/48639369
tags question: http://stackoverflow.com/q/48611240
tags question: http://stackoverflow.com/q/48609658
tags question: http://stackoverflow.com/q/48580189
tags question: http://stackoverflow.com/q/48530886
tags question: http://stackoverflow.com/q/48599462
tags question: http://stackoverflow.com/q/48622107
tags question: http://stackoverflow.com/q/48626328
tag name: image
tags question: http://stackoverflow.com/q/48561603
tags question: http://stackoverflow.com/q/48554401
tags question: http://stackoverflow.com/q/48588260
tags question: http://stackoverflow.com/q/48618979
tags question: http://stackoverflow.com/q/48580525
tags question: http://stackoverflow.com/q/48531082
type: Tag
tags question: http://stackoverflow.com/q/48613602
tags question: http://stackoverflow.com/q/48527429

http://stackoverflow.com/comment/83976905
has text: Can you elaborate on your answer? OP doesn't use indexing at all, so it shouldn't matter that the index count in Python starts at 0.
comment on: http://stackoverflow.com/a/48491832
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51678999
has body: You can change the source code. Just assign the value of executable_path to your chromedriver path. Let me explain - When you "normally" type this - driver = webdriver.Chrome(r"path\chromedriver.exe") The WebDriver object initializes in its class. The class file is located at //selenium_folder/webdriver/chrome/webdriver.py. Inside it, if you notice the __init__ method, it takes an argument of executable_path. So you can simply do - def __init__(self, executable_path="chromedriver", port=0, options=None, service_args=None, desired_capabilities=None, service_log_path=None, chrome_options=None): executable_path = "path\chromedriver.exe" This way, the following code will successfully run the driver - driver = webdriver.Chrome()
score: 3
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48581090

http://stackoverflow.com/a/48520475
has body: The following should work. Change r = requests.get(p) data = r.text soup = BeautifulSoup(data, "lxml").text clean_soup = unicodedata.normalize("NFKD", soup) container = clean_soup.find_all('div', attrs={'id': 'yw0'}) to r = requests.get(p) clean_text = unicodedata.normalize('NFKD', r.text) soup = BeautifulSoup(clean_text, 'lxml') container = soup.find_all('div', attrs={'id': 'yw0'})
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48514985

http://stackoverflow.com/comment/84211646
comment on: http://stackoverflow.com/q/48607528
type: QuestionComment
has text: Please add in your question example for an input file. Not just one object.
type: Comment
score: 0

http://stackoverflow.com/comment/84002625
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48504285
type: AnswerComment
has text: Yeap! Just like how I printed out the contents of the text file in line 11-14

http://stackoverflow.com/comment/83986427
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48496659
has text: Is the data guaranteed not to contain contradictory information wrt to the given constraints?
score: 0

http://stackoverflow.com/q/48503939
has body: I'm trying to generate a random name when logging in, through a function in Python. The problem is that it doesn't consider it as a function, but as a plain text, though i've imported the library and called it explicitly. Here's the Python function in file Generators.py: import random letters = [chr(ord('a')+i) for i in range(26)] def generate_name(): name = "" for i in range(9): name = name + random.choice(letters) return "Testing_Mark[" + name + "]" And here's the Robot file: *** Settings *** Library Generators.py Library Selenium2Library *** Variables *** ${User} Generators.Generate Name ${Password} 1234 *** Test Cases *** Organisation Test Open Browser http://mywebsite.com/login googlechrome Log In [Teardown] Close Browser *** Keywords *** Log In Wait Until Page Contains Log in Input Text //input[@name="name"] ${User} Input Password //input[@name="password"] ${Password} Click Button //button[@type="submit"] Wait Until Element Is Visible //span[@class="alert-description"] Sleep 3 What am I doing wrong? I know Robot should recognize the above function as a keyword, but still can't figure out why it is not. Both files are in the same folder.
score: 2
has comment: http://stackoverflow.com/comment/84009596
upvote count: 2
has comment: http://stackoverflow.com/comment/84011760
answer count: 1
downvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/48504189
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: robotframework
has title: RobotFramework - Calling a function from python library
accepted answer: http://stackoverflow.com/a/48504189
has comment: http://stackoverflow.com/comment/84005885
tagged with: python

http://stackoverflow.com/comment/83975813
comment on: http://stackoverflow.com/a/48491364
score: 0
type: Comment
has text: Can someone confirm the thing I said in the last sentence...?
type: AnswerComment

http://stackoverflow.com/comment/84058905
comment on: http://stackoverflow.com/a/48530566
score: 0
type: Comment
has text: The reason everyone keeps suggesting a dict (dictionary) type for dealing with this is because usually works really well, and you didn't describe anything that would contradict this yet. See @quamrana 's answer. For the limited information you provided, it's a really good solution.
type: AnswerComment

http://stackoverflow.com/q/48641130
tagged with: django-views
has answer: http://stackoverflow.com/a/48671403
answer count: 1
tagged with: django-models
tagged with: python
tagged with: httprequest
type: Question
has title: POST Request File Upload in Django
accepted answer: http://stackoverflow.com/a/48671403
tagged with: django
has body: How to pass a file to perform file upload in Django Views by POST Request? The File should be detected in request.FILES, and further shall be accepted by Model's FileField field.
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/84067404
type: Comment
type: AnswerComment
has text: Yes, `hdfs_server` is not the actual server's name. I'll try what you suggested and post an update.
score: 0
comment on: http://stackoverflow.com/a/48536161

http://stackoverflow.com/comment/84280026
comment on: http://stackoverflow.com/a/48641401
score: 0
has text: if i run script without sudo and right after import i insert line print(uinput) it prints `<module 'uinput' from '/home/pi/.local/lib/python3.5/site-packages/uinput/__init__.py'>` which i guess is correct
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84191799
score: 0
type: Comment
type: QuestionComment
has text: @UweMannl: It's not a problem with `PATH`. Output is produced, so the Python interpretter is executing.
comment on: http://stackoverflow.com/q/48597496

http://stackoverflow.com/a/48613731
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89053297
answers question: http://stackoverflow.com/q/48613394
has body: If the encoding order doesn't matter, you can do: df_new = ( pd.DataFrame(columns=df.columns, data=LabelEncoder() .fit_transform(df.values.flatten()).reshape(df.shape)) ) df_new Out[27]: a b c 0 1 2 0 1 2 1 0
score: 1
downvote count: 0

http://stackoverflow.com/a/48542550
type: AcceptedAnswer
upvote count: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/48542089
has body: You cannot use select like this. Use foreach / foreachPartition: import json def send(part): kafkaClient = ... for r in part: kafkaClient.send(json.dumps(r.asDict())) If you need diagnostic information just use Accumulator. In current releases I would use Kafka source directly (2.0 and later): from pyspark.sql.functions import to_json, struct (df.select(to_json(struct([df[x] for x in df.columns])).alias("value")) .write .format("kafka") .option("kafka.bootstrap.servers", bootstrap_servers) .option("topic", topic) .save()) You'll need Kafka SQL package for example: --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.2.1
has comment: http://stackoverflow.com/comment/84080743
score: 9
has comment: http://stackoverflow.com/comment/84080698
answers question: http://stackoverflow.com/q/48542089
downvote count: 0

http://stackoverflow.com/q/48580836
has answer: http://stackoverflow.com/a/48581145
has comment: http://stackoverflow.com/comment/84158600
score: 0
tagged with: yaml
answer count: 1
has title: !!python/object:__main__.ClassName throwing exception
tagged with: pyyaml
has comment: http://stackoverflow.com/comment/84158543
type: Question
has body: I have a YAML file: ./YAML/simpleData.yml - name: 'Somu' age: 26 content: - name: 'Neo' age: 27 content: [] - name: 'Ari' age: 26 content: [] And I'm trying to parse it using PyYAML via: import yaml # Creating objects directly with the YAML module: print("Attempting Direct Object Load: ") class Person: def __init__(self, name, age, con): self.name = name self.age = hp self.content = con def __repr__(self): return "%s(name=%r, hp=%r, sp=%r)" % ( self.__class__.__name__, self.name, self.age, self.content) def printData(self): print(self.name) print(self.age) if self.content: for per in self.content: print("--&gt;", end="") per.printData() # Data load: person_obj = None data = "" try: with open('YAML/simpleData.yml') as source: for line in source: data += line except Exception as err: print("An exception occurred: " + str(err)) person_obj = yaml.load("""!!python/object:__main__.Person\n""" + data) if not person_obj: print("Data Loading Failed..! EXITING!!") exit(1) person_obj.printData() I'm new to Python, and thus can't determine what I'm doing wrong, due to which this exception is being raised: yaml.constructor.ConstructorError: expected a mapping node, but found sequence in "&lt;unicode string&gt;", line 1, column 1: !!python/object:__main__.Person ^ How do I fix this? Full Output Dump: Attempting Direct Object Load: Traceback (most recent call last): File "/home/somu/Programming/python/HeadFirstPython/yamlIntro.py", line 106, in &lt;module&gt; person_obj = yaml.load("""!!python/object:__main__.Person\n""" + data) File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/__init__.py", line 72, in load return loader.get_single_data() File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/constructor.py", line 37, in get_single_data return self.construct_document(node) File "/home/somu/Programming/python/HeadFirstPython/venv/lib/python3.6/site-packages/yaml/constructor.py", line 46, in construct_docume…
has comment: http://stackoverflow.com/comment/84158483
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48555602
accepted answer of: http://stackoverflow.com/q/48555425
has body: use iterrows and store the results in a list that you can then append to the dataframe as a column: rcut = [] for i, row in df.iterrows(): if row['INT_STATUS'] in ['B','C','F','H','P','R','T','X','Z','8','9']: rcut.append('01') elif row['BLOCK_CODE_1'] in ['A','B','C','D','E','F','G','I','J','K','L','M', 'N','O','P','R','U','W','Y','Z']: rcut.append('02') elif row['BLOCK_CODE_1'] in ['A','B','C','D','E','F','G','I','J','K','L','M', 'N','O','P','R','U','W','Y','Z']: rcut.append('03') else: rcut.append('00') df['rcut'] = rcut (Note: your 2nd and 3d conditions are the same, I've reused your code here so you would have to change that)
answers question: http://stackoverflow.com/q/48555425
upvote count: 2
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84107329
type: AcceptedAnswer

beautifulsoup
tags question: http://stackoverflow.com/q/48592572
tags question: http://stackoverflow.com/q/48527447
tags question: http://stackoverflow.com/q/48623456
tags question: http://stackoverflow.com/q/48514389
tags question: http://stackoverflow.com/q/48569170
type: Tag
tags question: http://stackoverflow.com/q/48612225
tags question: http://stackoverflow.com/q/48611992
tags question: http://stackoverflow.com/q/48635338
tags question: http://stackoverflow.com/q/48637930
tags question: http://stackoverflow.com/q/48610652
tags question: http://stackoverflow.com/q/48591624
tags question: http://stackoverflow.com/q/48541033
tags question: http://stackoverflow.com/q/48512943
tags question: http://stackoverflow.com/q/48595073
tags question: http://stackoverflow.com/q/48509238
tags question: http://stackoverflow.com/q/48567205
tags question: http://stackoverflow.com/q/48639819
tags question: http://stackoverflow.com/q/48635413
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/48534197
tags question: http://stackoverflow.com/q/48550451
tags question: http://stackoverflow.com/q/48622710
tags question: http://stackoverflow.com/q/48591134
tags question: http://stackoverflow.com/q/48634867
tags question: http://stackoverflow.com/q/48540867
tags question: http://stackoverflow.com/q/48645232
tags question: http://stackoverflow.com/q/48625138
tags question: http://stackoverflow.com/q/48502868
tags question: http://stackoverflow.com/q/48538436
tags question: http://stackoverflow.com/q/48536494
tags question: http://stackoverflow.com/q/48525383
tags question: http://stackoverflow.com/q/48613380
tags question: http://stackoverflow.com/q/48556651
tags question: http://stackoverflow.com/q/48516371
tags question: http://stackoverflow.com/q/48509147
tags question: http://stackoverflow.com/q/48605455
tags question: http://stackoverflow.com/q/48569690
tags question: http://stackoverflow.com/q/48507623
tags question: http://stackoverflow.com/q/48597821
tags question: http://stackoverflow.com/q/48606245
tags question: http://stackoverflow.com/q/48545807
tags question: http://stackoverflow.com/q/48591045
tags question: http://stackoverflow.com/q/48585637
tags question: http://stackoverflow.com/q/48527629
tags question: http://stackoverflow.com/q/48587429
tags question: http://stackoverflow.com/q/48492755
tags question: http://stackoverflow.com/q/48554509
tags question: http://stackoverflow.com/q/48594666
tags question: http://stackoverflow.com/q/48514985
tags question: http://stackoverflow.com/q/48496412
tags question: http://stackoverflow.com/q/48546823
tags question: http://stackoverflow.com/q/48603132
tags question: http://stackoverflow.com/q/48508942
tags question: http://stackoverflow.com/q/48625597
tags question: http://stackoverflow.com/q/48505409
tags question: http://stackoverflow.com/q/48638325
tags question: http://stackoverflow.com/q/48497090
tags question: http://stackoverflow.com/q/48603744
tags question: http://stackoverflow.com/q/48645233
tags question: http://stackoverflow.com/q/48585425
tags question: http://stackoverflow.com/q/48490940
tags question: http://stackoverflow.com/q/48506950
tags question: http://stackoverflow.com/q/48494492
tags question: http://stackoverflow.com/q/48491227
tags question: http://stackoverflow.com/q/48536953

http://stackoverflow.com/comment/84219033
type: Comment
comment on: http://stackoverflow.com/a/48602806
type: AnswerComment
has text: @brewcrazy share us the output when you try access to the API
score: 0

http://stackoverflow.com/comment/84224320
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48612077
type: QuestionComment
has text: @Alex, I believe that fundamentally your problem is bad for modern CPUs because if `amount` is as random as it looks in your examples, your code will break branch prediction quite often which is bad.

http://stackoverflow.com/comment/84099202
type: Comment
type: QuestionComment
has text: Could well be -- `grep` is heavily optimized. That said, if you're going to be doing this repeatedly, getting your data into an indexed format so this stops being an O(n) operation is in your interest. (If the lines are sorted, for instance, then it's a bisect operation to find either the start or the end of the section that starts with `>`; that gives you the number of *bytes* between those two regions in amortized constant time).
score: 0
comment on: http://stackoverflow.com/q/48551165

http://stackoverflow.com/comment/84050936
score: 1
type: Comment
has text: you don't say what code you used to move the legend to the bottom
type: QuestionComment
comment on: http://stackoverflow.com/q/48527614

http://stackoverflow.com/a/48635178
score: 4
answers question: http://stackoverflow.com/q/48635104
has comment: http://stackoverflow.com/comment/84291547
has comment: http://stackoverflow.com/comment/84269108
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/84268250
has body: One way is to use the regular expression and use the ? operator to check if an extra y occurs in the string . That is ,we find occurences of ky and the check if the next value is y if it occurs we take it else we dont &gt;&gt;&gt; import re &gt;&gt;&gt; st = 'kkyykykyyk' &gt;&gt;&gt; re.findall(r'kyy?',st) ['kyy', 'ky', 'kyy'] &gt;&gt;&gt; re.findall(r'kyy?',st).count('kyy') 2 &gt;&gt;&gt; re.findall(r'kyy?',st).count('ky') 1
downvote count: 0

http://stackoverflow.com/comment/84283184
score: 0
type: AnswerComment
has text: Then I recommend to post more info about how you start application and the application code (essentials) itself so people can check what's going on. Perhaps posting example part of `config.ini` possible?
comment on: http://stackoverflow.com/a/48642361
type: Comment

http://stackoverflow.com/a/48528262
type: Answer
has comment: http://stackoverflow.com/comment/140044058
score: 8
downvote count: 2
has body: Alternatively, a backslash \ can be put at the end of line except the last one. t_values = df_grouped_by_day \ .sort_values('day_of_week') \ .groupby(['day_of_week', 'day_of_week_name'])['Show_up'] \ .apply(lambda sample: ttest_ind(population, sample)) \ .reset_index()
answers question: http://stackoverflow.com/q/48528146
upvote count: 10

http://stackoverflow.com/q/48549535
tagged with: python
has comment: http://stackoverflow.com/comment/84095524
possible better answer: http://stackoverflow.com/a/60995412
has body: How can the amount of available lines in a terminal be found? Preferably in a cross-platform manner but any suggestions (even OS-specific) are welcome. The height and length of a terminal can be found using the os module however this does not take into account the amount of lines that may already have been used. To clarify things here is an example: In this example the height of the terminal here is 33 however since 3 lines have been used, only 30 lines are available.
favorite count: 0
score: 8
type: Question
has answer: http://stackoverflow.com/a/60995412
answer count: 2
has answer: http://stackoverflow.com/a/48550155
upvote count: 9
has comment: http://stackoverflow.com/comment/88761427
has comment: http://stackoverflow.com/comment/84095292
has title: Getting the amount of available lines in a terminal
has comment: http://stackoverflow.com/comment/84095314
has comment: http://stackoverflow.com/comment/84095168
downvote count: 1
accepted answer: http://stackoverflow.com/a/48550155
has comment: http://stackoverflow.com/comment/84096323
type: AnsweredQuestion
tagged with: terminal
has comment: http://stackoverflow.com/comment/84096259
has comment: http://stackoverflow.com/comment/84095144
has comment: http://stackoverflow.com/comment/84095357

http://stackoverflow.com/a/48551710
accepted answer of: http://stackoverflow.com/q/48551370
type: AcceptedAnswer
downvote count: 0
has body: You are using groupby without any aggregate function which returns as groupby object, NOT a series. You need cost = df1.set_index(['ID', 'yy'])['cost'] pct = df2.set_index(['ID', 'yy'])['cost'] cost.mul(pct/100) ID yy 312 13 22214.421669 361 15 56583.626963 373 14 49756.096000 403 13 37895.000550 14 37895.000550 15 44316.319281 16 31211.543783 17 44477.374796
has comment: http://stackoverflow.com/comment/84100470
type: Answer
answers question: http://stackoverflow.com/q/48551370
score: 2
has comment: http://stackoverflow.com/comment/84100054
upvote count: 2
has comment: http://stackoverflow.com/comment/84099994

http://stackoverflow.com/comment/83984332
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48494269
has text: I can't give that question justice. The answer is moderately nuanced. This talk by Raymond Hettinger might be a good start: https://www.youtube.com/watch?v=Bv25Dwe84g0

http://stackoverflow.com/comment/83991170
type: AnswerComment
has text: Thanks! Super useful. Any chance of putting it into an IF/Else statement? I'm trying to update values in a np.zeros according to the outcome of this...
type: Comment
comment on: http://stackoverflow.com/a/48497712
score: 0

http://stackoverflow.com/comment/84266686
has text: Just beat me to it!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48634942

http://stackoverflow.com/a/48616798
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/84231247
score: 2
has comment: http://stackoverflow.com/comment/84230562
has body: I have made an attempt to edit combinations according to your requirements : def combinations(iterable, r): # combinations('ABCD', 2) --&gt; AB AC AD BC BD CD # combinations(range(4), 3) --&gt; 012 013 023 123 pool = tuple(iterable) n = len(pool) if r &gt; n: return indices = list(range(r)) # yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 # print(tuple(pool[i] for i in indices ), "hai") if 1 in tuple(pool[i] for i in indices ) and 3 in tuple(pool[i] for i in indices ): pass else: yield tuple(pool[i] for i in indices) d = combinations(list(range(1, 6)),4) for i in d: print(i) It will return something like this : (1, 2, 4, 5) (2, 3, 4, 5)
answers question: http://stackoverflow.com/q/48616694
has comment: http://stackoverflow.com/comment/84269076
has comment: http://stackoverflow.com/comment/84231220
has comment: http://stackoverflow.com/comment/84230519
downvote count: 1
has comment: http://stackoverflow.com/comment/84230464

http://stackoverflow.com/comment/84265525
comment on: http://stackoverflow.com/q/48632349
has text: i saw that post before, but i didn't think it was applicable because im not using a virtualenv. i just downloaded the file i had to edit, then ran it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48597248
has body: You need something like this: folder_name = 'abc' execfile("/a/b/c/{folder_name}".format(folder_name=folder_name))
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48597234

http://stackoverflow.com/q/48604495
tagged with: python
tagged with: dictionary
has body: I am trying to load some data from a .mat file with scipy's io.loadmat(). The function basically returns a dictionary containing all the data from the file. And if I just want to get one value from the data file, I can do something like val_a = io.loadmat(filename)['val_a']. But now I'd like to take 2 values out. Can I also achieve this with only one command? Or do I have to first assign the dictionary to a variable and then get the two values one by one? Like raw_data = io.loadmat(filename) val_a = raw_data['val_a'] val_b = raw_data['val_b'] But what I am looking for is something like val_a, val_b = io.loadmat(filename)['val_a', 'val_b'] By doing so I hope to avoid unnecessary data from the file occupying my memory.
has title: How to access 2 keys with 1 command in python dictionary
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48604570
accepted answer: http://stackoverflow.com/a/48604570
tagged with: scipy
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48604519
possible better answer: http://stackoverflow.com/a/48604519

http://stackoverflow.com/a/48563841
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48563302
answers question: http://stackoverflow.com/q/48563302
type: Answer
upvote count: 4
score: 4
has body: You can do this by putting white frames inside a black one and using the padx and pady arguments of grid: import tkinter as tk root = tk.Tk() frame = tk.Frame(root, bg='black') frames = [] for i in range(3): frames.append([]) for j in range(3): frames[i].append(tk.Frame(frame, bg='white', width=50, height=50)) frames[i][j].grid(row=i, column=j, padx=((j != 0) * 2, (j != 2) * 2), pady=((i != 0) * 2, (i != 2) * 2)) frame.pack() root.mainloop() padx and pady can either take a single number to get a symmetrical result or a tuple of values:padx=(&lt;left&gt;, &lt;right&gt;) and pady=(&lt;top&gt;, &lt;bottom&gt;).

http://stackoverflow.com/comment/84269294
type: Comment
type: AnswerComment
has text: I understand that, generally I define my variables at the start of main, but the pseudo code I'm supposed to follow places the code in this order. I'm going to assume my professor made an error and rewrite as I see fit
comment on: http://stackoverflow.com/a/48615668
score: 0

http://stackoverflow.com/comment/136668125
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
comment on: http://stackoverflow.com/a/77519676
score: 0

http://stackoverflow.com/q/48640001
upvote count: 3
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84348847
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84348592
has comment: http://stackoverflow.com/comment/84303672
linked to: http://stackoverflow.com/q/5136611
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48633847
has body: I'm trying to figure out how to redirect/catch (in a string) all output from argparse.parse_args() to a upd-socket (server), but not from stdout in general. Eg when running this code: import argparse parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('-x', nargs=2) parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz')) args = parser.parse_args('-x p g -h'.split())
tagged with: http-redirect
tagged with: python
tagged with: sockets
score: 3
has answer: http://stackoverflow.com/a/62923345
has title: redirect all out from argparse to a socket connection but not stdout in general
tagged with: argparse

http://stackoverflow.com/comment/84173955
type: QuestionComment
has text: … that is useful to understand and convey to others. Nobody answers C question by saying “C is like this” and linking to some summary of C (not even the standard). Why is floating-point given short shrift? Aside from the specification, there are textbooks written about it, there are theorems, there are specific techniques and algorithms, there are ways to calculate error bounds, ways to avoid errors, and more. The answer to floating-point questions is not “Floating-point is inaccurate; give up.”
comment on: http://stackoverflow.com/q/48574261
score: 0
type: Comment

http://stackoverflow.com/comment/83976984
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48491609
has text: re_path('lifecoaching/resultslifecoaching/(?P<user_name>[\w.@+-]+)/', views.LifeCoachSearchResults, name='results_life_coaching'), ofc you have to import re_path next to path
type: Comment

http://stackoverflow.com/comment/84115611
comment on: http://stackoverflow.com/a/48558119
type: AnswerComment
has text: I see that `df.shape[0]` is just slightly less terse than `len(df)` but why does pandas handle a n-length 1D `np.array` so different to an nx1, 2D array? I think that was the crux of my problem.
score: 0
type: Comment

http://stackoverflow.com/q/48594502
tagged with: raspberry-pi3
has body: A simple program to open and close 2 doors with servo motor depending on the content of unlock.txt file. It just give Segmentation Fault. I did: ulimit -s 20000 Earlier it was around 8000, since i am on my raspberry pi 3. Still getting Segmentation Fault. from time import sleep import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(40,GPIO.OUT) GPIO.setup(38,GPIO.OUT) GPIO.output(40,GPIO.LOW) GPIO.output(38,GPIO.LOW) pwm1=GPIO.PWM(40,50) pwm2=GPIO.PWM(38,50) flag=0 prevlok=0 while(True): with open('/home/pi/Documents/HAP/unlock.txt','r') as f1: unlock=f1.read() if flag == 0: if unlock == '1': pwm1.start(2.5) pwm2.start(2.5) sleep(2) pwm1.stop() pwm2.stop() flag=1 else: pwm1.start(7.5) pwm2.start(7.5) sleep(2) pwm1.stop() pwm2.stop() flag=1 if prevlok != unlock: flag=0 else: flag=1 prevlok=unlock
type: Question
has answer: http://stackoverflow.com/a/48594886
type: UnansweredQuestion
tagged with: python
has title: simple python program segmentation fault
score: 0
answer count: 1

http://stackoverflow.com/comment/84223748
type: QuestionComment
has text: Update: cost variable matches MSE as well.
type: Comment
comment on: http://stackoverflow.com/q/48612519
score: 0

http://stackoverflow.com/q/48533101
type: Question
has body: I am trying to use selenium to send credit card info onto a site, and each element is contained in a separate iframe tag in the HTML. For example, the box to enter a credit card number is contained in the first iframe tag, and the card holder name is contained in the second iframe, and so on, and so forth. I am able to access the first iframe tag, and send the credit card number into the box, however I an unable to locate the cardholder name iframe tag, and thus cannot send the keys to enter a cardholder name. I'm wondering if there is a way to specifically search for the second (or an arbitrary number other than the first element) iframe tag with webdriver. Here is the code I used: driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) cc = driver.find_element_by_id("number") cc.send_keys(credit_card_number) This correctly found the first iframe tag which contains the field to enter a card number, and sent the appropriate keys driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) driver.find_element_by_id("name").send_keys(cc_name) This resulted in the following error: Message: no such element: Unable to locate element:{"method":"tag name","selector":"iframe"}
possible better answer: http://stackoverflow.com/a/48534421
has answer: http://stackoverflow.com/a/48540002
has answer: http://stackoverflow.com/a/48534421
accepted answer: http://stackoverflow.com/a/48540002
tagged with: python
has comment: http://stackoverflow.com/comment/84066962
has title: Multiple iframe tags Selenium webdriver
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: iframe
linked to: http://stackoverflow.com/q/47770144
tagged with: selenium
tagged with: webdriver
favorite count: 0

http://stackoverflow.com/comment/84070752
type: Comment
score: 2
comment on: http://stackoverflow.com/a/48536000
type: AnswerComment
has text: To compute distances between the points in two different arrays, use [`scipy.spatial.distance.cdist`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html) (not `pdist`).

http://stackoverflow.com/q/48543834
favorite count: 0
has comment: http://stackoverflow.com/comment/139299751
type: Question
tagged with: docker
tagged with: docker-multi-stage-build
has comment: http://stackoverflow.com/comment/84402056
has title: How do I reduce a python (docker) image size using a multi-stage build?
tagged with: python
upvote count: 60
answer count: 4
accepted answer: http://stackoverflow.com/a/48714519
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48543945
has body: I am looking for a way to create multistage builds with python and Dockerfile: For example, using the following images: 1st image: install all compile-time requirements, and install all needed python modules 2nd image: copy all compiled/built packages from the first image to the second, without the compilers themselves (gcc, postgers-dev, python-dev, etc..) The final objective is to have a smaller image, running python and the python packages that I need. In short: how can I 'wrap' all the compiled modules (site-packages / external libs) that were created in the first image, and copy them in a 'clean' manner, to the 2nd image.
has answer: http://stackoverflow.com/a/48714519
score: 60
downvote count: 0
possible better answer: http://stackoverflow.com/a/61879604
has answer: http://stackoverflow.com/a/71088501
tagged with: dockerfile
has answer: http://stackoverflow.com/a/61879604

http://stackoverflow.com/q/48565021
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84126843
tagged with: string
linked to: http://stackoverflow.com/q/15890743
has comment: http://stackoverflow.com/comment/84127196
favorite count: 0
has title: How do I split a Very huge string And string without spaces?(python3)
has comment: http://stackoverflow.com/comment/84126500
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/84127090
has body: Firstly I have this long string s = '1MichaelAngelo' How can I get the output as new_s = '1 Michael Angelo' and as a list new_list = [1,'Michael', 'Angelo'] Note: I have like a thousand I parsed from an html. Secondly, I have this huge string (consists of names and numbers up to 1000]). E.g 1\nfirstName\nlastName\n.......999\nfirstName\nlastName where \n denotes a newline. How can I extract data from it to output something like: [1, 'Michael', 'Emily], [2,'Mathew','Jessica'], [3, 'Jacob', 'Ashley '] and so on.
has answer: http://stackoverflow.com/a/48603186

http://stackoverflow.com/q/48589653
tagged with: grumpy
tagged with: python
has comment: http://stackoverflow.com/comment/84178340
has comment: http://stackoverflow.com/comment/84178542
has body: I wrote a HelloWorld.py and using grumpy I compiled the HelloWorld.py to a Go source code. but after running go build, the binary file does not get generated, the go build command was executed successfully without any error but there was no binary file found in the folder. here is the code inside HelloWorld.py: def hello(): print("hello, world") here is the generated code in hello.go: package __main__ import πg "grumpy/build/src/grumpy" var Code *πg.Code func init() { Code = πg.NewCode("&lt;module&gt;", "hello.py", nil, 0, func(πF *πg.Frame, _ []*πg.Object) (*πg.Object, *πg.BaseException) { var πR *πg.Object; _ = πR var πE *πg.BaseException; _ = πE ßhello := πg.InternStr("hello") var πTemp001 *πg.Object _ = πTemp001 var πTemp002 []πg.Param _ = πTemp002 for ; πF.State() &gt;= 0; πF.PopCheckpoint() { switch πF.State() { case 0: default: panic("unexpected function state") } // line 1: def hello(): print "hello, world" πF.SetLineno(1) πTemp002 = make([]πg.Param, 0) πTemp001 = πg.NewFunction(πg.NewCode("hello", "hello.py", πTemp002, 0, func(πF *πg.Frame, πArgs []*πg.Object) (*πg.Object, *πg.BaseException) { var πTemp001 []*πg.Object _ = πTemp001 var πR *πg.Object; _ = πR var πE *πg.BaseException; _ = πE for ; πF.State() &gt;= 0; πF.PopCheckpoint() { switch πF.State() { case 0: default: panic("unexpected function state") } // line 1: def hello(): print "hello, world" πF.SetLineno(1) πTemp001 = make([]*πg.Object, 1) πTemp001[0] = πg.NewStr("hello, world").ToObject() if πE = πg.Print(πF, πTemp001, true); πE != nil { continue } } if πE != nil { πR = nil } else if πR == nil { πR = πg.None } return πR, πE }), πF.Globals()).ToObject() if πE = πF.Globals().SetItem(πF, ßhello.ToObject(), πTemp001); πE != nil { continue } } return nil, πE }) πg.RegisterModule("__main__", Code) } when i try to add the main function to the end of the hello.go and call init() like this : func main() { init() } i get this error when i run go build can't load package: package .: main.go:1:2: expected '…
has comment: http://stackoverflow.com/comment/84176689
has comment: http://stackoverflow.com/comment/84176833
has comment: http://stackoverflow.com/comment/84177579
score: 0
has answer: http://stackoverflow.com/a/56334764
answer count: 1
has comment: http://stackoverflow.com/comment/84176593
has title: binary file of the helloworld.go generated by Grumpy does not get generated
type: Question
tagged with: go
type: UnansweredQuestion

http://stackoverflow.com/q/48519049
tagged with: kivy
type: Question
has title: Kivy BoxLayout size_hint not working?
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: sizehint
has body: i observed that size_hint_x doesn't work in BoxLayout, e.g. BoxLayout: Button: Size_hint_x: #any value above zero has same effect, it streches to full x axis width. or BoxLayout: orientation: 'vertical' Button: Size_hint_y: #any value above zero has same effect, it streches to full y axis width. same for Popup, if i put value to zero it sets to a particular height or width, but if i use screen it works correctly. Am i missing something according to BoxLayout?
tagged with: boxlayout
favorite count: 0
score: 3
upvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/48523872

http://stackoverflow.com/q/48573494
favorite count: 0
has title: variable truth table to CNF / DNF
type: Question
tagged with: boolean-operations
score: 0
tagged with: boolean-expression
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48593021
answer count: 2
has answer: http://stackoverflow.com/a/48574239
upvote count: 1
type: UnansweredQuestion
downvote count: 1
tagged with: boolean-logic
has body: My code purpose is to create this truth table that is in the attached picture, however it is not working the code. The output for this code get different results from the truth table The truth table: . It needs to be identical to the truth table in the picture. I hope someone can figure out my mistake! def cnf(a, b, c, d): return [ [a, b, c, d], #2 [not a, not b, not c, d], #3 [not a, not b, c, not d], #4 [ not a, not b, c, d], #5555 [a, not b, c, d], #6 [a, not b, c, not d], #777 [ [a, not b, not c, d], #8 [a, not b, c, d], #1 [a, not b, not c, not d], ] def dnf(a, b, c, d): return [ [not a, b, c, d], #1 [ a, not b, not c, d], [a, not b , not c, not d], #7777 [a, not b , c, not d], [ not a, b , not c, not d], #6 [a, b, not c, not d], #5 [ a, b , not c, d], #4 [a, b , c, not d], #3 [not a, not b , not c, not d], #2 ]

http://stackoverflow.com/q/48641798
has answer: http://stackoverflow.com/a/48643595
tagged with: flask
type: Question
score: 0
tagged with: python
has title: Python-Flask - render template within a class gives 404
has body: I am trying to run python with html using flask locally, i try to render a template within a class object, it compiles but when i try to access it on http://localhost:5000 it gives me 404. Could anyone tell what I'm doing wrong here? I am trying to display values from a json format using chart.js library. from flask import Flask from flask import render_template import os.path import json app = Flask(__name__) #import the json file _player_json_file = os.path.join(os.path.dirname(__file__), 'players.json') def read_players(player_file=None): if player_file is None: player_file = _player_json_file try: data = json.loads(open(player_file).read()) except IOError: return {} #make player dictionary players = {} #get player ID from json file = data. for playerID in data: players[playerID] = Player_data(data[playerID]) return players class Players_Data (object): @app.route("/") def __init__(self, data): """ Assign all the values from the json file to new variables the values are birth date age weight... """ self.player_ID = data['gsis_id'] self.gsis_name = data.get('gsis_name', '') self.player_fullname = data.get('full_name', '') self.player_first_name = data.get('first_name', '') self.player_last_name = data.get('last_name', '') self.player_weight = data.get('weight','') self.player_height = data.get('height' , '') self.player_birth = data.get('birthdate', '') self.player_pro_years = data.get('years_pro', '') self.player_team = data.get('data', '') values = [player_ID,gsis_name,player_fullname,player_first_name,player_last_name,player_weight] return render_template('chart.html', data=data, values=values) if __name__ == "__main__": app.run(host='localhost')
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/84169474
comment on: http://stackoverflow.com/q/48585468
score: 1
type: QuestionComment
type: Comment
has text: Is a pointer to someone else's solution in your interest? As part of his book "From Python to NumPy", Nicolas Rougier presents a vectorized game of life ([direct link](http://www.labri.fr/perso/nrougier/from-python-to-numpy/index.html#the-game-of-life))

http://stackoverflow.com/q/48593969
favorite count: 0
has title: Appending to multiple lists in a function - python
type: Question
has answer: http://stackoverflow.com/a/48599808
type: AnsweredQuestion
tagged with: python
has body: I have code that gets information from iTunes based on a search term that returns a list of dictionaries with various media types in it. I would like to group this information by whether or not it is a movie, song, or other media type. I want to do this within a function for later use, and was thinking the best way to do this would be to append each dictionary to a list based on what type it is. I am getting empty lists, even though the input I am putting in the function is a list of 100 dictionaries. Is there a better way to do this? This is my code - def make_object(list_from_req): movie_lst = [] song_lst = [] media_other_lst = [] for d in list_from_req: if d['kind'] == 'song': song_lst.append elif d['kind'] == 'feature-movie': movie_lst.append else: media_other_lst.append return movie_lst, song_lst, media_other_lst
has comment: http://stackoverflow.com/comment/84185571
score: -2
tagged with: dictionary
tagged with: python-3.x
tagged with: list
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84185585
accepted answer: http://stackoverflow.com/a/48599808
has comment: http://stackoverflow.com/comment/84196223

http://stackoverflow.com/q/48559538
has comment: http://stackoverflow.com/comment/84147114
has comment: http://stackoverflow.com/comment/84118462
has comment: http://stackoverflow.com/comment/84115142
has comment: http://stackoverflow.com/comment/84147392
score: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
downvote count: 1
has title: pywinauto - maybe too many control clause can not find element
has comment: http://stackoverflow.com/comment/84120614
has body: In pywinauto==0.6.3, self.Select_All_Templates.click_input() has a COMError. When I upgrade to 0.6.4 version, the COMError disappears but I get an ElementNotFound error, but a print_control_identifiers call shows that child_windows is correct. when I delete all list in the grid, and run the code again, error is gone. my GUI--picture pywinauto.findwindows.ElementNotFoundError: {'control_type': 'CheckBox', 'title': 'Select All Templates', 'top_level_only': False, 'parent': &lt;uia_element_info.UIAElementInfo - '', , None&gt;, 'backend': u'uia'} class Pywin(object): def __init__(self): self.app = application.Application(backend="uia") def controlor(self): self.about_dlg = self.app.window(class_name="Qt5QWindowIcon") self.Select_All_Templates = self.about_dlg["Pane"].child_window(title="Select All Templates", control_type="CheckBox") # self.Select_All_Templates = self.about_dlg["Select All Templates"] def dlg(self): # self.Select_All_Templates.wrapper_object().click_input() self.Select_All_Templates.click_input() def connect(self, window_name): self.app.connect(path = window_name) time.sleep(1) if __name__ == "__main__": app = Pywin() tool_name = "FingerPrint EVK Client *" window_name = r"E:\EVK\EVK\FingerPrintEVK_V1.19.10 Beta20\FingerPrintEVK_V1.19.10 Beta20.exe" app.connect(window_name) app.controlor() app.dlg()
tagged with: pywinauto
has comment: http://stackoverflow.com/comment/84164809
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84376792
has comment: http://stackoverflow.com/comment/84421490
tagged with: python

http://stackoverflow.com/a/48632064
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/48631087
type: Answer
has body: Change %Y for %y In the format string. %Y is for the year with four digits (2018) while %y is for 2 (18)
accepted answer of: http://stackoverflow.com/q/48631087

http://stackoverflow.com/a/48533199
type: Answer
accepted answer of: http://stackoverflow.com/q/48519570
answers question: http://stackoverflow.com/q/48519570
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Here is an example of how to do multiple patching class TestABCDFoo(unittest.TestCase): @mock.patch('hello.value_a', return_value='mocking_va') @mock.patch('hello.another_method', return_value='mocking_another') def test_result(self, mock_value_a, mock_another_method): """ The return_value better to be defined outside the test function with multiple patch """ a = value_a() self.assertEqual(a, 'mocking_va') result = abcd_foo(a, 'b', 'c', 'd') self.assertEqual(result, 'mocking_another')
score: 1

http://stackoverflow.com/a/48598854
answers question: http://stackoverflow.com/q/48598382
has body: I don't think above question's code snippet fits to a Minimal, Complete, and Verifiable example but at the very least it's runnable. You have three mistakes compared to that of: How to resize a scrollable frame to fill the canvas? The most significant of which is that in the linked question, the OP uses the option tags where you don't. Replace: self.canvas.create_window((0,0),window = self.innerFrame,anchor="nw") with: self.canvas.create_window((0,0),window = self.innerFrame, anchor="nw", tags="my_tag") Another mistake is that you're binding the event of a frame's resizing as opposed to the actual Canvas' resizing, also pointed out in Bryan's comment here. Replace: self.innerFrame.bind("&lt;Configure&gt;", self.set_canvas_scrollregion) with: self.canvas.bind("&lt;Configure&gt;", self.set_canvas_scrollregion) Lastly, tkinter doesn't seem to accept space character with tags, replace: self.canvas.itemconfigure("self.innerFrame ", width=width) with: self.canvas.itemconfigure("my_tag", width=width) Finally, you should have: from Tkinter import * class Scrollable_frame(Frame): def __init__(self, parent, title, values): self.parent = parent Frame.__init__(self, self.parent) self.canvas = Canvas(self, borderwidth=0, background="#ffffff") self.scrollbar = Scrollbar(self, command=self.canvas.yview) self.innerFrame = Radiobutton_frame(self.canvas,title,values) self.canvas.configure(yscrollcommand=self.scrollbar.set) self.canvas.grid(row=0, column=0, sticky= N+S) self.scrollbar.grid(row=0, column=1, sticky = N+S) self.canvas.create_window((0,0),window = self.innerFrame,anchor="nw", tags="my_tag") self.canvas.bind("&lt;Configure&gt;", self.set_canvas_scrollregion) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) def set_canvas_scrollregion(self, event): width = event.width - 4 self.canvas.itemconfigure("my_tag", width=width) self.canvas.config(scrollregion=self.canvas.bbox("all")) class Radiobutton_frame(LabelFrame): def __init__(self, parent, title, va…
has comment: http://stackoverflow.com/comment/84224040
score: 2
has comment: http://stackoverflow.com/comment/84581581
type: AcceptedAnswer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48598382
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84223825

http://stackoverflow.com/a/48575307
type: AcceptedAnswer
score: 0
has body: You need to assert that left and right are not None before calling .value on them: Python lazy evaluation of expressions allows you to do this on one line. if word_search is None or word_search.value is None will evaluate word_search, and if it is None, will not evaluate word_search.value. def iterative_word_search(current, user_input): word_search = current.root while True: if word_search is None or word_search.value is None: print("not found") break if word_search.value == user_input: print("found") break if(user_input &lt; word_search.value): word_search = word_search.left elif(word_search.right != None): word_search = word_search.right return word_search
type: Answer
accepted answer of: http://stackoverflow.com/q/48574363
has comment: http://stackoverflow.com/comment/84148285
answers question: http://stackoverflow.com/q/48574363

http://stackoverflow.com/comment/84114560
has text: Thank you both!!! It worked wonders.
score: 0
comment on: http://stackoverflow.com/q/48536340
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84098179
score: 0
has text: Yes, this is essentially correct. If it was a continuous field on the left it was pretty straight forward. But since it is oscillating in the vertical direction, I ponder what is the best approach..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48535471

http://stackoverflow.com/q/48501392
upvote count: 1
favorite count: 0
type: Question
has title: Read all emails from outlook
tagged with: outlook
tagged with: python
accepted answer: http://stackoverflow.com/a/48501521
type: AnsweredQuestion
has body: I wanted to check how can I read all emails from outlook in python I am using below code, but this code is reading only first mail, import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case, # the inbox. You can change that number to reference # any other folder messages = inbox.Items message = messages.GetLast() body_content = message.Body subject = message.Subject categories = message.Categories print(body_content) print(subject) print(categories) I tried to find a way so that we can read all emails but unable to get a solution, is anyone know how we can read all emails and store in the database.
has comment: http://stackoverflow.com/comment/84007676
has answer: http://stackoverflow.com/a/48501521
score: 1
has comment: http://stackoverflow.com/comment/83996444
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/84006788
type: Comment
comment on: http://stackoverflow.com/a/48506242
score: 0
has text: Excellent I'll give this a go but it looks like you've understood my question and this looks like the exact sort of answer I was looking for. Thank you very much
type: AnswerComment

http://stackoverflow.com/q/48574530
has comment: http://stackoverflow.com/comment/84145898
tagged with: tensorflow
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84146166
type: UnansweredQuestion
tagged with: cpu-usage
tagged with: python
has comment: http://stackoverflow.com/comment/84145852
has comment: http://stackoverflow.com/comment/84146147
score: 0
has body: My python 2.7 program with 'tensorflow-gpu' and 'numpy' run on a 32 cores CPU and 4 Nvidia Tesla K80 GPUs Server on ubuntu. When i use 'top', i find it use over 3000% cpu power. Why does this happen? It is only a single-threaded program.
answer count: 0
has title: Why does my single-thread python program use 3000% cpu power?

http://stackoverflow.com/comment/84141861
score: 0
has text: @Blckknght: Now that I write that out, I'm realizing that what I'm describing is a rather specific scenario, and a custom solution would be needed anyway :)
type: QuestionComment
comment on: http://stackoverflow.com/q/48572201
type: Comment

http://stackoverflow.com/comment/84169364
comment on: http://stackoverflow.com/q/48585988
type: Comment
has text: Check your file encoding make sure it doesn't have the BOM (byte order mark) in the encoding. You can see this using Notepad++.
score: 0
type: QuestionComment

http://stackoverflow.com/q/48540103
tagged with: rdd
has title: Pyspark : list of dictionaries to data frame
possible better answer: http://stackoverflow.com/a/48541192
answer count: 2
has comment: http://stackoverflow.com/comment/84075411
upvote count: 2
has answer: http://stackoverflow.com/a/48541192
score: 1
has body: I have a dataframe in which I have a column and each row contains a list of dictionaries : [ Row(payload=u"[{'key1':'value1'},{'key2':'value2'},{'key3':'value3'},{...}]"), Row(payload=u"[{'key1':'value1'},{'key2':'value2'},{'key3':'value3'},{...}]") ] How can I parse it to a dataframe structure like this: key1 | key2 | key3 | keyN | value1|value2|value3|valueN| value1|value2|value3|valueN|
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48541574
type: Question
type: AnsweredQuestion
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/48541574
has comment: http://stackoverflow.com/comment/91377065
tagged with: pyspark
tagged with: http://stackoverflow.com/tag/json
tagged with: python
linked to: http://stackoverflow.com/q/51713790

http://stackoverflow.com/a/48537574
has comment: http://stackoverflow.com/comment/84091709
type: Answer
has body: Without seeing the full program code; if you check the docs, it recommends putting the line: Py_SetProgramName(argv[0]); /* optional but recommended */ Before you make the Py_Initialize() function call. "The Py_SetProgramName() function should be called before Py_Initialize() to inform the interpreter about paths to Python run-time libraries" Make sure your main function has the argv argument like the example in the docs. #include &lt;Python.h&gt; int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; }
score: 0
has comment: http://stackoverflow.com/comment/84086064
answers question: http://stackoverflow.com/q/48527324
has comment: http://stackoverflow.com/comment/84088647

http://stackoverflow.com/q/48613681
type: UnansweredQuestion
tagged with: python
has title: How to get similar arrays in two lists using numpy?
score: 0
has answer: http://stackoverflow.com/a/48613895
has body: I have two lists characterized as such: circles_1 = [ array([[ [342. , 198. , 28.600698], [ 58. , 166. , 28.600698], [282. , 82. , 28.600698]]], dtype=float32), array([[ [ 78. , 174. , 24.351591], [302. , 234. , 24.207438], [314. , 114. , 23.43075 ]]], dtype=float32)] circles_2 = [ array([[ [ 76.5 , 193.5 , 21.505814], [355.5 , 121.5 , 22.726637], [355.5 , 274.5 , 22.726637]]], dtype=float32), array([[ [ 76.5 , 193.5 , 21.505814], [355.5 , 121.5 , 22.726637], [355.5 , 274.5 , 22.726637]]], dtype=float32)] If there exist possible array duplicates between the two lists, how can I get them using numpy? Is there a better way than looping through circles_1 and then for each element checking if it exists in circles_2?
answer count: 1
has comment: http://stackoverflow.com/comment/84224248
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84224359

http://stackoverflow.com/q/48509887
answer count: 1
has body: I have a very simple html template named my.html that is accessed simply by the class Wifi below, and I want to enable the user to download that same my.html document as a file. In class File I don't know how to access the template to place in the self.response.out.write argument. Alternatively is there a way for the user to download the template using appcfg.py or the likes directly from the Templates subdirectory? class Wifi(BaseHandler): def get(self): template_values = { } template = JINJA_ENVIRONMENT.get_template('my.html') self.response.out.write(template.render( template_values)) class File(webapp.RequestHandler): def get(self, upload_type): self.response.headers['Content-Type'] = 'text/script' self.response.headers['Content-Disposition'] = "attachment; filename=my.html" self.response.out.write(??????????????)
type: Question
has title: enable user to download template
tagged with: google-app-engine
tagged with: python
accepted answer: http://stackoverflow.com/a/48601272
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48601272
score: 0

http://stackoverflow.com/comment/84057389
type: QuestionComment
type: Comment
score: 0
has text: remove your 3rd and 4th line and then correct the indentation, see what you get
comment on: http://stackoverflow.com/q/48530848

http://stackoverflow.com/a/48593390
has comment: http://stackoverflow.com/comment/84184110
has comment: http://stackoverflow.com/comment/84184136
has comment: http://stackoverflow.com/comment/84184096
score: 0
answers question: http://stackoverflow.com/q/48593345
type: Answer
has comment: http://stackoverflow.com/comment/84184087
has body: You can do something like this: def studentGrades(a): # return [sum(k[1:])/(len(k)-1) for k in a[1:]] # Or l = len(a[0]) - 1 # how many quizzes, thanks to @Mad Physicist return [sum(k[1:])/l for k in a[1:]] grades= [['Student','Quiz 1','Quiz 2','Quiz 3','Final'], ['John', 100, 90, 80, 90], ['McVay', 88, 99, 11, 15], ['Rita', 45, 56, 67, 89], ['Ketan', 59, 61, 67, 32], ['Saranya', 73, 79, 83, 45], ['Min', 89, 97, 101, 100]] final = studentGrades(grades) print(final) Output: [90, 53, 64, 54, 70, 96]

http://stackoverflow.com/q/48519641
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84034399
accepted answer: http://stackoverflow.com/a/48519802
has comment: http://stackoverflow.com/comment/84211692
has answer: http://stackoverflow.com/a/48519802
has comment: http://stackoverflow.com/comment/84036181
has comment: http://stackoverflow.com/comment/84034288
has body: I am creating just a simple application for a live face detection using python opencv tkinter. I could do the live face detection but when I try to create a button to start the live feed, it is not even executing the program. Could anybody help me? from ttk import * import Tkinter as tk from Tkinter import * import cv2 from PIL import Image, ImageTk import os import numpy as np face_classifier = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml') global last_frame #creating global variable last_frame = np.zeros((480, 640, 3), dtype=np.uint8) global cap cap = cv2.VideoCapture(0) def show_vid(): #creating a function if not cap.isOpened(): print("cant open the camera") flag, frame = cap.read() frame = cv2.flip(frame, 1) if flag is None: print "Major error!" elif flag: global last_frame last_frame = frame.copy() pic = cv2.cvtColor(last_frame, cv2.COLOR_BGR2GRAY) faces = face_classifier.detectMultiScale(pic, 1.3, 5) for (x,y,w,h) in faces: x = x - 50 w = w + 50 y = y - 50 h = h + 50 cv2.rectangle(last_frame,(x,y),(x+w,y+h),(255,0,0),2) last_frame=cv2.cvtColor(last_frame, cv2.COLOR_BGR2GRAY) img = Image.fromarray(last_frame) imgtk = ImageTk.PhotoImage(image=img) lmain.imgtk = imgtk lmain.configure(image=imgtk) lmain.after(10, show_vid) if __name__ == '__main__': root=tk.Tk() lmain = tk.Label(master=root) lmain.grid(column=0, rowspan=4, padx=5, pady=5) root.title("Live face detection") button = Button(root, text = "Start", command=show_vid).pack() #show_vid() root.mainloop() cap.release() When I commented button line and uncommented show_vid() line live face detection works, but when I do the opposite it is not working.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84036801
tagged with: tkinter
upvote count: 0
score: -2
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84034115
has title: Cannot create a button
tagged with: python
tagged with: opencv

http://stackoverflow.com/comment/84169989
type: Comment
has text: my colums dont have names so I get the error "key_error: col_2"
comment on: http://stackoverflow.com/a/48586400
type: AnswerComment
score: 0

http://stackoverflow.com/a/48615956
answers question: http://stackoverflow.com/q/48615299
has body: One way by using itertools.product from itertools import product lst_eval = [(i, j[1:-1].split(',')) if j.startswith('[') else j for i,j in enumerate(mylist)] idx, lst = zip(*[l for l in lst_eval if isinstance(l, tuple)]) for p in product(*lst): for i, v in zip(idx, p): mylist[i] = v print (mylist) Output: ['I', 'want', 'to', 'go', 'to', 'park'] ['I', 'want', 'to', 'go', 'to', 'school'] ['I', 'want', 'you', 'go', 'to', 'park'] ['I', 'want', 'you', 'go', 'to', 'school']
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/48531960
type: UnansweredQuestion
has title: What are the ways for creating a Django project structure
has comment: http://stackoverflow.com/comment/84081289
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48533526
has body: I have been following Django tutorials. It says I can create projects using the following command: django-admin startproject mysite And then I can create apps using python manage.py startapp polls This gives me a standard project structure. When creating real life websites/portal is this how project structures are? Are there other ways of creating projects?
answer count: 1
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84059898

http://stackoverflow.com/q/48619709
has comment: http://stackoverflow.com/comment/87115788
has answer: http://stackoverflow.com/a/57326946
tagged with: enums
has body: Python's enum class supports iteration, but PyCharm has trouble figuring this out. from enum import Enum class Color(Enum): RED = 0 BLUE = 1 for color in Color: # Warning: Expected 'collections.Iterable', got 'Type[Color]' instead print(color) Though the method EnumMeta.__iter__ exists, PyCharm has trouble figuring this out. I don't mind manually adding type hinting to work around the problem, I'm just not sure what and where.
score: 21
has title: PyCharm type hinting enum iteration
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84242829
has comment: http://stackoverflow.com/comment/84242333
possible better answer: http://stackoverflow.com/a/64058653
has comment: http://stackoverflow.com/comment/84380191
answer count: 2
tagged with: pycharm
has answer: http://stackoverflow.com/a/64058653
has comment: http://stackoverflow.com/comment/84240592
downvote count: 0
upvote count: 21
tagged with: python-typing
has comment: http://stackoverflow.com/comment/107601001
accepted answer: http://stackoverflow.com/a/57326946
favorite count: 0
type: Question

http://stackoverflow.com/q/48608297
score: 2
type: AnsweredQuestion
has title: Error when storing content from a .txt file to a .xlsx using python
downvote count: 0
has answer: http://stackoverflow.com/a/51615865
accepted answer: http://stackoverflow.com/a/51615865
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
has body: I'm a new coder, currently trying to create a sample code for something bigger. I google'd most of my problems but I could not find any answers for the "final" problem, so I decided to post it. This code is basically something that opens a Excel file, gets a specific column's data, edits the data and saves it to a text file called "Saved.txt". The code works good till here. My problem is when I'm trying to upload all the data line by line into row by row to another Excel file. Please help me out! import openpyxl from openpyxl import Workbook Code = "0507" Save = open("Saved.txt","a") #Reading from XLSX and writing into a TEXT FILE after appending the data. fname = 'Wekanda 2.xlsx' wb = openpyxl.load_workbook(fname) sheet = wb.get_sheet_by_name('Wekanda 2') for rowOfCellObjects in sheet['R2':'R282']: for cellObj in rowOfCellObjects: line_w = cellObj.value line_w = str(line_w) line_w = line_w.replace(" ","@") Save.write("\n"+Code+line_w) test = str(line_w) Save.close() This code works perfectly till here. #Storing into Excel! book = Workbook() sheet = book.active with open("Saved.txt","r") as f: for line in f: for i in range(1,281): Pointer = "A"+str(i) sheet[Pointer] = line book.save("Next.xlsx") OUTPUT - EXCEL FILE | TEXT FILE | OUTPUT FILE 50 B2-3/3 | 050750@B2-3/3 | 050715 50 B2-3/4 | 050750@B2-3/4 | 050715 50 B2-3/5 | 050750@B2-3/5 | 050715 I want the content in the TEXT FILE to exactly be there on the OUTPUT FILE. Content in Text FILE. 050730 050740 050740A 050740B 050740-1/1 050740-1/2 050740-2/1 050740-2/2 050740-3/1 050740-3/2 050740-4/1 050740-4/2
tagged with: openpyxl
tagged with: excel-2010
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/84213401
has comment: http://stackoverflow.com/comment/84212948
tagged with: python-2.7

http://stackoverflow.com/a/48548244
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48545168
type: Answer
has body: What API are you connecting to? Try adding a user-agent to the header: r = requests.get(url, auth=HTTPBasicAuth(apiuser, apipass), headers={'User-Agent':'test'})
score: 1

http://stackoverflow.com/comment/135651199
comment on: http://stackoverflow.com/a/48526127
type: AnswerComment
has text: Is this really answering the question that was asked? I interpret the question as wanting to only *sample* from the video stream every second, and process it. Your solution will not skip any frames from a live network stream (i.e. an RTSP stream), every call to `cap.read()` will return the next frame in the sequence. How do you actually skip frames so you are sampling frames once per second?
score: 1
type: Comment

http://stackoverflow.com/a/48578920
downvote count: 0
has comment: http://stackoverflow.com/comment/84154253
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84154121
has comment: http://stackoverflow.com/comment/84154009
type: Answer
has body: Did you tried like this.? I hope It'll work in your case INSERT INTO products(products_amazon) VALUES ('one'), ('two'), ('three')....
answers question: http://stackoverflow.com/q/48578848
has comment: http://stackoverflow.com/comment/84154039
has comment: http://stackoverflow.com/comment/84154192

http://stackoverflow.com/a/48498189
has body: I found the solution Note our statement that recv() blocks until either there is data available to be read or the sender has closed the connection holds only if the socket is in blocking mode. That mode is the default, but we can change a socket to nonblocking mode by calling setblocking() with argument 0. I have modified the server.py import socket TCP_IP = '127.0.0.1' TCP_PORT = 8340 BUFFER_SIZE = 1024 # Normally 1024, but we want fast response s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() conn.setblocking(0) final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+') while 1: try: print('Connection address:', addr) r = conn.recv(BUFFER_SIZE).decode() final.write(r) print("received data:", r) except: break k="file received" conn.send(k.encode()) conn.close() Now I am able to receive the file and send message "file received" to client and connection is closed. non-blocking socket,error is always http://www.mws.cz/files/PyNet.pdf
type: Answer
answers question: http://stackoverflow.com/q/48496982
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48587475
has answer: http://stackoverflow.com/a/48587655
accepted answer: http://stackoverflow.com/a/48587655
has body: I am making a program to extract information out of some logs. The problem I am having is that I have a few loops to pick up different types of data on cluster nodes, but the loops all collect data on the nodes more than once and in a weird pattern. If I collect data on a 4 node cluster it will collect data in this order 1, 1, 2, 1, 2, 3, 3, 4, 3, 4 instead of just having data for 1,2,3,4 here is a sample def sysinfo_get(showall): for match in re.findall('&lt;system-information-get for pnode[^&lt;]+|', showall.read()): overview.append(match) overview = [] healthfile = open('..\Healthcheck.txt', 'w+') print('Collecting system info') for path, dirs, files in os.walk('.'): for f in files: if f.endswith('-showall.txt'): showall = open(os.path.join(path, f), 'r') sysinfo_get(showall) for i in overview: healthfile.write(i)
type: Question
upvote count: 0
downvote count: 2
tagged with: for-loop
score: -2
answer count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84172238
has title: Python loop collects data more than once and in weird order, what is going wrong?
tagged with: python

http://stackoverflow.com/comment/83994096
score: 0
has text: What do you mean with "my code is not working"? Do you have an error, and can you post that?
comment on: http://stackoverflow.com/q/48500373
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48559995
possible better answer: http://stackoverflow.com/a/48565531
has answer: http://stackoverflow.com/a/48569183
has answer: http://stackoverflow.com/a/48565531
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: pandas
tagged with: dataframe
has answer: http://stackoverflow.com/a/48560126
has title: generate every possible permutation
type: Question
has body: I have a dataframe as follows: project_id member_id 1 A 1 B 1 C 2 A 2 D 2 B I want to find all pairs of people that have worked together on at least one project. So the resulting dataframe should look like this: member_id co_member_id A B A C A D B A B C B D C A C B D A D B One way I could think of is to df.groupby('project_id') but then I would have to calculate a pairwise permutation of every possible unique value within each project_id , then drop any duplicate pairings in the resulting df. I was wondering if there was a more efficient way to do this.
has comment: http://stackoverflow.com/comment/84115818
accepted answer: http://stackoverflow.com/a/48560126
tagged with: python

http://stackoverflow.com/comment/84016437
comment on: http://stackoverflow.com/q/48510545
score: 0
type: Comment
type: QuestionComment
has text: Not sure I am pinning it on shift()... since it's working in a Spyder terminal window, i am not sure what's causing it. It's my first ever attempt at running a Python script in Tableau, so I am possibly mis-interpreting the error... here is the error from Tableau, trying to figure how to embed a screenshot of the error in Tabpy-server... TypeError : Object of type Series is not JSON serializable

http://stackoverflow.com/q/48516846
has comment: http://stackoverflow.com/comment/84163317
tagged with: php
score: 0
has comment: http://stackoverflow.com/comment/84164549
has answer: http://stackoverflow.com/a/48518018
tagged with: scientific-computing
has body: I'm working on my project in which i'm trying to classify image. for this i'm sending the image from the android device to the server for classification. On the server there is a php script that accepts the image and stores it in the uploads folder on the local server.below is the code that saves the image on server. upload.php &lt;?php // Path to move uploaded files $target_path = dirname(__FILE__).'/uploads/'; if (isset($_FILES['image']['name'])) { $target_path = $target_path . basename($_FILES['image']['name']); try { // Throws exception incase file is not being moved if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) { // make error flag true echo json_encode(array('status'=&gt;'fail', 'message'=&gt;'could not move file')); } //echo $output; $output = null; exec('python walnut_predict.py' ,$output, $return); echo json_encode(array('status'=&gt;'success', 'message'=&gt;$output)); // File successfully uploaded // echo json_encode(array('status'=&gt;'success', 'message'=&gt;$output)); } catch (Exception $e) { // Exception occurred. Make error flag true echo json_encode(array('status'=&gt;'fail', 'message'=&gt;$e-&gt;getMessage())); } } else { // File parameter is missing echo json_encode(array('status'=&gt;'fail', 'message'=&gt;'Not received any file')); } /* $output = null; exec('python walnut_predict.py' ,$output, $return); echo json_encode(array('status'=&gt;'fail', 'message'=&gt;$output)); //print_r($output); //print_r($return) */ ?&gt; walnut_predict.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): from keras.models import load_model from keras.models import Sequential import cv2 import demjson import numpy as np from Tkinter import Tk from tkFileDialog import askopenfilename from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img model = Sequential() model = load_model('first_try_walnut.h5') model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accur…
tagged with: python
has comment: http://stackoverflow.com/comment/84028549
has comment: http://stackoverflow.com/comment/84116669
type: Question
type: UnansweredQuestion
has title: how to execute scientific python scripts on server
answer count: 1
tagged with: neural-network

http://stackoverflow.com/a/48606301
answers question: http://stackoverflow.com/q/48605630
score: 0
type: Answer
has body: SMTP servers (usually) ignore duplicated recipients in message (e.g. duplicated RCPT TO:) . They deliver single copy to repeated recipient of message. If you want to get blocked by gmail then execute server.sendmail 1_000 times.

http://stackoverflow.com/a/48610172
has comment: http://stackoverflow.com/comment/133535306
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/128924629
score: 2
has body: You can actually just do boolean indexing like this: extracted = sampleArr[sampleArr &gt; 0.5]
answers question: http://stackoverflow.com/q/48610136
downvote count: 1
has comment: http://stackoverflow.com/comment/84217514

http://stackoverflow.com/comment/84105695
has text: Thanks much for your comment. Then wondering what should i do if i want to merge them based on their common column - "user_id" here? what i wanna figure out is how many people click the ad among the users listed on the master dataset. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/48554628
type: Comment
score: 0

http://stackoverflow.com/comment/84004628
has text: Sure, global values in a module are fine. You're trying to use globals to *span across* modules though, which doesn't work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48503893
score: 1

http://stackoverflow.com/comment/84016786
type: Comment
has text: Is that your actual indentation?
type: QuestionComment
comment on: http://stackoverflow.com/q/48510800
score: 0

http://stackoverflow.com/a/48525300
has body: You need the Python Development headers. Install sudo apt-get install python-dev or sudo apt-get install python3-dev first. Then try again. Update Realized you're on OpenSUSE so it'll be sudo zypper install python-dev or sudo zypper install python3-dev
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48525155
type: Answer
score: 2

http://stackoverflow.com/comment/84168994
comment on: http://stackoverflow.com/q/48585856
score: 0
type: Comment
type: QuestionComment
has text: Sorry. The correct link: https://stackoverflow.com/a/19747557/803316

http://stackoverflow.com/comment/84216828
score: 1
type: QuestionComment
has text: What is the problem here? What error are you getting?
type: Comment
comment on: http://stackoverflow.com/q/48610130

http://stackoverflow.com/comment/84138396
type: Comment
type: QuestionComment
has text: What happens if you type `which topydo` in Terminal?
comment on: http://stackoverflow.com/q/48570796
score: 0

http://stackoverflow.com/q/48509265
has comment: http://stackoverflow.com/comment/84019335
has comment: http://stackoverflow.com/comment/84014486
has body: Trying to subset a df by name inside a for loop that progresses through a list of names: names = ['Name','Name','Name'] &gt;&gt;&gt; type(names[0]) &lt;type 'str'&gt; df has a 'Name' column that is an object type containing strings, and when run locally, expressions like for i in names: csum = time_data.ix[:,(time_data['Name'].values==i)] or csum = time_data.loc[time_data['Name']==i] work just fine. However, once the app is deployed to GAE flexible, pandas throws KeyError: False for the first expression and TypeError: invalid type comparison for the second. This is Pandas version 0.22 and python 2.7.14. Can anybody tell me what's going on and how to fix it?! df looks like: &gt;&gt;&gt; time_data.head() Date Name In AM Out AM In PM Out PM 0 2018-01-04 TESTY TEST 7:03:24 AM 12:06:24 PM 12:38:06 PM 5:34:30 PM 1 2018-01-07 TESTY TEST 3:14:25 PM NaN NaN NaN &gt;&gt;&gt; time_data.dtypes Date datetime64[ns] Name object In AM object Out AM object In PM object Out PM object dtype: object &gt;&gt;&gt; type(time_data.Name[0]) &lt;type 'str'&gt; Full tracebacks: /env/local/lib/python2.7/site-packages/pandas/core/ops.py:816: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison Traceback (most recent call last): File "/env/local/lib/python2.7/site- packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/env/local/lib/python2.7/site- packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/env/local/lib/python2.7/site- packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/env/local/lib/python2.7/site- packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/env/local/lib/python2.7/site- packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/vmagent/app/timecard_report/views…
tagged with: pandas
tagged with: google-app-engine
score: 1
tagged with: python
has title: Pandas on GAE flexible Won't Subset DataFrame
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84014005
has comment: http://stackoverflow.com/comment/84018978
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48512231

http://stackoverflow.com/q/48593157
downvote count: 0
score: 16
tagged with: python
has answer: http://stackoverflow.com/a/59915795
upvote count: 16
tagged with: categorical-data
has comment: http://stackoverflow.com/comment/84183592
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48593212
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48593361
has title: Pandas dataframe encode Categorical variable with thousands of unique values
type: UnansweredQuestion
has body: I have a dataframe about data on schools for a few thousands cities. The school is the row identifier and the city is encoded as follow: school city category capacity 1 azez6576sebd 45 23 2 dsqozbc765aj 12 236 3 sqdqsd12887s 8 63 4 azez6576sebd 7 234 ... How can I convert the city variable to numeric knowing that I have a few thousand cities ? I guess one-hot encoding is not appropriate as I will have too many columns. What is the general approach to convert categorical variable with thousand of levels to numeric ? Thank you.

http://stackoverflow.com/q/48620526
accepted answer: http://stackoverflow.com/a/48630668
tagged with: selenium
has body: I'm trying to use ChromeDriver within with block to make the code look better and get rid of using driver.quit() command in the end. However, It doesn't seem to work. As soon as the browser opens, it throws the following error. Perhaps, I doing something wrong. Ain't there any way to do so? Thanks in advance. This is what I've tried: from selenium import webdriver with webdriver.Chrome() as wd: res = wd.get('https://stackoverflow.com/questions/') print(res.page_source) #Another failure attempt with the same error with webdriver.Chrome() as wd: wd.get('https://stackoverflow.com/questions/') print(wd.page_source) This is the error I'm having: with webdriver.Chrome() as wd: AttributeError: __exit__
favorite count: 0
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/84238471
possible better answer: http://stackoverflow.com/a/54149666
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/54149666
has title: How to use webdriver as context manager
tagged with: python
score: 15
upvote count: 15
tagged with: selenium-webdriver
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48630668

http://stackoverflow.com/a/68745001
score: 0
answers question: http://stackoverflow.com/q/48590268
has body: Getting top 5 most common lastname pandas: df['name'].apply(lambda name: name.split()[-1]).value_counts()[:5]
type: Answer

http://stackoverflow.com/a/48633948
accepted answer of: http://stackoverflow.com/q/48633861
downvote count: 0
answers question: http://stackoverflow.com/q/48633861
type: Answer
upvote count: 4
has body: That looks like a tab-delimited file. You can use sep='\t' and it should work fine. Indeed, the default value for pd.read_table is already sep='\t.
type: AcceptedAnswer
score: 4

http://stackoverflow.com/q/48498910
tagged with: lxml
score: 1
has answer: http://stackoverflow.com/a/48499383
downvote count: 0
tagged with: web-scraping
upvote count: 1
tagged with: html-parsing
has body: im working with automate my script to scrape counters from lan-website and im pulling my hairs now. code looks like this &lt;TR&gt;&lt;td&gt;&lt;p align="left" style="margin-left: 30;"&gt;&lt;b&gt;title&lt;/b&gt;&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt; &lt;/p&gt;&lt;/td&gt; &lt;/TR&gt; &lt;TR&gt;&lt;td&gt;&lt;p align="left" style="margin-left: 40;"&gt;table one&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt; Task&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;average &lt;/p&gt;&lt;/td&gt; &lt;/TR&gt; &lt;TR&gt;&lt;td&gt;&lt;p align="left" style="margin-left: 40;"&gt;&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt; number&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;number &lt;/p&gt;&lt;/td&gt; &lt;/TR&gt; &lt;TR&gt;&lt;td&gt;&lt;p align="left" style="margin-left: 40;"&gt;1-1&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;C&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt; 6490&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;1 &lt;/p&gt;&lt;/td&gt; &lt;/TR&gt; &lt;TR&gt;&lt;td&gt;&lt;p align="left" style="margin-left: 40;"&gt;2-4&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;C&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt; 442&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;2 &lt;/p&gt;&lt;/td&gt; &lt;/TR&gt; &lt;TR&gt;&lt;td&gt;&lt;p align="left" style="margin-left: 40;"&gt;5-10&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;C&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt; 44&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;6 &lt;/p&gt;&lt;/td&gt; &lt;/TR&gt; &lt;TR&gt;&lt;td&gt;&lt;p align="left" style="margin-left: 40;"&gt;11-20&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;C&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt; 3&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;15 &lt;/p&gt;&lt;/td&gt; &lt;/TR&gt; &lt;TR&gt;&lt;td&gt;&lt;p align="left" style="margin-left: 40;"&gt;21-30&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;C&lt;/p&gt;&lt;/td&gt;&lt;t…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83991124
possible better answer: http://stackoverflow.com/a/48499440
tagged with: python
has answer: http://stackoverflow.com/a/48499440
has title: lxml web-scraping, specific word extraction
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/48499383

http://stackoverflow.com/comment/84118980
score: 0
has text: Well, guess what? `['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__']`. I don't know, but I have no other script but lambda.py...
type: QuestionComment
comment on: http://stackoverflow.com/q/48551038
type: Comment

http://stackoverflow.com/a/48527728
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48527619
type: AcceptedAnswer
has body: ... when provided as default function arguments, they have to be defined before the function. Is this correct? Correct. Default arguments are evaluated at function definition time. If you need them evaluated at function call time, this common pattern works: def say_hello(message=None): if message is None: message = MESSAGE print(message) MESSAGE = "Hello, world!" say_hello()
type: Answer
has comment: http://stackoverflow.com/comment/84050567
accepted answer of: http://stackoverflow.com/q/48527619
upvote count: 3

http://stackoverflow.com/comment/84053788
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48529159
has text: @JohnColeman or better yet, `upper = str.upper`
type: Comment

http://stackoverflow.com/q/48562383
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49703284
has comment: http://stackoverflow.com/comment/84124124
tagged with: sasl
has comment: http://stackoverflow.com/comment/84123184
tagged with: python
has comment: http://stackoverflow.com/comment/84123996
has title: sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory
has body: I have OS Red Hat Enterprise Linux Server release 7.4 (Maipo) and python Python 2.7.13 :: Anaconda 4.4.0 (64-bit) Tried to install lib sasl sudo pip install sasl Collecting sasl Downloading http://repo.com/api/pypi/pypi/packages/8e/2c/45dae93d666aea8492678499e0999269b4e55f1829b1e4de5b8204706ad9/sasl-0.2.1.tar.gz Collecting six (from sasl) Downloading http://repo.com/api/pypi/pypi/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl Installing collected packages: six, sasl building 'sasl.saslwrapper' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/sasl gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Isasl -I/usr/include/python2.7 -c sasl/saslwrapper.cpp -o build/temp.linux-x86_64-2.7/sasl/saslwrapper.o In file included from sasl/saslwrapper.cpp:254:0: sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory #include &lt;sasl/sasl.h&gt; ^ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-Ym7ZOA/sasl/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-_8ahws-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-Ym7ZOA/sasl/ How solve this problem?
possible better answer: http://stackoverflow.com/a/49703284
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48897431
accepted answer: http://stackoverflow.com/a/48897431
answer count: 2
downvote count: 0
upvote count: 24
score: 24

http://stackoverflow.com/comment/84219764
type: AnswerComment
comment on: http://stackoverflow.com/a/48611204
score: 2
has text: You were right on target. That was the exact problem. Just one line wasted my whole day!
type: Comment

http://stackoverflow.com/q/48629568
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84256039
has answer: http://stackoverflow.com/a/48629790
tagged with: multiple-columns
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84256220
tagged with: python-3.x
has body: I want to drop multiple columns(around 800) from the dataframe using python. I have written below code: def corr_df(x, corr_val): # Creates Correlation Matrix and Instantiates corr_matrix = x.corr() iters = range(len(corr_matrix.columns) - 1) drop_cols = [] df_drop=pd.DataFrame() cols=[] # Iterates through Correlation Matrix Table to find correlated columns for i in iters: for j in range(i): item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)] col = item.columns row = item.index val = item.values if val &gt;= corr_val: # Prints the correlated feature set and the corr val #print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2)) drop_cols.append(i) drops = sorted(set(drop_cols))[::-1] df_dropped=x.drop(drops,axis=1) # Drops the correlated columns # for i in drops: # col=(x.iloc[:, (i+1):(i+2)].columns.values.tolist()) # print (col) # df_dropped=df.drop(col, axis=1) #cols.append() #print(df_dropped) return (df_dropped) But this code is printing the dataframe have only one column dropped. Any comments or suggestions on this? Thanks in advance
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84256396
tagged with: dataframe
tagged with: python
has title: Drop multiples columns from the dataframe in python
has comment: http://stackoverflow.com/comment/84256271
has comment: http://stackoverflow.com/comment/84256246
downvote count: 0
has comment: http://stackoverflow.com/comment/84256317
tagged with: pandas

http://stackoverflow.com/q/48608910
type: UnansweredQuestion
has title: Spotipy Getting songs of artists
tagged with: python
has comment: http://stackoverflow.com/comment/84221684
score: 0
tagged with: spotipy
answer count: 0
tagged with: spotify
has body: import spotipy import spotipy.util as util import json token =util.oauth2.SpotifyClientCredentials(client_id, client_secret) cache_token = token.get_access_token() spotify = spotipy.Spotify(cache_token) tids = [] track_list = [] artist_list = ['Taylor Swift','Linkin Park','Charlie Puth'] for artist in artist_list: print artist results = spotify.search(q=artist,limit = 50) for i, t in enumerate(results['tracks']['items']): tids.append(t['uri']) This gives me a an error like this : SpotifyException: http status: 400, code:-1 - <a href="https://api.spotify.com/v1/audio-features/?ids=4nVBt6MZDDP6tRVdQTgxJg,6tKW2g2So84pCTZXE0Furx,5O2P9iiztwhomNh8xkR9lJ,7kSLdGdXLey7pzLsWpdg1h,2K87XMYnUMqLcX3zvtAF4G,2afCBiru10AFckfOa49wIa,0HMjXBAZmSYOTTi33WpMso,72C7aUQECOhNtnD0AC36ua,3NLnwwAQbbFKcEcV8hDItk,3SPDQfj2UfWq6A2NllZnzn,2Bs4jQEGMycglOfWPBqrVG,5CRVwXGikmqzoRO6q7FeAg,5T7ZFtCcOgkpjxcuaeZbw0,3JjnGLK8IxkNLvo8Lb3KOM,0AkQbXGN4KG34TS7xLrM68,5omYVLodGmaxnhua99xIE8,48vlTTvosBO3rErgxYKxxR,4JaLkM90MJutDAl5jD9BZX,6nIE1oCE4udqMGv3bqVNVb,1ZWLWVqeEMWMKTlteS0yLH,1UAXlOxY1NXiJpP2sEK102,0L5gFNrzHyh4OhMwEz6DGS,6N5xh0tYYLTQRiCCaNbAUt,6aGjEZ7kq3YXgD0EDt80O5,34aYkYrY3sXhEU9O4VQgtB,6AzCBeiDuUXGXjznBufswB,6HFywc5eQYRRYHYTatCb5Y,4RC5YmcpCbRsX3AtRzoQeh,1dQQ2QlnvXUehsRUrukKmf,608R6FvRtAqf2dvgKMzebP,5AezhHjX3R1bmxcAEgrFpS,7pWzcvjSSXlGS0Cn790Nb7,5wjmqUGN7vrAqFqDWrywlZ,3cKM7UXBZmgjEgEBTkaIlU,03oZejWqXLbKhhM4iTgShq,4hJfmMjy3wFIOknfYwhouY,5Lf9rCqReE9Ri4tZvLRLuy,4RpsltwxERLiq6AXU39Dhx,0iSWAT0EL8TwmzcgBjKMh6,5dONhl6aXFuN86UBdayF6W,70OTIpw8x8UXUsuCHW9i1i,7rdP71W8x4UbJ0KAKBACbo,1BxXN8mBcTPhtuFLXD2dwH,7MbII8jWqFiTFYU3MPYEfW,5UgsZiYk1lkEobuPHmRtWm,6twW4ma6w0mOeejejPK0nY,3yAmqW5F28duOyV60VtIgN,7GtGeeChOx4NS77bqK8SUx,3UT493iwo6kvyL18zvAJE5,2Xcvt8NRLw0xbB3ClfW8MI,60a0Rd6pjrkxjPbaKzXjfq,2nLtzopw4rPReszdYBJU6h,18lR4BzEs7e3qzc0KVkTpU,3xXBsjrbG1xQIm1xv1cKOt,0UFDKFqW2oGspYeYqo9wjA,104buTcnP2AsxqB7U1FIZ4,3K4HG9evC7dg3N0R9cYqk4,7dyluIqv7QYVTXXZiMWPHW,57BrRMwf9LrcmuOsyGilwr,1Vej0qeQ3ioKwpI6FUbRv1,7oVEtyuv9NBmnytsCIsY5I,3FQCJI2t5L…
type: Question
has comment: http://stackoverflow.com/comment/84283703

http://stackoverflow.com/q/48493187
tagged with: pandas
score: 3
tagged with: group-by
tagged with: duplicates
tagged with: python
has answer: http://stackoverflow.com/a/48493249
possible better answer: http://stackoverflow.com/a/48493344
tagged with: pandas-groupby
has title: Adding duplicate rows to a DataFrame
has answer: http://stackoverflow.com/a/48493344
type: AnsweredQuestion
upvote count: 3
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/48493198
has answer: http://stackoverflow.com/a/48493198
favorite count: 0
has body: I did not figure out how to solve the following question! consider the following data set: df = pd.DataFrame(data=np.array([['a',1, 2, 3], ['a',4, 5, 6], ['b',7, 8, 9], ['b',10, 11 , 12]]), columns=['id','A', 'B', 'C']) id A B C a 1 2 3 a 4 5 6 b 7 8 9 b 10 11 12 I need to group the data by id and in each group duplicate the first row and add it to the dataset like the following data set: id A B C A B C a 1 2 3 1 2 3 a 4 5 6 1 2 3 b 7 8 9 7 8 9 b 10 11 12 7 8 9 I really appreciate it for your help. I did the following steps, however I could not expand it : df1 = df.loc [0:0 , 'A' :'C'] df3 = pd.concat([df,df1],axis=1)
type: Question

http://stackoverflow.com/comment/84105753
type: Comment
type: AnswerComment
has text: Thanks for the reply. Let say the result from generic_process_001 is needed to pass to customized_process_000 for further processing. How can I force certain structure? Or this is not making sense in Python as it is not strongly typed? A dict declared at the outmost scope is ok? It is just like that I declare a global variable and use elsewhere, which may not be a good practice.
score: 0
comment on: http://stackoverflow.com/a/48545519

http://stackoverflow.com/comment/84104516
has text: Ah ok, val loss doesn't ever decrease though (as in the graph). I did have an early stopping callback but it just gets triggered at whatever the patience level is. Is it possible that there is just no discernible relationship in the data so that it will never generalize? Sounds like I might need to work on more features?
type: QuestionComment
comment on: http://stackoverflow.com/q/48542473
score: 1
type: Comment

http://stackoverflow.com/q/48585827
tagged with: python
has title: How to make numpy array with 2D shape
has comment: http://stackoverflow.com/comment/84169764
tagged with: numpy
has answer: http://stackoverflow.com/a/48585935
tagged with: numpy-ndarray
has answer: http://stackoverflow.com/a/48586155
type: Question
score: 0
has answer: http://stackoverflow.com/a/48585867
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48585875
has answer: http://stackoverflow.com/a/48587831
has body: I have simple array like this x = np.array([1,2,3,4]) In [3]: x.shape Out[3]: (4,) But I don't want shape to return (4,), but (4,1). How can I achieve this?
answer count: 5

http://stackoverflow.com/q/48624364
has answer: http://stackoverflow.com/a/48624743
has comment: http://stackoverflow.com/comment/84245875
has answer: http://stackoverflow.com/a/48628935
has comment: http://stackoverflow.com/comment/84245664
has comment: http://stackoverflow.com/comment/84245422
has comment: http://stackoverflow.com/comment/84246033
score: 0
has answer: http://stackoverflow.com/a/48624936
has comment: http://stackoverflow.com/comment/84246108
answer count: 3
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84246275
has title: How do I locate the recursion conditions?
has comment: http://stackoverflow.com/comment/84245518
has comment: http://stackoverflow.com/comment/84245446
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84247324
has body: My code is as follows. I tried coding out for each case first, so given n = 4, my code looks like this: a = overlay_frac(0,blank_bb,scale(1/4,rune)) b = overlay_frac(1/4,blank_bb,scale(1/2,rune)) c = overlay_frac(1/2,blank_bb,scale(3/4,rune)) d = overlay_frac(3/4,blank_bb,scale(1,rune)) show (overlay(a,(overlay(b,(overlay(c,d)))))) My understanding is that the recursion pattern is: a = overlay_frac((1/n)-(1/n),blank_bb,scale(1/n,rune)) b = overlay_frac((2/n)-(1/n),blank_bb,scale(2/n,rune)) c = overlay_frac((3/n)-(1/n),blank_bb,scale(3/n,rune)) d = overlay_frac((4/n)-(1/n),blank_bb,sale(4/n,rune)) Hence, the recursion pattern that I came up with is: def tree(n,rune): if n==1: return rune else: for i in range(n+1): return overlay(overlay_frac(1-(1/n),blank_bb,scale(i/n,rune)),tree(n-1,rune)) When I hardcode this, everything turns out just fine, but I suspect I'm not doing the recursion properly. Where have I gone wrong?
tagged with: recursion
has comment: http://stackoverflow.com/comment/84245375
type: Question

http://stackoverflow.com/q/48626713
has title: customization command-line based installer
type: Question
has comment: http://stackoverflow.com/comment/84250280
tagged with: automation
has body: I want to use python to create an application for installing multiple programs. Most of witch have unique command line switches to make them install silently. I only want UAC to pop up once. A year ago I created one but it is not easily customization. Meaning if I want to add a new program to the install list I have to open the code and added it manually. The main thing I need answered is how to have UAC prompt once.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84421351
has comment: http://stackoverflow.com/comment/84250805
tagged with: python
linked to: http://stackoverflow.com/q/5944180
has comment: http://stackoverflow.com/comment/84250638
tagged with: uac
has comment: http://stackoverflow.com/comment/84251081
score: 0
has comment: http://stackoverflow.com/comment/84250790
tagged with: installation
answer count: 0

http://stackoverflow.com/q/48627165
has comment: http://stackoverflow.com/comment/84251213
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48629378
has title: Extract column from pandas dataframe
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84251340
answer count: 1
type: Question
tagged with: pandas
tagged with: python
tagged with: dictionary
has body: How can I extract a column as pandas df from a following pandas df containing dictionary: (I need all values of 'name' with the index) nutrients_df Out[63]: nutrients 0 [{'code': '203cp1252', 'name': 'Proteincp1252'... 1 [{'code': '203cp1252', 'name': 'Proteincp1252'... 2 [{'code': '203cp1252', 'name': 'Proteincp1252'... 3 [{'code': '203cp1252', 'name': 'Proteincp1252'... 4 [{'code': '203cp1252', 'name': 'Proteincp1252'... 5 [{'code': '203cp1252', 'name': 'Proteincp1252'... 6 [{'code': '203cp1252', 'name': 'Proteincp1252'... "nutrients_df" is defined as pandas df from json database as follows: nutrient_name=[] for index, row in data_df.iterrows(): nutrients1 = row['nutrients'] nutrients.append(nutrients1) nutrients_df = pd.DataFrame({'nutrients': nutrients})
has comment: http://stackoverflow.com/comment/84251369

http://stackoverflow.com/q/48640679
has answer: http://stackoverflow.com/a/48644847
has body: I am trying to execute the command below on cloudera hadoop, but it runs into problem and I am getting the error message. Not sure if its a bug or I have done something wrong. Any information would be much appreciated. hadoop jar /usr/lib/hadoop-mapreduce/hadoop-streaming.jar -files /home/cloudera/mapper.py /home/cloudera/reducer.py -mapper "python mapper.py" -reducer "python reducer.py" -input /user/cloudera/test_file -output /user/cloudera/wc_output01 error message: Found 1 unexpected arguments on the command line [/home/cloudera/reducer.py] Try -help for more information Streaming Command Failed!
tagged with: hadoop-streaming
possible better answer: http://stackoverflow.com/a/48642030
tagged with: mapreduce
type: Question
tagged with: hadoop
has title: Hadoop streaming - unexpected argument
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48642030
accepted answer: http://stackoverflow.com/a/48644847
type: AnsweredQuestion
score: 0

interpolation
tags question: http://stackoverflow.com/q/48582675
tags question: http://stackoverflow.com/q/48614440
type: Tag
tags question: http://stackoverflow.com/q/48535694
tags question: http://stackoverflow.com/q/48563101
tags question: http://stackoverflow.com/q/48527473
tag name: interpolation
tags question: http://stackoverflow.com/q/48619835
tags question: http://stackoverflow.com/q/48591984
tags question: http://stackoverflow.com/q/48562123

http://stackoverflow.com/comment/84259955
has text: Perfect! That did the trick. Thank you so, so much—much appreciated!
comment on: http://stackoverflow.com/a/48631407
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48549598
has answer: http://stackoverflow.com/a/48550288
favorite count: 0
has body: How do I get the union of a list of indices in pandas? I have the following, but is there a more elegant way? import pandas as pd def union_list_indices( list_of_indices): new_index = pd.Index([]) for index in list_of_indices: new_index = new_index.union(index) return(new_index)
type: Question
has title: Union of a list of indices
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/44761846
has comment: http://stackoverflow.com/comment/84095220
score: 2
has comment: http://stackoverflow.com/comment/84095212
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/84108896
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48556290
has text: Thanks! This seems the cleanest solution to me. Unfortunately the implementation hides a bit the fact that this is derived from `Cache`, but as you mentioned, without method overloading it is not possible to achive this.

digits
tags question: http://stackoverflow.com/q/48548330
tag name: digits
type: Tag

http://stackoverflow.com/a/48555973
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/48555847
type: Answer
score: -1
has body: you can use pyquery which allows you to make jquery queries on xml documents.

http://stackoverflow.com/q/48624119
type: Question
has body: I hope this question is unique and will help also other testers. I need the solution for python selenium. I need to replace several time.sleep() lines of code, by time explicit waits. When Chrome sleeps for few seconds before every element which is expected to be clicked, the test runs successfully, without, it fails. So it goes like this: driver.find_element_by_xpath("x").click() time.sleep(5) driver.find_element_by_xpath("y").click() time.sleep(5) driver.find_element_by_xpath("z").click() time.sleep(5) ... Implicity wait is not enough, for sure. Here is the recommended code: from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) element = wait.until(EC.element_to_be_clickable((By.ID, 'someid'))) I look at this example code, but it seems that I must refer to every single ID, in my case several times. So the question is: Is there any global solution to use explicit wait for every element in script, without multiplying lines of code?
has comment: http://stackoverflow.com/comment/84245334
tagged with: explicit
has title: General explicit wait - selenium python
tagged with: python
has comment: http://stackoverflow.com/comment/84245648
score: 2
has answer: http://stackoverflow.com/a/48624532
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: selenium
favorite count: 0

http://stackoverflow.com/comment/84204261
has text: Why does this class even exist? Python isn't Java; you don't need to stick absolutely everything in a class.
comment on: http://stackoverflow.com/q/48603786
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48514673
has comment: http://stackoverflow.com/comment/84023896
score: 8
type: Question
has answer: http://stackoverflow.com/a/48514749
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/136706867
downvote count: 0
linked to: http://stackoverflow.com/q/8886947
tagged with: python
has title: Shift letters by a certain value in python
favorite count: 0
upvote count: 8
has answer: http://stackoverflow.com/a/48514880
answer count: 3
has body: I had a coded text file that was coded by simple letter shifting. I have now gotten the information from it into two lists. In this format: list_1 =['fjsir', 'vnjk', 'eioafnvjf', 'einbvfbj'] list_2 =[3,4,7,1] The second list is by how many places in the alphabet should it move over. For eg. if index 0 in list one had 'fjsir' and it's corresponding index in list_2 is 3 then it would decode to 'cfpeo'. I'm not sure how I would match these in python.
has answer: http://stackoverflow.com/a/48514930

http://stackoverflow.com/comment/84181898
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48591812
has text: No need, If I am the visitor I would like see one answer contain all possible solution :-)
score: 0

http://stackoverflow.com/a/48603641
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48603517
has body: You have to use the indexAt() method of the QAbstractScrollArea (QTableView): def onRightClick(self, qPoint): index = self.view.indexAt(qPoint) if index.isValid(): print('onClick index.row: %s, index.col: %s' % (index.row(), index.column()))
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48603517

http://stackoverflow.com/q/48580822
tagged with: python
has answer: http://stackoverflow.com/a/50414810
tagged with: command-line-interface
type: Question
answer count: 2
tagged with: ansible
has body: I'm struggling to automate my deployment processes to WildFly over its cli. The cli itself don't work idempotent, so if I want to add using ansible for example some server properties it just threw an error in case it already exist (official cli documentation gives only 3 methods add, read, remove https://docs.jboss.org/author/display/WFLY10/CLI+Recipes - no replace or force add). So I need to create some conditions before, and the easiest is ready (just if exists): Ansible code: - name: Check Server Runtime properties shell: ./jboss-cli.sh --commands="connect {{ wf_server }},/core-service=platform-mbean/type=runtime:read-attribute(name=system-properties)" $AUTH_DATA args: chdir: "{{ wf_path }}/bin" register: srp_chk - name: Configure Some properties shell: ./jboss-cli.sh --commands="connect {{ wf_server }},/system-property={{ item.mkey }}:add(value=\"{{ item.mval }}\")" $AUTH_DATA args: chdir: "{{ wf_path }}/bin" when: "not '{{ item.mkey }}' in srp_chk.stdout" with_items: - { mkey: some.property1, mval: "{{ some_value1 }}" } - { mkey: some.property2, mval: "{{ some_value2 }}" } It works fine till the case when I need to change some_value1 or some_value2. In that case as you can get, I need to delete properties and create again. So we are almost near my question :) I know that these values could be found in srp_chk.stdout and I can create the same check for ex: when: "not '{{ item.mval }}' in srp_chk.stdout" BUT in case I have more complex structure and I need to compare two jsons in Ansible? Thats where my question begins :)) In my example srp_chk.stdout have Jboss cli output in Json format but in one line, and unfortunatelly when I try Jinja2 filter "from_json" it gives errors: the field 'args' has an invalid value ([]), and could not be converted to an dict "to_json" and "to_nice_json" gives some strange unreadable data and error: template error while templating string: expected token 'end of print statement', got 'outcome'. "outcome" - is content of my string. So…
type: UnansweredQuestion
tagged with: wildfly
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84159461
favorite count: 0
has answer: http://stackoverflow.com/a/48619239
has title: Convert Jboss (WildFly) cli output to json in Ansible
score: 1
has comment: http://stackoverflow.com/comment/84158763

http://stackoverflow.com/q/48594829
has comment: http://stackoverflow.com/comment/84190030
has comment: http://stackoverflow.com/comment/84186694
answer count: 0
has title: Update Django template without page refresh
downvote count: 0
tagged with: django
upvote count: 1
tagged with: jquery
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84192867
type: UnansweredQuestion
score: 1
has body: I have Django code like below and I am getting connected device details dynamically and I am updating in template. I am getting what I want but I want to refresh every time to know whether any new devices are connected or not. Here is my view code: class UserDashBoard(LoginRequiredMixin, TemplateView): def get_context_data(self, **kwargs): context = super(UserDashBoard, self).get_context_data(**kwargs) context['total_devices'] = get_device_mac_details(cmd='iw dev wlan0 station dump |grep Station |wc -l') return context Here is what my template looks like: MAC Id {% for device in total_devices %} {{ device }} {% endfor %} How can I get details without refreshing page?
has comment: http://stackoverflow.com/comment/84186736
tagged with: javascript
tagged with: python

http://stackoverflow.com/q/48577424
has body: After i have installed python 3.6.4 pip is not working i have done following procedure : Microsoft Windows [Version 10.0.16299.98] (c) 2017 Microsoft Corporation. All rights reserved. C:\WINDOWS\system32&gt;python --version Python 3.6.4 C:\WINDOWS\system32&gt;pip --version 'pip' is not recognized as an internal or external command, operable program or batch file. C:\WINDOWS\system32&gt;%PATH% 'F:\app\YASHRAJ\product\11.2.0\grid\bin' is not recognized as an internal or external command, operable program or batch file. C:\WINDOWS\system32&gt;echo %PATH% F:\app\YASHRAJ\product\11.2.0\grid\bin;C:\ProgramData\Oracle\Java\javapath;F:\app\YASHRAJ\product\11.2.0\dbhome_1\bin;C:\Program Files (x86)\Intel\iCLS Client\;C:\Progr am Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;c:\Program Files (x86)\ATI Technologies\ ATI.ACE\Core-Static;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program F iles (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Users\YASHRAJ\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\YASHRAJ\AppData\Local\Programs\Python\Python36-32\ ;C:\Program Files (x86)\Java\jdk1.8.0_45\bin;C:\Users\YASHRAJ\AppData\Local\Microsoft\WindowsApps;C:\Program Files (x86)\IDM Computer Solutions\UltraEdit\ C:\WINDOWS\system32&gt;
linked to: http://stackoverflow.com/q/43304612
score: 0
has answer: http://stackoverflow.com/a/48577656
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84152972
duplicate of: http://stackoverflow.com/q/43304612
type: Question
has comment: http://stackoverflow.com/comment/84152408
has comment: http://stackoverflow.com/comment/84158863
type: UnansweredQuestion
has title: pip not found after installation of python 3.6.4
linked to: http://stackoverflow.com/q/3701646

http://stackoverflow.com/a/48501282
score: 1
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48501023
has body: In order to return it as a list, you will first need to figure out the maximum expiration date in the fridge. max_expiration = max(food.expiration for food in fridge) +1 # need +1 since 0 is also a possible expiration exp_list = [0] * max_expiration for food in fridge: exp_list[food.expiration] += 1 print(exp_list) returns [0, 2, 0, 1, 1]
has comment: http://stackoverflow.com/comment/83996113
answers question: http://stackoverflow.com/q/48501023
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83998702
has comment: http://stackoverflow.com/comment/83996384

http://stackoverflow.com/q/48535471
tagged with: python
has comment: http://stackoverflow.com/comment/84108852
score: 2
upvote count: 2
tagged with: numpy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84074601
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/84100117
has comment: http://stackoverflow.com/comment/84085007
has comment: http://stackoverflow.com/comment/84110825
has comment: http://stackoverflow.com/comment/84122377
favorite count: 0
type: Question
has body: I have this 2D array, that looks like this using imshow: I would like to find an algorithm that fits a straight line that passes between the ends of the "fingers", in this fashion: Any ideas how can I do it? The 2D array data can be obtained from here http://dpaste.com/3H31X3G
has comment: http://stackoverflow.com/comment/84098179
has title: Python: fitting a straight line between first peaks in 2D array
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/84075408

http://stackoverflow.com/q/48604575
has answer: http://stackoverflow.com/a/48604618
linked to: http://stackoverflow.com/q/1906717
has title: Storing each digit of a number into separate variables
has answer: http://stackoverflow.com/a/48604656
tagged with: python
tagged with: sorting
possible better answer: http://stackoverflow.com/a/48604584
duplicate of: http://stackoverflow.com/q/1906717
answer count: 4
has answer: http://stackoverflow.com/a/48604584
has body: for example i have this variable: x=123 how can i convert it to a tuple or each digit into separate variables?: x=(1,2,3) or x1=1 x2=2 x3=3
type: AnsweredQuestion
score: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/84205842
downvote count: 2
accepted answer: http://stackoverflow.com/a/48604618
has answer: http://stackoverflow.com/a/48604611
favorite count: 0
type: Question

http://stackoverflow.com/q/48615284
tagged with: http://stackoverflow.com/tag/r
score: 2
type: AnsweredQuestion
has title: Suggestions on how to draw a concentric spheres plot?
has comment: http://stackoverflow.com/comment/84228371
possible better answer: http://stackoverflow.com/a/48640668
type: Question
has comment: http://stackoverflow.com/comment/84248293
has answer: http://stackoverflow.com/a/48640668
answer count: 2
has body: Hi, I am interested in drawing a figure, in R or python, resembling the attached image, where the largest sphere represents the total and each of the smaller spheres represent a certain percentage of the total?
has comment: http://stackoverflow.com/comment/84260433
upvote count: 3
accepted answer: http://stackoverflow.com/a/76031890
tagged with: python
has answer: http://stackoverflow.com/a/76031890
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84262901

http://stackoverflow.com/a/48635092
answers question: http://stackoverflow.com/q/48634538
type: Answer
has body: The django-bootstrap modules provides a set of convenience template tags and integration with existing django features such as forms. For instance, styling and rendering a django form in a template with bootstrap styling is as simple as {% bootstrap_form form %} As for upgrading to bootstrap4, django-boostrap4 is available. Of course nothing is forcing you to use the django bootstrap module if you prefer to manually write your own bootstrap HTML tag class names and that might be better for your specific use case.
score: 0

http://stackoverflow.com/q/48530306
tagged with: unix
type: Question
has title: How do I merge a remote repo with my current existing directory?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48533984
tagged with: django
tagged with: python
has body: I have my Django project in a Bitbucket repo that I want to merge with my newly created Digital Ocean server. The server directory contains a few basic files for a Django project for my server like env, static and manage.py. The Bitbucket repo has all my project apps etc. I've already done git remote add origin https://user@bitbucket.org/user/project.git from the server directory. So I then perform git merge master but it says Already up-to-date.. I've tried git pull master but it says: fatal: 'master' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Any idea what I can try?
tagged with: git
tagged with: bitbucket
score: 0
has comment: http://stackoverflow.com/comment/84056602
answer count: 1

http://stackoverflow.com/comment/84286023
score: 0
type: Comment
has text: I have a curiosity, usually when the application is launched the focus is placed in the app, how have you tried or eliminated the focus of the app in your current example?
type: QuestionComment
comment on: http://stackoverflow.com/q/48644511

http://stackoverflow.com/q/48493835
has answer: http://stackoverflow.com/a/48496020
upvote count: 0
answer count: 3
downvote count: 3
type: UnansweredQuestion
has title: Facial recognition Software using python
tagged with: image-processing
favorite count: 0
has answer: http://stackoverflow.com/a/48493911
tagged with: face-recognition
type: Question
has answer: http://stackoverflow.com/a/72305877
tagged with: opencv
score: -3
has body: I'm following a tutorial for creating a facial recognition software (link: https://pythonprogramming.net/haar-cascade-face-eye-detection-python-opencv-tutorial/) and I keep getting the error: OpenCV Error: Assertion failed (!empty()) in cv::CascadeClassifier::detectMultiScale, file C:\projects\opencv- python\opencv\modules\objdetect\src\cascadedetect.cpp, line 1698 Traceback (most recent call last): File "C:/Users/Jacob/PycharmProjects/DesignProject/main.py", line 17, in &lt;module&gt; faces = face_cascade.detectMultiScale(gray, 1.3, 5)". Looking at my code (below) and other questions like this online, it says that it was because I didn't specify my file path, but i still get the same error. I'm still new to this type of software, and python in general, so I'm not sure where I'm going wrong. Any help would be appreciated!!! import cv2 face_cascade = cv2.CascadeClassifier('/C:/User/Jacob/Downloads/haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('/C:/User/Jacob/Downloads/haarcascade_eye.xml') cap = cv2.VideoCapture(0) while 1: ret, img = cap.read() if ret is True: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: continue faces = face_cascade.detectMultiScale(gray, 1.3, 5) for(x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) roi_gray = gray[y:y+h, x:x+h] roi_color = img[y:y+h, x:x+h] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex, ey), (ex+ew), (ex+ew, ey+eh), (0, 255, 0), 2) cv2.imshow('img', img) k = cv2.waitKey(30) &amp; 0xFf if k == 27: break cap.release() cv2.destroyAllWindows() Thank you to those that helped!! the solution was to put the xml files into the working directory of the project instead of trying to type out the entire file path
has comment: http://stackoverflow.com/comment/83981013
tagged with: python

http://stackoverflow.com/q/48539511
tagged with: python
linked to: http://stackoverflow.com/q/47112527
has comment: http://stackoverflow.com/comment/84100219
upvote count: 6
answer count: 4
has answer: http://stackoverflow.com/a/48552385
linked to: http://stackoverflow.com/q/49194575
has comment: http://stackoverflow.com/comment/84099192
downvote count: 0
has answer: http://stackoverflow.com/a/49126828
score: 6
has body: I'm working on a Google App Engine application written in Python (Standard Environment) and I need to whitelist some additional modules in the development server environment. I have been doing it using this code in the appengine_config file for a long time, and it worked very well: from google.appengine.tools.devappserver2.python import sandbox sandbox._WHITE_LIST_C_MODULES += ['_ssl', '_socket'] As answered in this question, some time ago the Google Cloud SDK was updated and the previous import caused an ImportError. The import just needed to be changed to: from google.appengine.tools.devappserver2.python.runtime import sandbox With this change, everything worked well again, until I updated the Cloud SDK to version: 186.0.0. Now it seems a "SandboxAccessPreventionImportHook" class has been added to the sandbox module so it can't be imported from the App Engine application. This is the error the application is raising: ImportError: Importing the devappserver sandbox module (google.appengine.tools.devappserver2.python.runtime.sandbox) from user application code is not permitted. Does anyone have an idea on how to bypass this? Or is there another way to whitelist modules in the development server environment? Thanks!!!
has answer: http://stackoverflow.com/a/48576940
favorite count: 0
has answer: http://stackoverflow.com/a/49207323
type: Question
has comment: http://stackoverflow.com/comment/84096608
type: UnansweredQuestion
tagged with: google-app-engine
has title: ImportError: Importing the devappserver sandbox module from user application code is not permitted

http://stackoverflow.com/comment/100488872
score: 4
has text: I can confirm that setting `WTF_CSRF_TIME_LIMIT` in the config object still works when using `Flask-WTF==0.14.2` and `WTForms==2.2.1`. I can see the original question is 1.5 yrs old at this time, so I thought it'd be a good idea to leave this quick update here.
type: Comment
comment on: http://stackoverflow.com/a/52787726
type: AnswerComment

http://stackoverflow.com/q/48523575
has title: Searching terms in list, and replacing them with corresponding terms in seperate list
has body: So I am trying to find and replace some terms. I have 3 seperate files. The first file, we can call 'berries' and is the .txt file that includes terms we shall search for. The second file, 'newberries' is the .txt file that once a match is found, should replace the found match with the 'newberries'. The file in which we will be parsing and replacing will be 'berrylist.txt'. For the first two files the positions for the term to search for and term to replace it with are the exact same. So line 2 can be replaced with line 2 of the 'newberries' file and so on. I started thinking of building a dictionary and finding and replacing but could not wrap my mind around it. My second option would be to use regex and search the terms and just append my '_3' between the end of the name and the ' " ' that is is closed in. So in the file to be parsed it would show as "blackberry" and would need to append to make the term "blackberry_3". find = open('berries.txt') findline = list(find) replace = open('newberries.txt') replaceline = list(replace) with open('berrylist.txt') as f: lines = f.read() with open('berrylist.txt', 'w') as f: for findline in f: data = lines.replace(findline, replaceline) CONFIG FILE EXAMPLE: FILE NAME: td-adc-post.txt set device-group TESTDEV-ADC pre-rulebase security rules "IA - Auto Pod Control" set device-group TESTDEV-ADC pre-rulebase security rules "IA - Auto Pod Control" set device-group TESTDEV-ADC pre-rulebase security rules RDC_MQ set device-group TESTDEV-ADC pre-rulebase security rules RDC_MQ EXAMPLE SEARCH TERMS: FILE NAME: ADCdup.txt (on line 9) IA - Auto Pod Control (on line 50) RDC_MQ EXAMPLE CHANGE TERM TO: FILE NAME: ADCdupreplace.txt (on line 9) IA - Auto Pod Control_3 (on line 50) RDC_MQ_3
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84042291
downvote count: 1
has answer: http://stackoverflow.com/a/48523779
favorite count: 0
has comment: http://stackoverflow.com/comment/84042066
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84042299
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/48523779
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84042105

http://stackoverflow.com/a/48627356
answers question: http://stackoverflow.com/q/48627255
type: Answer
score: 4
upvote count: 4
has body: You can't use a dictionary comprehension for this, that can't know about preceding keys already being present. You'll have to use a straight-up loop. Add all values to a list, not just the repeating ones. Don't mix structures here, that'll only create more headaches later on. If you don't you'll have to detect if you have a nested list or a flat list with one fruit and price later on. You can use a regular dictionary: my_dict = {} for fruit, price, origin in lst1: my_dict.setdefault(origin, []).append([fruit, price]) The dict.setdefault() call adds an empty list to the dictionary if the key (the first argument) is missing. It then returns the value for the given key (which could be an already existing list or the new empty list). The line then call list.append() to add the fruit and price. Or you can use a collections.defaultdict() object to create the empty lists when a key is missing: from collections import defaultdict my_dict = defaultdict(list) for fruit, price, origin in lst1: my_dict[origin].append([fruit, price]) Code using a defaultdict is a little more concise, but the downside is that this object will now continue to produce empty lists for missing keys, even when you perhaps didn't intend to due to a bug in your code. Both produce the desired result: &gt;&gt;&gt; my_dict = {} &gt;&gt;&gt; for fruit, price, origin in lst1: ... my_dict.setdefault(origin, []).append([fruit, price]) ... &gt;&gt;&gt; my_dict {'Swiss': [['Apple', 20.0], ['Strawberry', 25.0]], 'Brazil': 'Banana', 5.0, 'Greece': 'Pear', 12.0, 'Peru': [['Mango', 3.0], ['Avacado', 7.0]]} &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; my_dict = defaultdict(list) &gt;&gt;&gt; for fruit, price, origin in lst1: ... my_dict[origin].append([fruit, price]) ... &gt;&gt;&gt; my_dict defaultdict(&lt;class 'list'&gt;, {'Swiss': [['Apple', 20.0], ['Strawberry', 25.0]], 'Brazil': 'Banana', 5.0, 'Greece': 'Pear', 12.0, 'Peru': [['Mango', 3.0], ['Avacado', 7.0]]})
accepted answer of: http://stackoverflow.com/q/48627255
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48531276
possible better answer: http://stackoverflow.com/a/48531547
has body: I am trying to calculate some polynomials given an input numerator and denominator polynomials as coefficient arrays. How can I create my polynomials from these arrays? E.g: Inputs: den= [2,3,4] num= [1,3] Output: (s+3)/(s^2+3*s+4) I need to use symbols because I will further need to divide the results by other polynomials and perform further polynomial computations. P.S Is sympy suitable for this? I would usually solve things like this in matlab but I want to expand my knowledge.
score: 2
type: AnsweredQuestion
answer count: 3
tagged with: sympy
upvote count: 2
downvote count: 0
tagged with: polynomials
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/75630912
has answer: http://stackoverflow.com/a/48531547
has title: How to create symbol polynomial from given array with sympy?
accepted answer: http://stackoverflow.com/a/48531424
has answer: http://stackoverflow.com/a/48531424
tagged with: python

http://stackoverflow.com/a/48609549
score: 1
answers question: http://stackoverflow.com/q/48605945
has body: Build dependencies are those required to build your project, while the run dependencies are those required to run the package once its installed. For instance, you may require a C compiler to build a C extension in your package, and then you'd require a (compatible) C library to run the package. Or, if you have a pure Python package, your build dependencies are likely to be Python and setuptools, while your run dependencies will be any other package that you import from within your package. See the documentation for further information, and note there is also a test requirements section where you can put dependencies that are only required to test your package. As far as I know, there is no way to automatically "copy" packages between an environment.yml and a meta.yml file. You could conceivably script some way to do that (perhaps with a Makefile from which you run conda build), but that seems quite complex and at least as prone to failure as manually copying the dependencies back and forth. Moreover, the packages in the environment.yml file are likely to be only the run dependencies, or perhaps a mish-mash of build and run dependencies, in which case, you'd have to manually manage the dependencies in meta.yaml anyways.
has comment: http://stackoverflow.com/comment/84336208
type: Answer
has comment: http://stackoverflow.com/comment/84312097
has comment: http://stackoverflow.com/comment/84456879
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48492221
score: 0
answers question: http://stackoverflow.com/q/48492155
has comment: http://stackoverflow.com/comment/83978264
has body: If I understand correctly, you want to retrieve the values of multiple dictionaries in the list. This can be done by using a list comprehension to iterate through the list and retrieve the values specified by the key, given that the list element is a dictionary. Below is a lambda function that works on your list and returns the values stored at 'apples' as a list. finder = lambda l, string: [x[string] for x in l if type(x) == dict] print(finder(f, 'apples')) # [430, 123] print(finder(f, 'peaches')) # [239, 345]
type: Answer

http://stackoverflow.com/comment/83989119
score: 0
type: Comment
has text: I have updated my answer. You need to provide the full path of the image.
type: AnswerComment
comment on: http://stackoverflow.com/a/48496303

http://stackoverflow.com/comment/84105692
comment on: http://stackoverflow.com/q/48554683
type: Comment
has text: @Shadow I'll use the servers at different times.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48493390
answers question: http://stackoverflow.com/q/48492273
has body: Remove all calls to update until your are ready for your UI to be visible, and don't use after(0, ...) because the zero means that code will run before tkinter has had a chance to process any other events, including requests to redraw portions of the screen.
score: 0
has comment: http://stackoverflow.com/comment/83999516
has comment: http://stackoverflow.com/comment/83998401
type: Answer
has comment: http://stackoverflow.com/comment/83998273

http://stackoverflow.com/comment/84204436
comment on: http://stackoverflow.com/q/48601728
score: 0
type: Comment
has text: Welcome to Stack Overflow! Please read [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and also [what have you tried](http://mattgemmell.com/what-have-you-tried/).
type: QuestionComment

http://stackoverflow.com/comment/131233859
comment on: http://stackoverflow.com/a/48714519
type: Comment
has text: This is probably a better solution than using the venv method which requires an env variable to be updated/image recreated.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48529687
type: AnsweredQuestion
has title: Python Encrypt PDF Simple Method AES 256
downvote count: 0
tagged with: pypdf
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/68096305
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/104433358
tagged with: encryption
accepted answer: http://stackoverflow.com/a/68096305
has comment: http://stackoverflow.com/comment/95461591
tagged with: python
has body: I have used this method to encrypt a PDF file with AES 128: import PyPDF2 pdffile = open(r"input.pdf", "rb") pdfReader = PyPDF2.PdfFileReader(pdffile) pdfWriter = PyPDF2.PdfFileWriter() for pageNum in range(pdfReader.numPages): pdfWriter.addPage(pdfReader.getPage(pageNum)) pdfWriter.encrypt('password') resultPDF = open(r"output.pdf", "wb") pdfWriter.write(resultPDF) resultPDF.close() ...but is there a similarly-simple way to use AES 256? Thanks in advance!

http://stackoverflow.com/a/55497985
score: 12
downvote count: 0
has body: You can filter with content_type and object_id, instead of content_object. from django.contrib.admin.options import get_content_type_for_model symbol = StockSymbol.objects.first() MyDailyPrice.objects.filter(content_type=get_content_type_for_model(symbol), object_id=symbol.pk)
answers question: http://stackoverflow.com/q/48605567
has comment: http://stackoverflow.com/comment/131099488
upvote count: 12
type: Answer

http://stackoverflow.com/a/48613050
has body: Permissions is the name of the class. To get the message authors permissions, you should access the guild_permissions property of the author. if ctx.message.author.guild_permissions.administrator: # you could also use guild_permissions.kick_members Update: A better way to validate the permissions of the person invoking the commands is by using the check feature of the commands extension, specifically the has_permissions check. For example, if you wanted to open your command only to people who had either the manage_roles permission or the ban_members permission, you could write your command like this: from discord import Member from discord.ext.commands import has_permissions, MissingPermissions @bot.command(name="kick", pass_context=True) @has_permissions(manage_roles=True, ban_members=True) async def _kick(ctx, member: Member): await bot.kick(member) @_kick.error async def kick_error(ctx, error): if isinstance(error, MissingPermissions): text = "Sorry {}, you do not have permissions to do that!".format(ctx.message.author) await bot.send_message(ctx.message.channel, text)
downvote count: 0
score: 17
upvote count: 17
has comment: http://stackoverflow.com/comment/84223809
type: Answer
answers question: http://stackoverflow.com/q/48612603
has comment: http://stackoverflow.com/comment/84224262
has comment: http://stackoverflow.com/comment/84223856
accepted answer of: http://stackoverflow.com/q/48612603
has comment: http://stackoverflow.com/comment/84224245
type: AcceptedAnswer

http://stackoverflow.com/q/48639281
has comment: http://stackoverflow.com/comment/84275677
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84276000
has comment: http://stackoverflow.com/comment/84275832
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/84275796
type: AnsweredQuestion
score: 2
upvote count: 3
has title: How to exactly compute percentage change with NaN in DataFrame for each day?
tagged with: pandas
has answer: http://stackoverflow.com/a/48639537
accepted answer: http://stackoverflow.com/a/48639537
answer count: 1
downvote count: 1
has body: I would like to compute a daily percentage change for this DataFrame (frame_): import pandas as pd import numpy as np data_ = { 'A':[1,np.NaN,2,1,1,2], 'B':[1,2,3,1,np.NaN,1], 'C':[1,2,np.NaN,1,1,2], } dates_ = [ '06/01/2018','05/01/2018','04/01/2018','03/01/2018','02/01/2018', '01/01/2018' ] frame_ = pd.DataFrame(data_, index=dates_, columns=['A','B','C']) The issue is that I get a DataFrame with this method: returns_ = frame_.pct_change(periods=1, fill_method='pad') dates,A,B,C 06/01/2018,,, 05/01/2018,,1.0,1.0 04/01/2018,1.0,0.5, 03/01/2018,-0.5,-0.6666666666666667,-0.5 02/01/2018,0.0,,0.0 01/01/2018,1.0,0.0,1.0 Which is not what I am looking for. And the dropna() method also doesn't give me the result I seek. I would like to compute a value for each day which has value and NaN for the day where there is no value or NaN. For example, on column A: as a percentage change I would like to see dates,A 06/01/2018,1 05/01/2018, 04/01/2018,1.0 03/01/2018,-0.5 02/01/2018,0.0 01/01/2018,1.0 Many thanks in advance

http://stackoverflow.com/comment/104031972
has text: This relies on the s3.amazonaws.com endpoint figuring out which region your bucket is in. That works for the aws partition, but it doesn't know anything about the GovCloud and China partitions. For GovCloud, it looks like s3-us-gov-west-1.amazonaws.com.
type: Comment
comment on: http://stackoverflow.com/a/56090535
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84263521
has text: The format looks perfect. The only issue is the dups.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48632824
type: AnswerComment

http://stackoverflow.com/a/48510327
has comment: http://stackoverflow.com/comment/84017441
has comment: http://stackoverflow.com/comment/84017960
accepted answer of: http://stackoverflow.com/q/48508938
has comment: http://stackoverflow.com/comment/84085374
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/84017477
has comment: http://stackoverflow.com/comment/84017681
type: AcceptedAnswer
downvote count: 0
has body: In curl, the -F or --form parameter is used to post multipart form data (files). In requests you can post files with the files parameter. In requests, the params parameter is used for query string data. If you want to send your data in the body of the POST request, you should use the data parameter. For basic authentication you can just use the auth parameter. So, your python code should look something like this, import requests url = 'https://www.sendowl.com/api/v1/products.xml' headers = {"Accept": "application/json"} auth = ('KEY', 'SECRET') data = {'product[name]':'test', 'product[product_type]':'digital', 'product[price]':'23'} files = {'product[attachment]': open('C:\Users\APPE\Desktop\SendOWL\\audi.jpg', 'rb')} r = requests.post(url, auth=auth, headers=headers, data=data, files=files) print(r.text)
answers question: http://stackoverflow.com/q/48508938
score: 2

http://stackoverflow.com/q/48497115
has title: ModuleNotFoundError at /polls/register/
type: Question
has comment: http://stackoverflow.com/comment/83990554
has comment: http://stackoverflow.com/comment/83990162
has comment: http://stackoverflow.com/comment/83991913
has comment: http://stackoverflow.com/comment/83988271
has comment: http://stackoverflow.com/comment/83988588
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/83990237
type: UnansweredQuestion
tagged with: django-forms
has comment: http://stackoverflow.com/comment/83987182
has body: I am creating a registration form in django. My project name is FirstProj containing mysite and mysite containing polls. My forms.py is this from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email= forms.EmailField(required = True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user My views.py is this from mysite.polls.forms import RegistrationForm from django.shortcuts import render,redirect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/polls') else: form = RegistrationForm() args = {'form': form} return render(request, 'polls/reg_form.html', args) However my cleaned_data() can't be read and i am getting the following erro. No module named 'mysite.polls' My urls.py in mysite is urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls', namespace= "polls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and, my urls.py in polls is from django.conf.urls import url from .import views from django.conf.urls import url from django.contrib.auth.views import login,logout urlpatterns= [ url(r'^$',views.index, name= "index"), #127.0.0.1/polls url(r'^(?P&lt;question_id&gt;[0-9]+)/$', views.detail, name= "detail"), #127.0.0.1/polls/1 url(r'^(?P&lt;question_id&gt;[0-9]+)/results$', views.results, name="results"), # 127.0.0.1/polls/1/results url(r'^(?P&lt;question_id&gt;[0-9]+)/vote$', views.vote, name="vote"), # 127.0.0.1/polls/1/vote url(r'^login/$', login, {'template_name': 'polls/login.html'}), url(r'^logout/$', logout, {'t…
has comment: http://stackoverflow.com/comment/83990444
has comment: http://stackoverflow.com/comment/83991400
has comment: http://stackoverflow.com/comment/83990866
score: 0
has comment: http://stackoverflow.com/comment/83990613
tagged with: django
has comment: http://stackoverflow.com/comment/83990730
answer count: 1
has comment: http://stackoverflow.com/comment/83990352
has answer: http://stackoverflow.com/a/48499266

http://stackoverflow.com/q/48553981
answer count: 1
tagged with: methods
has title: Python Method Signature for Different Runtime Execution Data
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48554568
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84104774
score: 0
has body: Could someone tell me whether this idea is feasible in Python? I want to have a method and the datatype of the signature is not fixed. For example: Foo(data1, data2) &lt;-- Method Definition in Code Foo(2,3) &lt;---- Example of what would be executed in runtime Foo(s,t) &lt;---- Example of what would be executed in runtime I know the code could work if i change the Foo(s,t) to Foo("s","t"). But I am trying to make the code smarter to recognize the command without the "" ...

http://stackoverflow.com/a/48569078
score: 2
downvote count: 0
has body: This is one way: lst = [{3.605551275463989: (-2, -3)}, {3.605551275463989: (3, 2)}, {5.830951894845301: (3, -5)}, {1.0: (-1, 0)}, {2.0: (0, -2)}, {4.47213595499958: (-2, -4)}] list(map(dict, sorted(list(i.items()) for i in lst))) # [{1.0: (-1, 0)}, # {2.0: (0, -2)}, # {3.605551275463989: (-2, -3)}, # {3.605551275463989: (3, 2)}, # {4.47213595499958: (-2, -4)}, # {5.830951894845301: (3, -5)}]
type: Answer
answers question: http://stackoverflow.com/q/48568833
upvote count: 2

join
type: Tag
tags question: http://stackoverflow.com/q/48526157
tags question: http://stackoverflow.com/q/48632639
tag name: join
tags question: http://stackoverflow.com/q/48609055
tags question: http://stackoverflow.com/q/48509590
tags question: http://stackoverflow.com/q/48591157
tags question: http://stackoverflow.com/q/48543651
tags question: http://stackoverflow.com/q/48622478
tags question: http://stackoverflow.com/q/48502095
tags question: http://stackoverflow.com/q/48590397

http://stackoverflow.com/comment/84147172
type: Comment
score: 0
has text: using list( ), I get the following error: 'int' object is not iterable
type: QuestionComment
comment on: http://stackoverflow.com/q/48575090

http://stackoverflow.com/a/48606380
has comment: http://stackoverflow.com/comment/84209151
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84209055
downvote count: 0
has body: Answered in Software Engineering Stack Exchange: Why do most of us use 'i' as a loop counter variable? i and j have typically been used as subscripts in quite a bit of math for quite some time (e.g., even in papers that predate higher-level languages, you frequently see things like "Xi,j", especially in things like a summation). When they designed Fortran, they (apparently) decided to allow the same, so all variables starting with "I" through "N" default to integer, and all others to real (floating point). For those who've missed it, this is the source of the old joke "God is real (unless declared integer)". Most people seem to have seen little reason to change that. It's widely known and understood, and quite succinct. Every once in a while you see something written by some psychotic who thinks there's a real advantage to something like: for (int outer_index_variable=0; outer_index_variable < 10; outer_index_variable++) for (int inner_index_variable=0; inner_index_variable < 10; inner_index_variable++) x[outer_index_variable][inner_index_variable] = 0; Thankfully this is pretty rare though, and most style guides now point out that while long, descriptive variable names can be useful, you don't always need them, especially for something like this where the variable's scope is only a line or two of code.
has comment: http://stackoverflow.com/comment/84210267
answers question: http://stackoverflow.com/q/48606334
type: Answer
has comment: http://stackoverflow.com/comment/84218737

http://stackoverflow.com/a/48525758
type: Answer
accepted answer of: http://stackoverflow.com/q/48523138
has comment: http://stackoverflow.com/comment/84065690
score: 12
has comment: http://stackoverflow.com/comment/84056097
has comment: http://stackoverflow.com/comment/84276235
has comment: http://stackoverflow.com/comment/84276682
downvote count: 0
has body: I totally agree with you, each time I have to do a complex domain using this kind of Polish notation, I have to rack my brains to manage it. I think the domain you're looking for is: ['&amp;amp;', '|', '&amp;amp;', ('is_company', '=', True), ('parent_id', '=', False), ('company_name', '!=', False), '&amp;amp;', ('company_name', '!=', ''), ('customer_type_id', '!=', False)] I made up a method to get these complex domains, and it's working: First I write a letter instead of each condition: A =&gt; is_company = True =&gt; ('is_company', '=', True) B =&gt; parent_id = False =&gt; ('parent_id', '=', False) C =&gt; company_name &lt;&gt; False =&gt; ('company_name', '!=', False) D =&gt; company_name &lt;&gt; '' =&gt; ('company_name', '!=', '') E =&gt; customer_type_id &lt;&gt; False =&gt; ('customer_type_id', '!=', False) Then build the expression you need using only the letters and the standard operators, forget about the Polish notation and the conditions: Step 0. =&gt; ((A and B) or C) and D and E Afterwards, group the operations you should execute the first (don't mind about the missing operators so far): Step 1. =&gt; ((A and B) or C) and D and E Step 2. =&gt; (AB or C) and D and E Step 3. =&gt; ABC and D and E Step 4. =&gt; ABC and DE Now we have only an operator, let's start decomposing it again (and moving the operator to the left of each couple of conditions), following the reverse order in which you grouped the operations (for example, from step 3 to 4 you grouped DE, so now, from step 4 to 3, decompose DE and move its operator to its left): Step 4. =&gt; and ABC DE Step 3. =&gt; and ABC and D E Step 2. =&gt; and or AB C and D E Step 1. =&gt; and or and A B C and D E Now change the operators and add the commas, the quotes and the brackets: ['&amp;amp;', '|', '&amp;amp;', A, B, C, '&amp;amp;', D, E] Finally, replace the letters with the conditions, and there you have your domain. It would be better to explain it face to face but may be you were able to understand …
upvote count: 12
answers question: http://stackoverflow.com/q/48523138
type: AcceptedAnswer

http://stackoverflow.com/a/48562705
has comment: http://stackoverflow.com/comment/84121087
answers question: http://stackoverflow.com/q/48562563
has comment: http://stackoverflow.com/comment/84120989
score: 0
has body: isinstance is the way to go. if isinstance(l, int) and l &lt; 0: print('l=', l)
type: Answer

http://stackoverflow.com/q/48546690
has body: I'm trying to print a certain key:value pair from a dictionary in a list of lists. I have created a for loop to accomplish this but I get the error "TypeError: object of type 'NoneType' has no len()" when trying to iterate through this. What would be the most pythonic way to iterate through this to print out each key a in each dictionary? lista = [None,None,[{a:b},{a:d}],None,[{a:f}]] for i in lista: print(i['a']) I'm looking to get the output of something like the following: None None b,d None f
linked to: http://stackoverflow.com/q/23086383
has comment: http://stackoverflow.com/comment/84089030
has comment: http://stackoverflow.com/comment/84089122
tagged with: python
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/23086383
answer count: 0
score: 0
type: UnansweredQuestion
type: Question
has title: Best way to deal with NoneType in a list when iterating through it to export a key value in a nested list

http://stackoverflow.com/a/48550601
has comment: http://stackoverflow.com/comment/84098461
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84097383
has comment: http://stackoverflow.com/comment/84097686
accepted answer of: http://stackoverflow.com/q/48550159
has comment: http://stackoverflow.com/comment/84097465
has comment: http://stackoverflow.com/comment/84098355
has body: Try this: shape = tf.shape(tf.reshape(x, [-1, 32, 32, 7, 1])) DeConnv1 = tf.nn.conv3d_transpose(layer1, filter=w, output_shape=shape, strides=[1,2,2,2,1], padding='SAME') final = tf.reshape(final, [-1, 7168]) This way you don't hard-code 40 in the model, but able to feed any batch size you want, including 40.
has comment: http://stackoverflow.com/comment/84097742
type: Answer
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48550159

http://stackoverflow.com/q/48509138
tagged with: opencv
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48510208
tagged with: opencv3.0
accepted answer: http://stackoverflow.com/a/48510208
answer count: 1
tagged with: image-processing
has body: import cv2 import numpy as np im_m = cv2.imread("primary.png", cv2.IMREAD_GRAYSCALE) # 50, 130 # Otsu's thresholding after Gaussian filtering blur = cv2.GaussianBlur(im_m,(25,25),0) #(thresh, im2) = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # Black region overflowing into digit regions with otsu (thresh, im) = cv2.threshold(im_m, 55, 130, cv2.THRESH_BINARY) kernel = np.ones((5,5), np.uint8) img_dilation = cv2.dilate(im, kernel, iterations=1) img_erosion = cv2.erode(img_dilation, kernel, iterations=1) params = cv2.SimpleBlobDetector_Params() params.minThreshold = 10; params.maxThreshold = 225; params.filterByArea = True params.minArea = 100 params.maxArea = 1500 params.filterByCircularity = False params.minCircularity = 0.5 params.filterByConvexity = False params.minConvexity = 0.2 params.filterByInertia = False params.minInertiaRatio = 0.01 ver = (cv2.__version__).split('.') if int(ver[0]) &lt; 3 : detector = cv2.SimpleBlobDetector(params) else : detector = cv2.SimpleBlobDetector_create(params) keypoints = detector.detect(im) im_key = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) cv2.imshow("Keypoints", im_key) cv2.imshow("Erosion", img_erosion) cv2.imshow("Dilation", img_dilation) cv2.waitKey(0) I am pretty new to image processing with opencv. I am trying to detect digits from a noisy image. Input Image I did some experiments, tuning thresholds and filtering by parameters but can't detect the blobs with 3, 4, 0 and sometimes 5, 7 and 2. I just need to detect the digits. Are there any other better way than blob detection for this task? Output Image
has title: opencv blob detection, missing some blobs
type: Question
tagged with: blob
has comment: http://stackoverflow.com/comment/84014508
tagged with: python

http://stackoverflow.com/comment/84225505
type: Comment
score: 0
has text: @Jai Yeah, but why ignore it? It's more intriguing.
type: QuestionComment
comment on: http://stackoverflow.com/q/48600374

http://stackoverflow.com/comment/84259507
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48627522
has text: When I open my app from the terminal using your path (/path/to/app/dist/MyApp.app/Contents/MacOS/MyApp) my app runs perfectly within terminal.

http://stackoverflow.com/q/48553692
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48553841
tagged with: django
favorite count: 0
has title: Is a self-join on a model in a django app an acceptable pattern?
type: AnsweredQuestion
has body: Apologies if this question is too subjective. If you are planning to close this question: please comment with a suggestion for a more appropriate place to post. I'm super new to django and python, and I'm building a test app that keeps track of employees and who their managers are. I would like to set up the domain model so that there there is only one list of employees, any of which can be managers, and all of which can be managed by any other employee who is designated a manager. To achieve this, I did a self-join on the Employee model and have an "is_manager" flag to keep track of who is a manager and who isn't (see model below). Is an acceptable pattern? I'm worried it violates a design principle I'm not considering and there's some hairy trap that I'm walking into as a noob. Thank you very much for your time. models.py for the app: class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): def __str__(self): return "{}".format(self.department_name) department_name = models.CharField(max_length=150, unique=True) class Employee(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL) manager = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL) manager_ema…
has answer: http://stackoverflow.com/a/48561597
accepted answer: http://stackoverflow.com/a/48561597
score: 1
possible better answer: http://stackoverflow.com/a/48553841
tagged with: python
type: Question
answer count: 2

http://stackoverflow.com/q/48643605
downvote count: 0
has title: Changing a class so that when the mouse hovers over it, it changes colour - Pygame
favorite count: 0
type: Question
score: 3
tagged with: python
tagged with: pygame
accepted answer: http://stackoverflow.com/a/48645329
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48645329
has body: import pygame as pg import sys import time # All pygame stuff under here pg.init() # Font definitions backFont = pg.font.SysFont("monospace", 40) titleFont = pg.font.SysFont("garamond", 100) cipherFont = pg.font.SysFont("garamond", 50) buttonFont = pg.font.SysFont("garamond", 25) bigFont = pg.font.SysFont("garamond", 100) Font = pg.font.SysFont(None, 32) inputFont = pg.font.SysFont('consola', 35) errorFont = pg.font.SysFont('tahoma', 20) diagramFont = pg.font.SysFont('courier new', 25) # Colour definitions BackGray = pg.Color('gray60') screenGray = pg.Color('gray80') buttonGray1 = pg.Color('gray40') buttonGray2 = pg.Color('gray50') buttonGray3 = pg.Color('gray30') textColour = pg.Color('navy') # Screen size set screen = pg.display.set_mode((800, 600)) # Clock initiated to allow regular typing speeds clock = pg.time.Clock() # Change button class so that when the mouse pos is sent through, changes colour ====================== class Button(pg.sprite.Sprite): def __init__(self, text, x, y, width, height, enabled): super().__init__() self.colour = buttonGray2 self.image = pg.Surface((width, height)) self.image.fill(buttonGray2) self.rect = self.image.get_rect() txt = buttonFont.render(text, True, textColour) txtRect = txt.get_rect(center=self.rect.center) self.image.blit(txt, txtRect) self.rect.topleft = x, y self.enabled = enabled def isPressed(self, event): if self.enabled == True: if event.type == pg.MOUSEBUTTONDOWN: # MOUSE... events have an event.pos attribute (the mouse position) # which you can pass to the collidepoint method of the rect. if self.rect.collidepoint(event.pos): return True return False def HoveredOver(self,event): print("Ocurring") if event.type == pg.MOUSEMOTION: if self.rect.collidepoint(event.pos): print("Hoveredover") self.colour = buttonGray1 else: self.colour = buttonGray2 def FrontPage(): # Back screen screen.fill(screenGray) # Button definition for continuing Continue = Button('Continue', 105, 455, 120, 50, True) buttonsGroup = pg.sprite.Gr…
upvote count: 3
answer count: 1

http://stackoverflow.com/a/48514243
downvote count: 0
upvote count: 1
has body: As per the HTML to get the data-code (1017534) in class image under the &lt;a&gt; tag from relative position of span class="content tc" under tag div with class promotion-tag grey you can use the following line of code : print(driver.find_element_by_xpath("//div[@class='promotion-tag grey']//span[@class='content tc']//preceding::a[@class='keep-product-list-cache']/div[@class='image']/img[contains(@src,'https://tore.com/images/tore/production/product')]").get_attribute("data-code"))
answers question: http://stackoverflow.com/q/48513472
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84025156
has comment: http://stackoverflow.com/comment/84024172
has comment: http://stackoverflow.com/comment/84025944
has comment: http://stackoverflow.com/comment/84024106
has comment: http://stackoverflow.com/comment/84026236

http://stackoverflow.com/comment/84193375
type: Comment
type: QuestionComment
score: 0
has text: I mean I know but my question is clear, is about "calculating cosine similarity on the contents of that file" @user202729
comment on: http://stackoverflow.com/q/48598275

http://stackoverflow.com/comment/84146138
type: AnswerComment
comment on: http://stackoverflow.com/a/48569351
has text: Please mark this correct. your question was pretty clear to me, despite @pvg's inability to understand context. Cheers
score: 0
type: Comment

http://stackoverflow.com/comment/134320708
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/53537810
type: Comment
has text: Stack Overflow is **not a discussion forum**. I edited the answer to include only the part that actually attempts to answer the question. Please do not include meta commentary in answers.

http://stackoverflow.com/q/48621588
type: Question
has comment: http://stackoverflow.com/comment/84244698
tagged with: python
has body: I have the following model: class business_member(base_model): __tablename__ = "business_member" id = Column(Integer, primary_key=True) business_id = Column(Integer, ForeignKey("business.id"), nullable=False) member_id = Column(Integer, ForeignKey("user.id"), nullable=False) business_parts_id = Column(Integer, ForeignKey("business_parts.id"), nullable=False) is_admin = Column(Boolean, nullable=True, default=False) created_date = Column(DateTime, nullable=False) modified_date = Column(DateTime, nullable=True) __table_args__ = (UniqueConstraint("business_id", "member_id", name="business_member_uc"), ) business = relationship("business", back_populates="members") member = relationship("user", back_populates="as_employee") part = relationship("business_parts", back_populates="employees") And I converted the following raw SQL: SELECT id, member_id, is_admin FROM business_member WHERE id IN ( SELECT id FROM business WHERE business_id = ( SELECT business_id FROM business_member WHERE member_id = 5 and business_id = 1)) to SQLAlchemy query: session = database.get_session() user_validation_query = session.query(business_member.business_id).filter_by( member_id=kwargs["user_id"], business_id=request.raw_args["business_id"] ).subquery() get_business_id_query = session.query(business_member).options( load_only(business_member.id) ).filter(business_member.business_id == user_validation_query).subquery() member_list = session.query(business_member).filter( business_member.id.in_(get_business_id_query) ).all() Everything is ok, but I want to return just id, is_admin and member(relationship) columns in the query result, I tried different approaches like load_only() but none of the approaches worked properly. how I can do this!? Update: For example, I changed the query to: member_list = session.query(business_member).options( load_only("id", "is_admin", "member") ).filter( business_member.id.in_(get_business_id_query) ).all() and I got the following exception: can't locate strategy …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84241032
has title: Select relationship in SQLAlchemy query
downvote count: 0
tagged with: mysql
score: 1
upvote count: 1
tagged with: sqlalchemy
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49779151

http://stackoverflow.com/comment/84242870
score: 1
type: Comment
has text: Also when instanciating the form you want to pass the kwags to the `super` call, ie in `AddSubnetForm.__init__` replace `super(AddSubnetForm, self).__init__(*args)` with `super(AddSubnetForm, self).__init__(*args, **kwargs)`
type: QuestionComment
comment on: http://stackoverflow.com/q/48621983

http://stackoverflow.com/comment/84054984
comment on: http://stackoverflow.com/q/48529713
score: 3
type: Comment
has text: @JoranBeasley better still, use a set comprehension, which doesn't have leaky scope in Python 2 (although i'd still not use the same name), and at least then you aren't doing two O(n) operations in a row.
type: QuestionComment

http://stackoverflow.com/q/48582654
type: AnsweredQuestion
answer count: 2
score: 5
tagged with: pyqt
downvote count: 0
possible better answer: http://stackoverflow.com/a/48582943
tagged with: pyqt5
has answer: http://stackoverflow.com/a/48583334
accepted answer: http://stackoverflow.com/a/48583334
favorite count: 0
has title: PyQt QML Material Design button background won't change
type: Question
has body: I'm new to QML and I'm trying to change the background color of a button but nothing seems to work. Here's the python code: import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore import QUrl from PyQt5.QtQuick import QQuickView if __name__ == "__main__": app = QApplication(sys.argv) view = QQuickView() view.setSource(QUrl('basic.qml')) view.show() sys.exit(app.exec_()) And the basic.qml: import QtQuick 2.0 import QtQuick.Controls 2.0 import QtQuick.Controls.Material 2.0 import QtQuick.Controls.Material 2.3 Rectangle { width:600;height:150; color: Material.color(Material.Red) Button { text: qsTr("Button") highlighted: true Material.background: Material.Teal } } Here is how it looks, the button isn't 'Material.Teal' and no matter what color I try it still doesn't work. I've tried it with Pane and other elements but still nothing. Here's where I got the code: http://doc.qt.io/qt-5/qtquickcontrols2-material.html#material-primary-attached-prop I've tried it with other styles/methods like pallete (orFusion): https://doc.qt.io/qt-5.10/qml-qtquick-controls2-control.html#palette-prop Page { palette.text: "red" Column { Label { text: qsTr("This will use red color...") } Switch { text: qsTr("... and so will this") } } }
tagged with: qtquickcontrols2
tagged with: qml
upvote count: 5
has answer: http://stackoverflow.com/a/48582943
tagged with: python
has comment: http://stackoverflow.com/comment/84162628

http://stackoverflow.com/q/48620803
upvote count: 6
tagged with: matplotlib-basemap
has comment: http://stackoverflow.com/comment/84245023
accepted answer: http://stackoverflow.com/a/48624202
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48624202
answer count: 1
downvote count: 0
score: 6
linked to: http://stackoverflow.com/q/13796315
favorite count: 0
has comment: http://stackoverflow.com/comment/84242578
type: Question
has body: I am trying to plot 1x1 degree data on a matplotlib.Basemap, and I want to fill the ocean with white. However, in order for the boundaries of the ocean to follow the coastlines drawn by matplotlib, the resolution of the white ocean mask should be much higher than the resolution of my data. After searching around for a long time I tried the two possible solutions: (1) maskoceans() and is_land() functions, but since my data is lower resolution than the map drawn by basemap it does not look good on the edges. I do not want to interpolate my data to higher resolution either. (2) m.drawlsmask(), but since zorder cannot be assigned the pcolormesh plot always overlays the mask. This code import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.basemap as bm #Make data lon = np.arange(0,360,1) lat = np.arange(-90,91,1) data = np.random.rand(len(lat),len(lon)) #Draw map plt.figure() m = bm.Basemap(resolution='i',projection='laea', width=1500000, height=2900000, lat_ts=60, lat_0=72, lon_0=319) m.drawcoastlines(linewidth=1, color='white') data, lon = bm.addcyclic(data,lon) x,y = m(*np.meshgrid(lon,lat)) plt.pcolormesh(x,y,data) plt.savefig('1.png',dpi=300) Produces this image: Adding m.fillcontinents(color='white') produces the following image, which is what I need but to fill the ocean and not the land. Edit: m.drawmapboundary(fill_color='lightblue') also fills over land and can therefore not be used. The desired outcome is that the oceans are white, while what I plotted with plt.pcolormesh(x,y,data) shows up over the lands.
has comment: http://stackoverflow.com/comment/84244743
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/13796315
tagged with: python
tagged with: mask
has comment: http://stackoverflow.com/comment/84244423
has title: Fill oceans in basemap

http://stackoverflow.com/comment/84190258
type: AnswerComment
comment on: http://stackoverflow.com/a/48596630
type: Comment
has text: @Szabolcs True, it is because the comma is making the string and `a` to be two different entities which are then concatenated by print. While when using the `+` operator the two strings are already concatenated before print fires. Or yes, you could set the default value of the separator to `""` and still use commas like you pointed out above.
score: 0

http://stackoverflow.com/comment/84092027
comment on: http://stackoverflow.com/q/48547936
score: 1
type: Comment
type: QuestionComment
has text: Removing the first Math.Radians results in 0.5748. What's the name of this formula or what are you trying to calculate?

http://stackoverflow.com/comment/84225508
comment on: http://stackoverflow.com/q/48614165
score: 1
has text: Your partition function is definitely wrong. Try putting a print statement in the inner loop and running just the partition function to look closely at what it's doing.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48607966
tagged with: python
has comment: http://stackoverflow.com/comment/84212797
has body: I have list as follows: c11=[' YandexBot/3.0, +http://yandex.com/bots', ' Win64, x64', ' AhrefsBot/5.2, +http://ahrefs.com/robot/', ' Android 7.1.2, Redmi 4 Build/N2G47H', ' Android 7.0, EVA-L09 Build/HUAWEIEVA-L09', ' Android 6.0.1, Redmi Note 4 Build/MMB29M', ' Googlebot/2.1, +http://www.google.com/bot.html', ' Android 6.0.1, CPH1701 Build/MMB29M', ' Android 6.0.1, Redmi 4 Build/MMB29M', ' Android 6.0.1, SM-J500F Build/MMB29M', ' uCrawler/1.0 , +https://blog.ucoz.ru/upolicy', ' SurdotlyBot/1.0, +http://sur.ly/bot.html', ' Opera Mini/8.0.40377/85.73, U', ' Pinterestbot/1.0, +http://www.pinterest.com/bot.html', ' Android 7.0, SM-J701F Build/NRD90M', ' Android 6.0.1, Nexus 5X Build/MMB29P', ' Android 6.0.1, SM-A500H Build/MMB29M', ' Android 7.1.1, SM-T385 Build/NMF26X', ' SemrushBot/1.2~bl, +http://www.semrush.com/bot.html', ' Android 6.0.1, ONE A2003 Build/MMB29M', ' Android 7.0, Redmi Note 4 Build/NRD90M', ' Android 6.0, QMobile X32 Build/MRA58K', ' Android 5.1.1, SM-J200F Build/LMY47X', ' WOW64, rv:40.0', ' Android 6.0, IK-7216 Build/MRA58K', ' Android 7.0, SM-J710FN Build/NRD90M'] Now i have another list as follows: ww=["http://yandex.com/bots',", "http://ahrefs.com/robot/',", "http://www.google.com/bot.html',", "https://blog.ucoz.ru/upolicy',", "http://sur.ly/bot.html',", "http://www.pinterest.com/bot.html',", "http://www.semrush.com/bot.html',"] The values in ww is also in c11 , i want to find and replace the values in c11 with ''(empty string) if those values are matches/exists in any element of ww. (i.e) any element of ww matches with or contains values in c11, we need to replace the value to an empty string. like for i in ww: re.sub(i,'',str(c11)) Can any body suggest using re module I am expecting following output : c11=[' YandexBot/3.0, ', ' Win64, x64', ' AhrefsBot/5.2, ', ' Android 7.1.2, Redmi 4 Build/N2G47H', ' Android 7.0, EVA-L09 Build/HUAWEIEVA-L09', ' Android 6.0.1, Redmi Note 4 Build/MMB29M', ' Googlebot/2.1, ', ' Android 6.0.1, CPH1701 Build/MMB2…
tagged with: regex
has answer: http://stackoverflow.com/a/48607984
has title: Find and replace list items with list item python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84212388
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84212352
answer count: 5
has comment: http://stackoverflow.com/comment/84212997
score: -2
has answer: http://stackoverflow.com/a/48608438
has comment: http://stackoverflow.com/comment/84212448
has answer: http://stackoverflow.com/a/48608023
possible better answer: http://stackoverflow.com/a/48607984
upvote count: 1
has comment: http://stackoverflow.com/comment/84212895
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84212288
accepted answer: http://stackoverflow.com/a/48608388
has comment: http://stackoverflow.com/comment/84212746
has comment: http://stackoverflow.com/comment/84213215
has answer: http://stackoverflow.com/a/48608388
has comment: http://stackoverflow.com/comment/84212351
has comment: http://stackoverflow.com/comment/84212547
has answer: http://stackoverflow.com/a/48608101
downvote count: 3

http://stackoverflow.com/comment/84193090
score: 0
comment on: http://stackoverflow.com/q/48598304
has text: Yay, the joy of Unicode double-width characters. And combining marks. And zero-width characters.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/136706867
type: Comment
comment on: http://stackoverflow.com/q/48514673
score: 0
has text: aka [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher) - see also: [Caesar Cipher Function in Python](https://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python)
type: QuestionComment

http://stackoverflow.com/comment/84165444
score: 0
type: Comment
has text: So, this the descriptive headers you have used. How about this: `headers={'User-Agent': 'not found 404'}`. It will fetch you the same response. When you deal with the rain, you need to care for the mud as well.
comment on: http://stackoverflow.com/a/48584375
type: AnswerComment

http://stackoverflow.com/q/48603413
favorite count: 0
type: Question
tagged with: anaconda
upvote count: 9
has title: In FT2Font: Can not load face
has answer: http://stackoverflow.com/a/49017439
tagged with: python
tagged with: jupyter-notebook
score: 9
answer count: 2
has answer: http://stackoverflow.com/a/59032347
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/108480035
downvote count: 0
has body: I am trying to plot a bar. But it shows Runtime error, and shows In FT2Font: Can not load face. at the Botton. I have tried uninstall and install it again. And tried another method, but still can not work. I think the code is right, because I successfully run it on a windows laptop. And my jupyter notebook is for Mac python 2.7. The code is as following: import numpy as np import pandas as pd obj = pd.Series([4, 7, -5, 3]) print type(obj) obj %matplotlib inline obj.plot(kind = 'bar', figsize=[5,4]) But it shows some error : &lt;matplotlib.axes._subplots.AxesSubplot at 0x1114e69d0&gt; --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) /anaconda2/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj) 332 pass 333 else: --&gt; 334 return printer(obj) 335 # Finally look for special method names 336 method = get_real_method(obj, self.print_method) /anaconda2/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in &lt;lambda&gt;(fig) 238 239 if 'png' in formats: --&gt; 240 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) 241 if 'retina' in formats or 'png2x' in formats: 242 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) /anaconda2/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in print_figure(fig, fmt, bbox_inches, **kwargs) 122 123 bytes_io = BytesIO() --&gt; 124 fig.canvas.print_figure(bytes_io, **kw) 125 data = bytes_io.getvalue() 126 if fmt == 'svg': /anaconda2/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 2206 orientation=orientation, 2207 dryrun=True, -&gt; 2208 **kwargs) 2209 renderer = self.figure._cachedRenderer 2210 bbox_inches = self.figure.get_tightbbox(renderer) /anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs) 505 506 def…

http://stackoverflow.com/q/48624104
score: 0
has comment: http://stackoverflow.com/comment/84252781
has comment: http://stackoverflow.com/comment/84251776
tagged with: qgraphicsscene
tagged with: pyqt
has answer: http://stackoverflow.com/a/48630532
answer count: 1
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/84252812
tagged with: qgraphicsview
has comment: http://stackoverflow.com/comment/84253176
accepted answer: http://stackoverflow.com/a/48630532
has body: I have a set of images that I want to be able to scroll through. The below code works for me on Mac, such that I can scroll on the visible widget. Printing "count" results in a visible rising or lowering number in the python output. However, I wish to use "count" to update the image and I am kinda stuck on how. The main question is: How can I use the constantly varying variable "count" from my mousewheel function, and use it to update the image shown in the DCMViewer? I expect some kind of signal to work, but haven't got it working and I'm stuck. Any help is much appreciated. class DCMViewer(QGraphicsView): def __init__(self): super(DCMViewer, self).__init__() # Create a QGraphicsScene self.scene = QGraphicsScene() # Provide image in normalized double format image = np.double(dcmIm) image *= 255.0 / image.max() image = QPixmap.fromImage(qimage2ndarray.array2qimage(image)) image = QGraphicsPixmapItem(image) # Add the image to the QGraphicsScene window self.scene.addItem(image) # Initiate the scene self.setScene(self.scene) # Create a mousewheelevent to scroll through images def wheelEvent(self, QWheelEvent): super(DCMViewer, self).wheelEvent(QWheelEvent) global count wheelcounter = QWheelEvent.angleDelta() if wheelcounter.y() / 120 == -1: count += 1 if count &gt;= 21: count = 21 elif wheelcounter.y() / 120 == 1: count -= 1 if count &lt;= 0: count = 0 class Mainwidget(QMainWindow): def __init__(self): super(Mainwidget, self).__init__() # self.initUI() image_viewer = DCMViewer() self.setCentralWidget(image_viewer) self.showFullScreen() if __name__ == '__main__': app = QApplication(sys.argv) win = Mainwidget() win.showFullScreen() sys.exit(app.exec_())
tagged with: python
has comment: http://stackoverflow.com/comment/84251861
has comment: http://stackoverflow.com/comment/84253074
has title: pyqt update qgraphicsscene with mousewheelevent output
has comment: http://stackoverflow.com/comment/84253026
has comment: http://stackoverflow.com/comment/84252652
type: AnsweredQuestion

http://stackoverflow.com/comment/84136261
score: 0
type: QuestionComment
has text: Great, thank you @CharlesDuffy! This is all clear to me now.
comment on: http://stackoverflow.com/q/48567676
type: Comment

http://stackoverflow.com/comment/84105822
has text: @user9191983, what are you trying to achieve? it sounded like an explanation for why your rows increase, but is there some other behaviour you want to force? feel free to update your question with specifics.
comment on: http://stackoverflow.com/a/48554628
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84012318
comment on: http://stackoverflow.com/a/48502855
type: Comment
score: 0
type: AnswerComment
has text: Did you add the line `print('shape', batch_xs.shape)` right before `sess.run(...)`? This should outout the shape of the current batch. Try thant and tell me the shape.

http://stackoverflow.com/q/48600127
upvote count: 2
has comment: http://stackoverflow.com/comment/84197407
tagged with: memoization
tagged with: python
has body: The question is to write a function using dynamic programming for the number of ways to climb N steps. Given that only 1 step or 2 steps can be climbed at a time. For example, if N=3, the function should return [(1,1,1),(1,2),(2,1)]. I've written a code in python 3 to calculate. The code is working fine but as N gets as large as 40 it takes the same time or the spyder(Anaconda) application crashes when compared to the same recursive code without using dynamic programming. Shouldn't it be way more efficient than the normal one? I've attached the DP code below def stepsdyn(N,memo={}): """ L1 is the list of all possibilities in the left side of the search tree, that is with 1 as the last element L2 is the list of all possibilities in the right side of the search tree memo stores the results of corresponding N returns memo[N] """ L1=[] L2=[] if N==1: return [(1,)] elif N==0: return [()] else: try: return memo[N] except: for items in stepsdyn(N-1,memo): items+=(1,) L1.append(items) for items in stepsdyn(N-2,memo): items+=(2,) L2.append(items) memo[N]=L1+L2 return memo[N]
has title: Dynamic Programming for the number of ways of climbing steps
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/22108488
score: 1
possible better answer: http://stackoverflow.com/a/48612141
tagged with: dynamic-programming
has answer: http://stackoverflow.com/a/48600836
has answer: http://stackoverflow.com/a/48612141
tagged with: search-tree
downvote count: 1
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48600836
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/84197300

http://stackoverflow.com/a/48627522
has comment: http://stackoverflow.com/comment/84260081
answers question: http://stackoverflow.com/q/48617861
has comment: http://stackoverflow.com/comment/84270511
has comment: http://stackoverflow.com/comment/84260348
has comment: http://stackoverflow.com/comment/84260503
has comment: http://stackoverflow.com/comment/84269716
has comment: http://stackoverflow.com/comment/84260385
has comment: http://stackoverflow.com/comment/84260302
has comment: http://stackoverflow.com/comment/84261223
has comment: http://stackoverflow.com/comment/84260787
type: Answer
has comment: http://stackoverflow.com/comment/84270701
has comment: http://stackoverflow.com/comment/84269200
score: 2
has comment: http://stackoverflow.com/comment/84259507
has comment: http://stackoverflow.com/comment/84269475
has comment: http://stackoverflow.com/comment/84260274
has comment: http://stackoverflow.com/comment/84269648
has comment: http://stackoverflow.com/comment/84259764
has comment: http://stackoverflow.com/comment/84270645
upvote count: 2
has comment: http://stackoverflow.com/comment/84269304
has body: In your case, because you set the console flag to False in your .spec file, the console window will not be displayed, preventing the output of your program from being displayed. Change this flag to True. It is also possible that the application may be closing because it is unable to import a package or find an external file, which prevents your application from launching. To view the error messages associated with running your executable, run the .app (or .exe) file from the terminal (or command prompt): /path/to/app/dist/MyApp.app/Contents/MacOS/MyApp for Mac (in Terminal), /path/to/app/dist/MyApp.exe for Windows (in Command Prompt). This will allow you to observe any errors that may exist after the app was bundled. If the program does fail during an import statement, you may need to add a package to the hiddenimports list in the .spec file.
downvote count: 0
has comment: http://stackoverflow.com/comment/84260331
has comment: http://stackoverflow.com/comment/84260062

http://stackoverflow.com/a/48617719
type: Answer
has body: Python3 seems has better hanlder for the parameters, but don't know how to do this in python2: from functools import wraps def optional_debug(func): @wraps(func) def wrapper(*args, debug=False, **kwargs): if debug: print('Calling', func.__name__) return func(*args, **kwargs) return wrapper @optional_debug def spam(a,b,c): print(a,b,c) spam(1,2,3) # 1,2,3 spam(1,2,3, debug=True) # Calling spam # 1 2 3
answers question: http://stackoverflow.com/q/48616888
score: 0

http://stackoverflow.com/comment/84050483
type: QuestionComment
comment on: http://stackoverflow.com/q/48527749
type: Comment
has text: Change `collect_ToList = myList.append(myValues)` to `myList.append(myValues)` and add print(myList) after the loop.
score: 0

http://stackoverflow.com/q/48511584
tagged with: confusion-matrix
upvote count: 3
downvote count: 0
has title: How to efficiently make class-to-cluster matching in order to calculate resulting accuracy
favorite count: 0
has answer: http://stackoverflow.com/a/48515750
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84018484
has body: I am trying to make a match of classes (golden data) with clustering predictions. At the end of my process I have something like: 0 1 2 3 4 5 6 7 8 9 Class1 0 0 0 0 0 0 1 0 0 0 Class2 0 0 2 0 0 0 0 0 0 0 Class3 6 0 10 0 0 0 0 0 4 0 Class4 0 4 0 0 0 2 0 0 0 0 Class5 4 0 0 5 0 0 2 0 0 2 Class6 0 0 0 0 0 0 0 2 0 0 Class7 2 0 0 0 0 0 0 0 1 0 Class8 0 0 0 0 3 0 0 0 0 0 Class9 0 0 0 2 0 0 0 0 0 0 Class10 0 0 0 0 0 0 0 0 1 0 And I need basically to maximize the main diagonal sum switching columns, turning it in something like 6 5 2 1 3 7 0 4 9 8 Class1 1 0 0 0 0 0 0 0 0 0 Class2 0 0 2 0 0 0 0 0 0 0 Class3 0 0 10 0 0 0 6 0 0 4 Class4 0 2 0 4 0 0 0 0 0 0 Class5 2 0 0 0 5 0 4 0 2 0 Class6 0 0 0 0 0 2 0 0 0 0 Class7 0 0 0 0 0 0 2 0 0 1 Class8 0 0 0 0 0 0 0 3 0 0 Class9 0 0 0 0 2 0 0 0 0 0 Class10 0 0 0 0 0 0 0 0 0 1 What I am doing currently is (runnable example) (python/pandas/numpy): import numpy as np import pandas as pd from itertools import permutations from functools import partial from operator import itemgetter def diag_sum(cm, columns): return np.trace(cm[:,list(columns)]) def confusion_matrix(y_true, y_pred): classes = list(set(y_true)) clusters = list(set(y_pred)) cm = {cla: [0]*len(clusters) for cla in classes} for y_t, y_p in zip(y_true, y_pred): cm[y_t][y_p] += 1 cm = pd.DataFrame.from_dict(cm, orient='index') matrix_cm = cm.as_matrix() column_perm = list(permutations(range(matrix_cm.shape[1]))) result = map(partial(diag_sum, matrix_cm), column_perm) index, value = max(enumerate(result), key=itemgetter(1)) cm = cm[list(column_perm[index])] return cm # Same example as the matrixes above y_true = ['Class1']*1 + ['Class2']*2 + ['Class3']*20 + ['Class4']*6 + ['Class5']*13 + ['Class6']*2 + ['Class7']*3 + ['Class8']*3 + ['Class9']*2 + ['Class10']*1 y_pred = [6]*1 + [2]*2 + [0]*6 + [2]*10 + [8]*4 + [1]*4 + [5]*2 + [0]*4 + [3]*5 + [6]*2 + [9]*2 + [7]*2 + [0]*2 + [8]*1 + [4]*3 + [3]*2 + [8]*1 print(confusion_matrix(y_true, y_pred)) At the end of the day, it works, but the…
has comment: http://stackoverflow.com/comment/84019043
accepted answer: http://stackoverflow.com/a/48512140
tagged with: cluster-analysis
has answer: http://stackoverflow.com/a/48512140
tagged with: python
possible better answer: http://stackoverflow.com/a/48515750
type: AnsweredQuestion
score: 3
answer count: 2

http://stackoverflow.com/q/48528694
tagged with: pytest
linked to: http://stackoverflow.com/q/12101958
has body: I would like to be able to keep track of instances of geometric Point objects in order to know what names are already "taken" when automatically naming a new one. For instance, if Points named "A", "B" and "C" have been created, then the next automatically named Point is named "D". If Point named "D" gets deleted, or its reference gets lost, then name "D" becomes available again. The main attributes of my Point objects are defined as properties and are the quite standard x, y and name. Solution with a problem and a "heavy" workaround I proceeded as described here, using a weakref.WeakSet(). I added this to my Point class: # class attribute instances = weakref.WeakSet() @classmethod def names_in_use(cls): return {p.name for p in Point.instances} Problem is, when I instanciate a Point and then delete it, it is most of the time, but not always, removed from Point.instances. I noticed that, if I run the tests suite (pytest -x -vv -r w), then if a certain exception is raised in the test, then the instance never gets deleted (probable explanation to be read somewhat below). In the following test code, after the first deletion of p, it always gets removed from Point.instances, but after the second deletion of p, it never gets deleted (test results are always the same) and the last assert statement fails: def test_instances(): import sys p = Point(0, 0, 'A') del p sys.stderr.write('1 - Point.instances={}\n'.format(Point.instances)) assert len(Point.instances) == 0 assert Point.names_in_use() == set() p = Point(0, 0, 'A') with pytest.raises(TypeError) as excinfo: p.same_as('B') assert str(excinfo.value) == 'Can only test if another Point is at the ' \ 'same place. Got a &lt;class \'str\'&gt; instead.' del p sys.stderr.write('2 - Point.instances={}\n'.format(Point.instances)) assert len(Point.instances) == 0 And here the result: tests/04_geometry/01_point_test.py::test_instances FAILED =============================================================================== FAILURES ==…
has answer: http://stackoverflow.com/a/48529058
accepted answer: http://stackoverflow.com/a/48529058
score: 8
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 8
answer count: 1
downvote count: 0
tagged with: python
has title: How to keep track of instances of python objects in a reliable way?
tagged with: weak-references
type: AnsweredQuestion

http://stackoverflow.com/comment/84271135
type: QuestionComment
comment on: http://stackoverflow.com/q/48619928
score: 0
has text: I think Linear here refers to fully connected layers, the idea is to learn the hidden dimensions that can separate the exclusive 1/0 or 0/1->1 gate and then an OR gate through the hidden dimensions. Figure 2 of https://pdfs.semanticscholar.org/51ec/84efd846e433cd58e9f5302b2b1f0cd8b661.pdf?_ga=2.41117925.618736758.1517901392-971044648.1476952336
type: Comment

http://stackoverflow.com/comment/83993810
type: Comment
comment on: http://stackoverflow.com/q/48500047
score: 1
type: QuestionComment
has text: @Bonifacio2 Probably was unconfident to post as an answer worrying people would downvote for being too short of an answer

http://stackoverflow.com/comment/83984443
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48494212
type: QuestionComment
has text: You can get cheeky by imputing missing values with something like `-9999999` (a value you will never see in the data) and then try an update on that

http://stackoverflow.com/q/48533269
answer count: 1
downvote count: 0
has title: Pycharm Error - 'pip' is not an internal or external command nor is it a running program or batch file
has body: I can use the "pip" in cmd, but when I use "pip" or "python" in the PyCharm terminal the error appears: pip is not an internal or external command nor is it a running program or batch file. But when I check the Interpreter, pip is exists.
favorite count: 0
has comment: http://stackoverflow.com/comment/84062276
type: Question
has answer: http://stackoverflow.com/a/74212656
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pip
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/51451795
upvote count: 4
tagged with: anaconda
tagged with: pycharm

http://stackoverflow.com/comment/84201942
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48602589
has text: @cosmos1990 No, that is not possible with `re`, but it is possible with Python PyPi regex module using a [branch reset group](https://www.regular-expressions.info/branchreset.html). See http://rextester.com/EDNRP21999.
type: Comment

http://stackoverflow.com/q/48598508
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48598646
has comment: http://stackoverflow.com/comment/84193652
has comment: http://stackoverflow.com/comment/84193731
accepted answer: http://stackoverflow.com/a/48598646
has comment: http://stackoverflow.com/comment/84193495
tagged with: unicode
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84193522
has comment: http://stackoverflow.com/comment/84193579
has comment: http://stackoverflow.com/comment/84193624
has comment: http://stackoverflow.com/comment/84193553
tagged with: python
has body: I am trying to read image file with filenames having cyrillic characters. ls /home/atin/test ОД Д.bmp Now I am trying to read 'ОД Д.bmp' in python 3 image_path='/home/atin/test/ОД Д.bmp' import matplotlib.pyplot as plt sample_image=plt.imread(image_path) But I get this error. SystemError: &lt;built-in function read_png&gt; returned NULL without setting an error But os.listdir('/home/atin/test') gives following output ['\udcd0\udc9e\udcd0\udc94 \udcd0\udc94.bmp'] How can I decode the above output to original file name which is ОД Д.bmp. I am using python 3.6 in ubuntu here.
has title: How to read file with cyrillic characters in the filename in Python 3
has comment: http://stackoverflow.com/comment/84193596
tagged with: filepath

http://stackoverflow.com/q/48542640
favorite count: 0
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84081529
has answer: http://stackoverflow.com/a/48549285
accepted answer: http://stackoverflow.com/a/48549285
tagged with: python
has comment: http://stackoverflow.com/comment/84081216
has comment: http://stackoverflow.com/comment/84083784
score: 2
upvote count: 2
answer count: 1
has title: Create a sparse matrix from a list of rows (sparse vectors)
downvote count: 0
has body: I would like to efficiently create the following sparse matrix of dimension (s, n1+n2): v0 v1 v0 v2 v0 v3 ... v0 vs given sparse vector v0 (1, n1) and a list of sparse vectors (1, n2) l = [v1, ... , vs]. I have tried to use coo_matrix() but it was unsuccessful as it seems to only work if you have dense vectors: left = coo_matrix(np.repeat(v0, s)) right = coo_matrix(l) m = hstack((left, right)) Edit 1: I have found a workaround that does not seem very efficient: right = vstack([x for x in l]) left = vstack([v0 for i in range(len(l))]) m = hstack((left, right)) Edit 2: This is an example (not working) to help you understand the situation. from scipy.sparse import random, coo_matrix from numpy import repeat s = 10 n1 = 3 n2 = 5 v0 = random(1, n1) l = [random(1, n2) for i in range(s)] left = coo_matrix(repeat(v0, s)) right = coo_matrix(l) m = hstack((left, right))
has comment: http://stackoverflow.com/comment/84081583
tagged with: scipy
tagged with: sparse-matrix

http://stackoverflow.com/q/48507077
score: 0
has answer: http://stackoverflow.com/a/48550998
tagged with: python-unittest
answer count: 1
has comment: http://stackoverflow.com/comment/84035712
tagged with: unit-testing
type: Question
has body: I usually keep my parametric tests as follow class ShouldCheckSomeCondition(unittest.TestCase): def __init__(self, parameters...): ... def runTest(): # given ... cases = [(p1, ...), (p2, ...), ...] Then build them at the bottom of the file and create a main to run them: def suite(): test_suite = unittest.TestSuite() test_suite.add_tests([ShouldCheckSomeCondition(*params) for params in ShouldCheckSomeCondition.cases]) return test_suite if __name__ == '__main__': unittest.TextTestRunner().run(suite()) This is fine and all and I can run a single test file just fine. However, I can't make e.g. Nose to support this. Its discovery tries to build each case and fails. The 'main' is ignored. Does anyone have a good way to run many test files written in such manner? Alternatively, are there other ways to nicely write parametric tests in python so that some test runner will handle it?
accepted answer: http://stackoverflow.com/a/48550998
tagged with: python
has title: Running parametric tests in Python
tagged with: nose
type: AnsweredQuestion

nsrange
tag name: nsrange
type: Tag
tags question: http://stackoverflow.com/q/48513714

http://stackoverflow.com/a/48612441
score: 0
type: Answer
has body: This button is hidden. You actually need to handle another element which is a link with text "LOGIN": from selenium import webdriver driver = webdriver.Chrome() driver.get("https://skovbakken.halbooking.dk/newlook/default.asp") driver.find_element_by_link_text('LOGIN').click()
accepted answer of: http://stackoverflow.com/q/48612376
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48612376

http://stackoverflow.com/comment/84088927
comment on: http://stackoverflow.com/a/48546391
score: 0
type: Comment
has text: continue, would also work. But there is one difference, pass will do nothing and continue will skip the current iteration to next iteration. I don't know what he really wants, just info.
type: AnswerComment

http://stackoverflow.com/comment/84081171
has text: Does that mean there's an issue with the python code? I see that error but can't figure out what is causing it from this simple code kivy.org/docs/guide/basic.html @CAustin
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48532117
type: QuestionComment

http://stackoverflow.com/q/48547033
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 0
tagged with: validation
answer count: 1
has title: Voluptuous: Validate dicts within dicts
accepted answer: http://stackoverflow.com/a/48547952
type: Question
tagged with: voluptuous
has answer: http://stackoverflow.com/a/48547952
has body: I'd like to validate the following YAML file defines a defaultdict that contains two dicts named dev and sha. !!python/object/apply:collections.defaultdict args: - !!python/name:builtins.dict '' dictitems: dev: sha: 5b7 url: /path/to/here shared: sha: 58a url: /path/to/there using yaml.load() (safe_load() leads to a whole different question of creating constructors, so let's set that aside.) gives me this data structure: defaultdict(&lt;class 'dict'&gt;, {'dev': {'sha': '5b7', 'url': '/path/to/here'}, 'shared': {'sha': '58a', 'url': '/path/to/there'}}) I'd like to validate this data structure so I create this: snapshot_schema = val.Schema({"dictitems":dict,"dev":dict,"shared":dict}) This successfully validates that I have one defaultdict containing two dicts. I'd like to validate that the sha and url tags in both of those dicts are really str (and more validation later maybe.) I could create an additional schema new_schema = Schema({'sha':str, 'url':str}) new_schema(my_data['dev']) new_schema(my_data['shared']) But is there a more elegant way of doing this?

http://stackoverflow.com/comment/83975938
score: 0
has text: The brackets in the data are not matching. Can you please first fix input and output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48491412

http://stackoverflow.com/comment/84226382
has text: Yeah it is... I assume that it's not the right graph ...
comment on: http://stackoverflow.com/q/48600374
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84169649
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48565948
score: 0
has text: Each client will be handled by a separate coroutine, and those are lightweight, so you should be fine, provided that the coroutine handler doesn't do something very CPU-consuming. Regardless, the only way to be sure is to create 3000 connections and measure the response.

http://stackoverflow.com/comment/84296783
type: Comment
type: AnswerComment
score: 0
has text: Thanks for your clarification! In the actual code I do not have direct access to that function, since I call it indirectly. I have updated the restrictions to point to this. Nevertheless, your answer is interesting. I learned something! :)
comment on: http://stackoverflow.com/a/48629133

http://stackoverflow.com/comment/84289218
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48643086
has text: you can also place geckodriver anywhere on your PATH and not worry about specifying the location in code. This also has nothing to do with pyvirtualdisplay.

http://stackoverflow.com/q/48506558
has comment: http://stackoverflow.com/comment/84008598
score: 0
has comment: http://stackoverflow.com/comment/84008031
answer count: 1
tagged with: http://stackoverflow.com/tag/xls
has answer: http://stackoverflow.com/a/48507962
accepted answer: http://stackoverflow.com/a/48507962
type: AnsweredQuestion
has body: I have a function that accepts four types of files: .csv .xls .xlsx .json The files can contain up to a couple thousand rows of data. I want to get the column headers for the file, and N example rows of data (doesn't need to be the first N, but need to be a total of N). An example: From animals.csv: To: animals = { "dogs": [1, 5, 8], "cats": [2, 6, 9], "birds": [3, 10, 14], "frogs": [4, 8, 11] } What's the most efficient way of doing this? Test files: animals.csv animals.json animals.xls animals.xlsx
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/json
has title: Read headers and N rows of data
tagged with: python
type: Question

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/48510545
tags question: http://stackoverflow.com/q/48634674

http://stackoverflow.com/a/48499317
type: Answer
has body: To label the contours you would use clabel. Since in this case it seems that you want to directly label the contours by their value, there should not be any need to determine the coordinates or manipulate the labels in any way. import matplotlib.pyplot as plt from numpy import arange, meshgrid delta = 0.025 x_range = arange(-20.0, 20.0, delta) y_range = arange(-20.0, 20.0, delta) X, Y = meshgrid(x_range,y_range) fig=plt.figure() ax=fig.add_subplot(111) ax.set_xlim(xmin=-6, xmax=6) ax.set_ylim(ymin=-4, ymax=4) # F is one side of the equation, G is the other F = (X**2)/2.0+(Y**2) C = range(6,14,3) CS = plt.contour(X, Y, F, C) labels = plt.clabel(CS) xy = [t.get_position() for t in labels] print(xy) plt.show()
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48498868
has comment: http://stackoverflow.com/comment/83994127
answers question: http://stackoverflow.com/q/48498868
score: 1

http://stackoverflow.com/a/48582458
has comment: http://stackoverflow.com/comment/84162541
score: 1
has comment: http://stackoverflow.com/comment/84164345
type: Answer
has comment: http://stackoverflow.com/comment/84162221
has comment: http://stackoverflow.com/comment/84164677
has comment: http://stackoverflow.com/comment/84164098
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: You first have to go into the folder where pip.exe is present. In windows, it is in Scripts folder: cd C:\Python27\Scripts pip install &lt;package&gt; Edit 1: You have to set the http and https proxys as: set HTTP_PROXY=http://&lt;&lt;your_proxy&gt;&gt;:&lt;&lt;your_port&gt;&gt; set HTTPS_PROXY=https://&lt;&lt;your_proxy&gt;&gt;:&lt;&lt;your_port&gt;&gt;
accepted answer of: http://stackoverflow.com/q/48574572
has comment: http://stackoverflow.com/comment/84164064
answers question: http://stackoverflow.com/q/48574572

http://stackoverflow.com/q/48502586
has answer: http://stackoverflow.com/a/48502746
downvote count: 1
accepted answer: http://stackoverflow.com/a/48503277
tagged with: sieve-of-eratosthenes
favorite count: 0
duplicate of: http://stackoverflow.com/q/567222
has body: This is my code: import math n=100 prime=[] [prime.append(i) for i in range(2,n)] i=2 """for i in range(2,int(math.sqrt(n))):""" while i*i &lt;= n: for j in range(2,n+1): if i * j in prime: prime.remove(i*j) i +=1 print(prime) Now this works, but when I changed n from 100 to 10000 it blows. How can I fasten it or should I use generator way? Thank you.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48503277
has title: How to fasten algorithm to calculate Prime Numbers in Python
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83998889
possible better answer: http://stackoverflow.com/a/48502643
tagged with: python
tagged with: primes
has answer: http://stackoverflow.com/a/48502643
has comment: http://stackoverflow.com/comment/83999658
has comment: http://stackoverflow.com/comment/83998943
linked to: http://stackoverflow.com/q/567222
type: AnsweredQuestion
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/83998894
answer count: 3

http://stackoverflow.com/comment/84327190
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48574538
has text: On mac these kind of problems have been around for quite some time. I never really found a fix for it, but here is a [workaround](https://stackoverflow.com/a/44242084/2454357) for the problem. Another option would be to use a different backend, for instance with `plt.switch_backend('TkAgg')`. That backend, however, is rather slow, at least on my machine. Another option would be to indeed use Python 3.6 instead of 2.7 -- is there any strong reason for using the latter?

http://stackoverflow.com/comment/84255505
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48629253
type: Comment
has text: @PaulH Python 3.6.3 and Pandas 0.20.3

http://stackoverflow.com/a/48543916
accepted answer of: http://stackoverflow.com/q/48543757
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/132883597
answers question: http://stackoverflow.com/q/48543757
has body: You are looking into the wrong place. pycountry is mean to give you simple country related information. If you need to dig into the city, use another database that deal with atomise regional details. Maxmind currently open up a free city database that you should look into.
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84094187

http://stackoverflow.com/comment/84001758
type: QuestionComment
has text: [Interprocess Communication and Networking](https://docs.python.org/3/library/ipc.html) RFM?
comment on: http://stackoverflow.com/q/48504023
score: 1
type: Comment

http://stackoverflow.com/comment/84279561
type: QuestionComment
has text: I cannot understand this part, *the comparison is NOT needed when both list indices are the same, because they come from the same data set.* Provide an example which shows this case.
comment on: http://stackoverflow.com/q/48641425
type: Comment
score: 0

http://stackoverflow.com/comment/110134549
type: Comment
comment on: http://stackoverflow.com/a/48525523
type: AnswerComment
score: 0
has text: It fails where data contains date and that date has : in it. e.g. timestamp_time":\"2020-06-08 22:40:00.000000 UTC. This regex convert it to timestamp_time":\"2020-06-08 "22":40:00.000000 UTC

http://stackoverflow.com/a/48571297
score: 1
upvote count: 1
has body: Because under the hood, sys.exit(0) raises a SystemExit exception. Further reading here what you want is: os._exit(1)
downvote count: 0
answers question: http://stackoverflow.com/q/48571212
type: Answer
has comment: http://stackoverflow.com/comment/84139641

http://stackoverflow.com/comment/84224079
has text: @match Loading pickled objects can execute arbitrary code, so that's really not something you want to use in a web app.
score: 0
comment on: http://stackoverflow.com/q/48613592
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48618260
favorite count: 0
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/84232996
has comment: http://stackoverflow.com/comment/84280004
upvote count: 0
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/48618290
has body: Why does the following code return True when it should return False. Trying to test if number is prime. The intent of the code is to loop the this range(2,n) and if any number i divides n (remainder is 0) return False. The code returns True (incorrect) for 25 but False (correct) for 20. When the loop reaches 5 then 25%5 is 0 so it should return False. Where did I go wrong. There are other ways to check if number is prime but I want to know why this way does not work for 25 but does for 20. def isPrime(n): """ """ for i in range(2,n): if n%i == 0: return False else: return True def main(): print isPrime(25) #Should return False if __name__ == '__main__': main() Here is another implementation without the return statements that get so the area of the code that I would like to better understand. for i in range(2,n+1): if n%i == 0: print 'for i =',i,'n%i =',n%i,'Therefore',n,'is not a prime' print 'Should break out of loop here and return False' else: print 'for i =',i,'n%i =',n%i Here is sample output. for i = 2 n%i = 0 Therefore 10 is not a prime Should break out of loop here and return False for i = 3 n%i = 1 for i = 4 n%i = 2 for i = 5 n%i = 0 Therefore 10 is not a prime Should break out of loop here and return False for i = 6 n%i = 4 for i = 7 n%i = 3 for i = 8 n%i = 2 for i = 9 n%i = 1 So, shouldn't have broken out where i is 2 or when i is 5 when n is 10? Why doesn't it?
has title: Incorrect boolean checking for Prime
answer count: 1
tagged with: python

http://stackoverflow.com/comment/84255569
has text: thnks for answer. But how i can get GMAIL ID like this http://take.ms/EjIXY i want then generation link
type: Comment
comment on: http://stackoverflow.com/a/48629145
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84262312
score: 0
has text: @FlyingTeller it says ModuleNotFoundError: No module named 'gdcm'. When I try to pip install gdcm it says the following: Could not find a version that satisfies the requirement gdcm (from versions: ) No matching distribution found for gdcm
comment on: http://stackoverflow.com/q/48632439
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48499883
accepted answer: http://stackoverflow.com/a/48499923
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48499923
upvote count: 2
answer count: 1
downvote count: 0
has body: After trying and failing with solutions given here...I now present my problem: I have a csv which was imported from multiple txt-files and currently the dtype is str in all columns. For sorting my data I need one column to be int again but converting doesn't work as I hoped. I'm using Pandas. I tried different approaches. Firsty, loading the data with a converter: df = pd.read_csv('501-1000.csv', sep='\t', header=None, index_col=False, names=cols, usecols=cols,converters={"PY":int}) and using df["PY"].astype(int). In both cases I got the ValueError: invalid literal for int() with base 10: 'BA' Since I read that this has something to do with values that can't be converted to ints I tried df.dropna(subset=['PY']) and df["PY"].fillna(0.0).astype(int) The results didn't change. Any ideas on how to solve this? Sadly checking my rows by hand is not really an option - In my test-file, maybe, but it's just to much data to do that. The full traceback when trying the converter is the following: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-4-d5ea8aa389dc&gt; in &lt;module&gt;() 16 # load data; note dtype not set to str since there appear to be numeric columns 17 cols = ['TI', 'AB', 'PY', 'DI'] ---&gt; 18 df = pd.read_csv('501-1000.csv', sep='\t', header=None, index_col=False, names=cols, usecols=cols,converters={"PY":int}) 19 20 # cycle through filename_dict, slice and export to csv ~\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, en…
favorite count: 0
type: Question
has title: Invalid Literal for Int Error with csv
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/a/48643720
answers question: http://stackoverflow.com/q/48643604
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84284254
has body: If i understand well what you need is cast the quotes and commas before panda read the csv. Like these: "Business focus","Country","City","Company Name" "IT","France","Lyon","Societe General" "Mining","Russia","Moscow","Company \"MoscowMining\" Owner1\, Owner2\, Owner3" "Agriculture","Poland","Warsaw","Company\" Jankowski\,A\,B\""

http://stackoverflow.com/comment/84243688
type: AnswerComment
has text: you could edit your question or create another one to explain why youre struggling with `Popen`. Everything that can be done with `run` can be done with `Popen`, and more...
score: 0
comment on: http://stackoverflow.com/a/48623543
type: Comment

http://stackoverflow.com/a/48602460
has comment: http://stackoverflow.com/comment/84201769
has comment: http://stackoverflow.com/comment/84201798
answers question: http://stackoverflow.com/q/48602311
score: 2
has comment: http://stackoverflow.com/comment/84201532
type: Answer
has comment: http://stackoverflow.com/comment/84201520
has comment: http://stackoverflow.com/comment/84201640
has comment: http://stackoverflow.com/comment/84201827
has comment: http://stackoverflow.com/comment/84201503
has comment: http://stackoverflow.com/comment/84201569
has comment: http://stackoverflow.com/comment/84201707
has body: Here is one way df = pd.read_clipboard(sep = '\s\s+') Index_Date A B C D 2015-01-31 10 10 we 10 2015-02-01 2 3 jk 22 and 23 and 24 2015-02-02 10 60 nm 280 2015-02-03 10 100 oi 250 df.set_index(['Index_Date', 'A', 'B', 'C']).D.str.split('and', expand = True)\ .stack().reset_index(4,drop = True).reset_index(name = 'D') Index_Date A B C D 0 2015-01-31 10 10 we 10 1 2015-02-01 2 3 jk 22 2 2015-02-01 2 3 jk 23 3 2015-02-01 2 3 jk 24 4 2015-02-02 10 60 nm 280 5 2015-02-03 10 100 oi 250
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/84074459
comment on: http://stackoverflow.com/q/48535847
score: 1
type: Comment
has text: @PeterThomas done
type: QuestionComment

http://stackoverflow.com/comment/84062195
type: AnswerComment
score: 1
has text: NB: don't use `plt.tight_layout()` or use it before `fig.subplot_adjust()`, else it won't work!
type: Comment
comment on: http://stackoverflow.com/a/48532569

http://stackoverflow.com/comment/87876906
has text: Is this still open? Need some details: Are the image URLs in a database in google cloud? Or are they streamed as a result of a crawler bot running on a GCE instance? Do you have budget or you are limited to free tier? If not still open, what did you end up doing?
comment on: http://stackoverflow.com/q/48594673
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84262548
type: Comment
has text: It just occurred to me that this might be a use case for overloading...
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48632608

http://stackoverflow.com/comment/84088825
type: Comment
comment on: http://stackoverflow.com/a/48531823
score: 0
has text: Awesome. First part is clear now. Coming to the second part, How both parameters 'size' and 'key' have been passed through MainLoop function?
type: AnswerComment

http://stackoverflow.com/q/48545255
type: Question
accepted answer: http://stackoverflow.com/a/49984841
upvote count: 2
has answer: http://stackoverflow.com/a/49984841
linked to: http://stackoverflow.com/q/4778043
downvote count: 0
answer count: 1
tagged with: python
tagged with: visual-studio-2015
has comment: http://stackoverflow.com/comment/84086404
tagged with: static-libraries
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84086867
has body: I am working with the 3.6.4 source release of Python. I have no trouble building it with Visual Studio as a dynamic library (/MDd) I can link the Python .dll to my own code and verify its operation. But when I build it (and my code) with (/MTd) it soon runs off the rails when I try to open a file with a Python program. A Debug assertion fails in read.cpp ("Expression: _osfile(fh) &amp; FOPEN"). What I believe is happening is the Python .dll is linking with improper system libraries. What I can't figure out is how to get it to link with the correct ones (static libraries).
linked to: http://stackoverflow.com/q/19560594
has comment: http://stackoverflow.com/comment/84087972
has comment: http://stackoverflow.com/comment/84087277
has title: I cannot build python.dll as a static library (/MTd) using Visual Studio
tagged with: libcmtd
favorite count: 0

http://stackoverflow.com/comment/84050652
type: QuestionComment
comment on: http://stackoverflow.com/q/48527267
score: 0
type: Comment
has text: Yes that makes sense. Thank you so much!

http://stackoverflow.com/q/48553196
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/487258
tagged with: data-mining
has comment: http://stackoverflow.com/comment/84145167
has comment: http://stackoverflow.com/comment/84123016
type: Question
tagged with: nltk
accepted answer: http://stackoverflow.com/a/48553275
has comment: http://stackoverflow.com/comment/84102888
tagged with: python
has title: Extracting sentence from a dataframe with description column based on a phrase
tagged with: regex
has comment: http://stackoverflow.com/comment/84108923
has answer: http://stackoverflow.com/a/48553275
possible better answer: http://stackoverflow.com/a/58621805
tagged with: nlp
has body: I have a dataframe with a 'description' column with details about the product. Each of the description in the column has long paragraphs. Like "This is a superb product. I so so loved this superb product that I wanna gift to all. This is like the quality and packaging. I like it very much" How do I locate/extract the sentence which has the phrase "superb product", and place it in a new column? So for this case the result will be expected output I have used this, searched_words=['superb product','SUPERB PRODUCT'] print(df['description'].apply(lambda text: [sent for sent in sent_tokenize(text) if any(True for w in word_tokenize(sent) if stemmer.stem(w.lower()) in searched_words)])) The output for this is not suitable. Though it works if I put just one word in " Searched Word" List.
has answer: http://stackoverflow.com/a/58621805
type: AnsweredQuestion

http://stackoverflow.com/comment/84021629
comment on: http://stackoverflow.com/q/48513344
type: Comment
type: QuestionComment
score: 0
has text: No, as far as pandas is concerned, this is on topic. But I need clarification. Point 2, you mention to flag the first row that violates the condition above. What condition are you referring to?

http://stackoverflow.com/q/48520244
has body: I am defining the below function. def trip_cost(days, city): return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days) However, when it executes I receive the below error: trip_cost('Pittsburgh', 8) raised an error: cannot concatenate 'str' and 'NoneType' objects But, if I execute the below code; def trip_cost(city,days): return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days) It runs fine. the complete code is provided below; def hotel_cost(nights): return 140 * nights def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 def rental_car_cost(days): cost = days * 40 if days &gt;= 7: cost -= 50 elif days &gt;= 3: cost -= 20 return cost def trip_cost(days, city): return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days)
answer count: 3
has comment: http://stackoverflow.com/comment/84035189
has comment: http://stackoverflow.com/comment/84035216
type: Question
has answer: http://stackoverflow.com/a/48520333
tagged with: python
type: UnansweredQuestion
has title: python function argument mismatch
has answer: http://stackoverflow.com/a/48520408
has answer: http://stackoverflow.com/a/48520378
has comment: http://stackoverflow.com/comment/84035208
score: 0
tagged with: function
has comment: http://stackoverflow.com/comment/84035090

http://stackoverflow.com/comment/84098430
type: AnswerComment
comment on: http://stackoverflow.com/a/48550644
score: 0
type: Comment
has text: Great thanks. I've marked it as an answer since it's way more efficient.

http://stackoverflow.com/a/48648071
answers question: http://stackoverflow.com/q/48640143
upvote count: 2
has body: Although you create your venv virtual environment with python=2.7, the message you get when trying to upgrade pip indicates that you are running it in Python 3.5; the path ./anaconda/lib/python3.5/site-packages clearly refers to the base Anaconda installation, and not to your venv virtual environment. Given that, the error message you get is not unexpected, since Turicreate is not yet available for Python 3.5: System Requirements Python 2.7 (Python 3.5+ support coming soon) x86_64 architecture
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48640143
score: 2

http://stackoverflow.com/comment/84117116
comment on: http://stackoverflow.com/a/48560753
has text: Can i write this authenticate method in my model ? having one to one with built in User
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84018810
type: Comment
has text: Wohooo... great its working... don't forget to feed the fish "usefull answer" ;-)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48511225

http://stackoverflow.com/q/48492755
score: 0
has body: Im trying to scrape over http://www.ign.com/ to be able to scrape over their videogame news, but their format has a slider reel where you select what type of news you want. By default this is set to "latest" but I want to be able to activate the "games" button to be able to extract info from there. How would I do this with Beautiful Soup?
answer count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/83978687
has answer: http://stackoverflow.com/a/48493454
tagged with: beautifulsoup
type: Question
has title: Pressing buttons while Web Scraping python
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48585865
favorite count: 0
score: 1
has comment: http://stackoverflow.com/comment/84169712
tagged with: django-models
tagged with: python
has title: Django : changing a specific form in modelformset
has body: Here is the riddle. This is a simplified version of the problem I am dealing with, just so we can capture the core problem. So, for the sake of simplicity and relevance, not all fields and relationships are shown here. So, I have a modelformset and I would like to access each individual form to change the field based on the queryset. class PlayerType(models.Model): type = models.CharField(max_length=30, choices = PLAYER_TYPES) class Player(models.Model): name = models.CharField(max_length=30, blank=False, null=False) player_type = models.ForeignKey(PlayerType, related_name ='players') contract_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank = False, null = False) price_unit_of_measurement = models.CharField(max_length=20, choices=STANDARD_UOM) Forms.py class PlayerForm(ModelForm): class Meta: fields = ['name','price_unit_of_measurement'] views.py PlayerFormSet = modelformset_factory(Player, form = PlayerForm, extra = 5) Now, say I want to display a different unit of measurement depending on which player I am showing. For instance, player 1's contract may be based on lump sump or amount per game, and another player's contract may be based on number of minutes played, price per month, etc. depending on the player type. In essence, I would like to know how to access each form in a modelformset and change the unit of measurement for that form alone, from the default set in the model. I also understand that inlinemodelformset is more appropriate for this application as Player related to PlayerType on one-to-many relationship basis.
tagged with: django-forms
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: django
linked to: http://stackoverflow.com/q/25156980

http://stackoverflow.com/comment/84191281
has text: Python is case-sensitive. `If` should be `if`.
type: Comment
comment on: http://stackoverflow.com/a/48597147
type: AnswerComment
score: 0

http://stackoverflow.com/comment/126854968
type: Comment
score: 0
type: AnswerComment
has text: Don't change the problem. You're using class Ui_MainWindow(QMainWindow): instead of class Ui_MainWindow(object):
comment on: http://stackoverflow.com/a/48667082

http://stackoverflow.com/comment/84283436
has text: Thank you very much for this! If you don't mind, could you please tell me what eval does in this case? I was using input only and it never worked.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48643105

http://stackoverflow.com/q/48580361
score: 7
downvote count: 0
has answer: http://stackoverflow.com/a/48580641
tagged with: permutation
has comment: http://stackoverflow.com/comment/84157370
upvote count: 7
has comment: http://stackoverflow.com/comment/126961795
accepted answer: http://stackoverflow.com/a/48581219
has body: Given a set of N elements, I want to choose m random, non-repeating subsets of k elements. If I was looking to generate all the N choose k combinations, I could have used itertools.combination, so one way to do what I m asking would be: import numpy as np import itertools n=10 A = np.arange(n) k=4 m=5 result = np.random.permutation([x for x in itertools.permutations(A,k)])[:m] print(result) The problem is of course that this code first generates all the possible permutations, and that this can be quite expensive. Another suboptimal solution would be to choose each time a single permutation at random (e.g. choose-at-random-from-combinations, then sort to get permutation), and discard it if it has already been selected. Is there a better way to do this?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84157797
possible better answer: http://stackoverflow.com/a/48580641
linked to: http://stackoverflow.com/q/15512058
has title: Python: Given a set of N elements, choose k at random, m times
tagged with: python
linked to: http://stackoverflow.com/q/22229796
has comment: http://stackoverflow.com/comment/84157309
has answer: http://stackoverflow.com/a/48581219
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/48531614
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84058823
has comment: http://stackoverflow.com/comment/84058846
has title: Why are my returned numbers in parentheses?
has answer: http://stackoverflow.com/a/48531656
tagged with: python
score: -1
tagged with: python-2.7
has body: When I run my code, the returned numbers are in parentheses Like this: Your Target Heart Rate zone is: (125, 144) beats per minute I know that this is a duple, but not how to avoid this. Anyone know how to fix? def target (rate): print "Please indicate your exercise objective as follows" print "1 = weight loss, building endurance" print "2 = weight management, improving cardio fitness " print "3 = interval workouts" zone = int(raw_input("input your objective: ")) if zone == 1: down = int(rate * .6) up = int(rate * .7) print down, up return down, up elif zone == 2: down = int(rate * .7) up = int(rate * .8) return down, up elif zone == 3: down = 0 up = int(rate * .8) return down, up print "This program calculates Maximum Heart Rate (MHR) and preferred Target Heart Rate (THR) Zones " print age = int(raw_input("Please input your age: ")) mhr = 220-age thr = target(mhr) print "Your Target Heart Rate zone is: ", thr, " beats per minute" The solution should be : Your Target Heart Rate zone is: # - # beats per minute
answer count: 2
downvote count: 2
duplicate of: http://stackoverflow.com/q/28116528
upvote count: 1
has answer: http://stackoverflow.com/a/48531658
linked to: http://stackoverflow.com/q/28116528

http://stackoverflow.com/q/48589705
tagged with: python-datetime
tagged with: datetime
has title: Convert all datetime elements in list to date?
has answer: http://stackoverflow.com/a/48589792
tagged with: python
score: -1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48589756
has body: The list has datetime elements along with other. (1127, 1, 2, datetime.datetime(1900, 1, 1, 8, 30), 'America/NewYork', None, None, datetime.datetime(1970, 1, 1, 0, 0), datetime.datetime(9999, 12, 31, 0, 0), 62, 3, ' ', 2, datetime.datetime(2017, 12, 6, 16, 4, 25, 233000)) I tried using with no luck i = [d.date() for d in i]
upvote count: 0
type: UnansweredQuestion
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84176877
has comment: http://stackoverflow.com/comment/84344774

http://stackoverflow.com/a/48553903
has body: I would try converting the string representation of what I suspect to be a datetime into a datetime object, using the parse function from dateutil.parser. https://chrisalbon.com/python/basics/strings_to_datetime/
answers question: http://stackoverflow.com/q/48553847
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/84050641
type: QuestionComment
score: 0
has text: just access the default value this way: `GlobalParams.date._default.strftime('%d-%b-%Y')`
type: Comment
comment on: http://stackoverflow.com/q/48509083

http://stackoverflow.com/comment/84003166
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48504421
has text: @RavinderSingh13 thanks...I've added +1 as ur code helps makes my awk command 1-liner in case I use shell.

http://stackoverflow.com/comment/84054571
has text: The problem is that your string has a lot of ` \ ` characters in it. In a raw string literal those will be left as-is, in a normal string literal they will swallow up the following character(s) and become a completely different character. This is exactly why raw string literals were invented, why can't you use them?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48529256
score: 0

http://stackoverflow.com/comment/84054329
has text: Is this how you're supposed to implement commands? Through the @client.event and on_message, not with @client.command?
type: AnswerComment
comment on: http://stackoverflow.com/a/48519097
type: Comment
score: 0

modelica
tag name: modelica
tags question: http://stackoverflow.com/q/48625195
tags question: http://stackoverflow.com/q/48597120
type: Tag

http://stackoverflow.com/q/48500558
type: Question
answer count: 5
accepted answer: http://stackoverflow.com/a/54101530
score: -2
has title: Python: making a project
has comment: http://stackoverflow.com/comment/83997335
has answer: http://stackoverflow.com/a/63924411
has answer: http://stackoverflow.com/a/52992006
has answer: http://stackoverflow.com/a/54101530
possible better answer: http://stackoverflow.com/a/48500849
tagged with: python
has comment: http://stackoverflow.com/comment/83994443
has answer: http://stackoverflow.com/a/49890754
has comment: http://stackoverflow.com/comment/83994370
has body: hello i am new in python and i started learning from a book called "automate the boring stuff" and there was a project in it called Character Picture Grid and i did it but i think my code is little bit stupid and anyone tell me the right way to do this project ? :D thank you ^^ code: 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', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] def x_y_1(grid): for y in range(9): for x in [0]: print(grid[y][x],end='') print(end='\n') def x_y_2(grid): for y in range(9): for x in [1]: print(grid[y][x],end='') print(end='\n') def x_y_3(grid): for y in range(9): for x in [2]: print(grid[y][x],end='') print(end='\n') def x_y_4(grid): for y in range(9): for x in [3]: print(grid[y][x],end='') print(end='\n') def x_y_5(grid): for y in range(9): for x in [4]: print(grid[y][x],end='') print(end='\n') def x_y_6(grid): for y in range(9): for x in [5]: print(grid[y][x],end='') print(end='\n') x_y_1(grid) x_y_2(grid) x_y_3(grid) x_y_4(grid) x_y_5(grid) x_y_6(grid)
has answer: http://stackoverflow.com/a/48500849
has comment: http://stackoverflow.com/comment/83994651
type: AnsweredQuestion
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83994519
has comment: http://stackoverflow.com/comment/83994359
favorite count: 0

http://stackoverflow.com/a/48640317
has comment: http://stackoverflow.com/comment/84281586
has comment: http://stackoverflow.com/comment/84280649
has comment: http://stackoverflow.com/comment/84348196
score: 0
has comment: http://stackoverflow.com/comment/84345663
answers question: http://stackoverflow.com/q/48638138
type: Answer
has body: You have several options: Switch to Python 3.6. Dictionaries got a LOT better in 3.6. Faster, smaller footprint, ordered by default, and I'm sure I'm forgetting something. Get more memory. You're clearly doing something bounded by memory on a machine that doesn't fit the bill. Buy more RAM, or rent an m4.xlarge AWS instance, or something. Redefine the problem. Do you need all million items in memory at once? Are you working on them all at once? Almost definitely not. Write your algorithms smarter, to work on the data chunks at a time, or even items at a time. If you make this concurrent (not necessarily parallel), most of the wait time will be IO, and can easily be threaded in Python. Try making use of generator expressions and generators in general. Their memory usage is tiny. Use a database Databases are specifically around to solve this problem. Write a small importer to chuck your data into MySQL or MongoDB, then express your problem in SQL.
has comment: http://stackoverflow.com/comment/84281251
has comment: http://stackoverflow.com/comment/84281940
has comment: http://stackoverflow.com/comment/84283486
has comment: http://stackoverflow.com/comment/84282419
has comment: http://stackoverflow.com/comment/84288511

http://stackoverflow.com/a/48556319
has comment: http://stackoverflow.com/comment/84108604
accepted answer of: http://stackoverflow.com/q/48555555
has comment: http://stackoverflow.com/comment/84132933
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: The msg argument to smtplib.sendmail should be a bytes sequence containing a valid RFC5322 message. Taking a string and encoding it as UTF-8 is very unlikely to produce one (if it's already ASCII, encoding it does nothing useful; and if it isn't, you are most probably Doing It Wrong). To explain why that is unlikely to work, let me provide a bit of background. The way to transport non-ASCII strings in MIME messages depends on the context of the string in the message structure. Here is a simple message with the word "Hëlló" embedded in three different contexts which require different encodings, none of which accept raw UTF-8 easily. From: me <sender@example.org> To: you <recipient@example.net> Subject: =?utf-8?Q?H=C3=ABll=C3=B3?= (RFC2047 encoding) MIME-Version: 1.0 Content-type: multipart/mixed; boundary="fooo" --fooo Content-type: text/plain; charset="utf-8" Content-transfer-encoding: quoted-printable H=C3=ABll=C3=B3 is bare quoted-printable (RFC2045), like what you see in the Subject header but without the RFC2047 wrapping. --fooo Content-type: application/octet-stream; filename*=UTF-8''H%C3%ABll%C3%B3 This is a file whose name has been RFC2231-encoded. --fooo-- There are recent extensions which allow for parts of messages between conforming systems to contain bare UTF-8 (even in the headers!) but I have a strong suspicion that this is not the scenario you are in. Maybe tangentially see also https://en.wikipedia.org/wiki/Unicode_and_email Returning to your code, I suppose it could work if base is coincidentally also the name of a header you want to add to the start of the message, and text contains a string with the rest of the message. You are not showing enough of your code to reason intelligently about this, but it seems highly unlikely. And if text already contains a valid MIME message, encoding it as UTF-8 should not be necessary or useful (but it clearly doesn't, as you get the encoding error). Let's suppose base contains Subject and text is defined thusly: …
has comment: http://stackoverflow.com/comment/84136852
answers question: http://stackoverflow.com/q/48555555
score: 3
has comment: http://stackoverflow.com/comment/84132233
has comment: http://stackoverflow.com/comment/102895724
type: Answer
has comment: http://stackoverflow.com/comment/102891734

http://stackoverflow.com/a/48524828
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48522997
answers question: http://stackoverflow.com/q/48522997
type: Answer
has body: This is because you did not specify the number of arguments expected after each flag with nargs as such: import argparse def parse_args(): parser = argparse.ArgumentParser(description='Simple training script for object detection from a CSV file.') parser.add_argument('csv_path', nargs="?", type=str, help='Path to CSV file') parser.add_argument('--weights', nargs="?", help='Weights to use for initialization (defaults to ImageNet).', default='imagenet') parser.add_argument('--batch-size', nargs="?", help='Size of the batches.', default=1, type=int) return parser.parse_args() parse_args() According to the doc: If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced. '?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples to illustrate this: Details here
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84050217
type: AcceptedAnswer

http://stackoverflow.com/q/48507946
has body: I have a python daemon process which periodically starts VLC player in fullscreen mode, plays some video and stops it: import vlc ... player = vlc.MediaPlayer() player.set_fullscreen(True) ... player.play() ... player.stop() ... But if I open or focus any other window after I start my script, VLC player pops up in fullscreen mode but don't go over this new top-level window. There is no such problem for Linux Mint. VLC in fullscreen overwrite anything, no matter what. Is there any solution or workaround for such problem?
has title: Windows 10. Python. VLC in fullscreen mode does not play in foreground
has answer: http://stackoverflow.com/a/49094790
answer count: 1
favorite count: 0
type: Question
tagged with: fullscreen
tagged with: windows
accepted answer: http://stackoverflow.com/a/49094790
tagged with: python
tagged with: vlc
type: AnsweredQuestion
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/48508424
has comment: http://stackoverflow.com/comment/84059662
answers question: http://stackoverflow.com/q/48508215
has comment: http://stackoverflow.com/comment/84061556
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84062694
has body: import pandas as pd data = [ ['AEC', 0.2093275], ['AEC', 0.5384086], ['CIZ', 0.1465657], ['CIZ', 0.7465657], ['CIZ', 0.1465657], ] df = pd.DataFrame(data, columns = ['ID', 'Load']) groups = df.groupby('ID').agg({'ID': 'count', 'Load': 'sum'}) groups = groups.rename(columns = {'ID': 'Count', 'Load': 'Total'}).reset_index() groups['adjust'] = (1 - groups['Total'])/groups['Count'] df = pd.merge(df, groups, on = 'ID') df['Load'] = df['Load'] + df['adjust'] df = df.drop(['Total', 'Count', 'adjust'], axis = 1) print(df) #output ID Load 0 AEC 0.335459 1 AEC 0.664541 2 CIZ 0.133333 3 CIZ 0.733333 4 CIZ 0.133333 Update code based on comment. Calculate an adjustment field based on a summarized dataframe. Then apply to adjustment evenly to each group.
upvote count: 1
has comment: http://stackoverflow.com/comment/84013799

http://stackoverflow.com/comment/123230106
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48552151
has text: Does this answer your question? [How to read image file from S3 bucket directly into memory?](https://stackoverflow.com/questions/44043036/how-to-read-image-file-from-s3-bucket-directly-into-memory)

http://stackoverflow.com/comment/132367515
score: 0
has text: @eyllanesc Seems your comment was the answer. Do you want to make it an answer?
type: Comment
comment on: http://stackoverflow.com/q/48644156
type: QuestionComment

labeling
tags question: http://stackoverflow.com/q/48500434
tag name: labeling
type: Tag

http://stackoverflow.com/a/48622078
type: AcceptedAnswer
downvote count: 0
score: 4
has body: Firstly, reshape your DataFrame so you have the following format. LOG_TIME ORIENTATION value result 0 68444.0 PRP 4.8 QP 1 68444.0 HCP 4.9 QP 2 68444.0 PRP 3.8 IP 3 68444.0 HCP 0.6 IP You can do this with the following. new = df.melt(id_vars='LOG_TIME', value_vars=['QP_PRP', 'QP_HCP', 'IP_PRP', 'IP_HCP'], var_name='ORIENTATION') new'result', 'ORIENTATION' = new['ORIENTATION'].str.split('_', expand=True).rename(columns={0: 'result', 1: 'ORIENTATION'}) Then you can pivot the data. new = new.pivot_table(index=['LOG_TIME', 'ORIENTATION'], columns='result', values='value') pd.DataFrame(new.to_records()) Out[6]: LOG_TIME ORIENTATION IP QP 0 68444.0 HCP 0.6 4.9 1 68444.0 PRP 3.8 4.8
accepted answer of: http://stackoverflow.com/q/48620969
type: Answer
answers question: http://stackoverflow.com/q/48620969
upvote count: 4

http://stackoverflow.com/a/48546233
score: 4
has body: Creating items on the canvas is slow, and the more you create the slower it gets (even if you delete them each time). Instead, create the rectangles once and then simply reconfigure them on each generation. The create_rectangle method returns an integer id. Save these ids, then use the itemconfigure method to change the color.
answers question: http://stackoverflow.com/q/48545890
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48545890

http://stackoverflow.com/comment/84003649
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48504746
has text: _"`import _tkinter # If this fails your Python may not be configured for Tk`"_ so I guess we at least know what the problem is.

http://stackoverflow.com/a/55697741
type: Answer
has body: I think there is some implementation issue in the itkFormatWarning() provided by itk, that python points to when using ITK or a numpy array generated using ITK. The following helped me, that is if you would like to ignore all the warnings. import warnings warnings.filterwarnings('ignore') For the vtk warnings I just route it to a file.
answers question: http://stackoverflow.com/q/48561123
score: 0

http://stackoverflow.com/a/63933172
upvote count: 16
has body: We can do the join without relationships as well. Explicitly mention the condition on join. Example from sqlalchemy.orm import aliased user1 = aliased(UserSkill) user2 = aliased(UserSkill) query_result = db.session.query( func.distinct(User.id).label('user_id'), User.username, ).join( user1, User.id == user1.user_id, ).join( user2, user2.id == User.id, ).filter( user1.user_id == id, ).all()
has comment: http://stackoverflow.com/comment/131133497
has comment: http://stackoverflow.com/comment/131252519
downvote count: 0
score: 16
answers question: http://stackoverflow.com/q/48550653
type: Answer

http://stackoverflow.com/q/48491128
possible better answer: http://stackoverflow.com/a/48491205
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48491205
tagged with: function
upvote count: 0
has body: I want to write a 'If Else' function in Python to check if a list of modules are present or not, else install modules in Python (3.6). Thanks in advance!
has title: How to write a function to check if a list of modules are present or not, else install modules in Python
downvote count: 1
has comment: http://stackoverflow.com/comment/83975332
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48491252
tagged with: if-statement
has answer: http://stackoverflow.com/a/48491252
tagged with: python-module
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83975436
linked to: http://stackoverflow.com/q/30483246

http://stackoverflow.com/a/48624401
has comment: http://stackoverflow.com/comment/84246153
has body: tl;dr Close the other instance of the Spark application in C:\Users\USER\Desktop\ColumnSimilarities\metastore_db and start over. The exception: ERROR XSDB6: Another instance of Derby may have already booted the database C:\Users\USER\Desktop\ColumnSimilarities\metastore_db says it all. You've got two instances of a Spark application up and running in C:\Users\USER\Desktop\ColumnSimilarities. It is not possible with the default hive external catalog (aka metastore). Spark SQL uses an external catalog (aka metastore) to manage the metadata of persistent tables and uses Derby as the underlying database that allows a single client to access it. You can only have one Spark application in a given directory (or you'd have to change the directory where the HiveExternalCatalog stores the metadata).
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84249035
score: 1
answers question: http://stackoverflow.com/q/48606032
type: Answer
accepted answer of: http://stackoverflow.com/q/48606032
has comment: http://stackoverflow.com/comment/84248367

http://stackoverflow.com/q/48600219
has comment: http://stackoverflow.com/comment/84197094
has comment: http://stackoverflow.com/comment/84197165
downvote count: 1
favorite count: 0
type: Question
has title: Regex. How to repalce all patterns except one?
has answer: http://stackoverflow.com/a/48601220
has comment: http://stackoverflow.com/comment/84201064
has comment: http://stackoverflow.com/comment/84197074
tagged with: python
score: -1
tagged with: regex
has comment: http://stackoverflow.com/comment/84198904
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1732348
upvote count: 0
has comment: http://stackoverflow.com/comment/84197349
accepted answer: http://stackoverflow.com/a/48601220
has body: I'm new to regular expressions, therefore I need some help. I have a string. For example: "Some words . Next words abc" I want to delete all tags except . Can I create one regex or I should to make several regular expression? Expected output: "Some words. Next words abc"
has comment: http://stackoverflow.com/comment/84208989
answer count: 1

http://stackoverflow.com/q/48499299
duplicate of: http://stackoverflow.com/q/31948285
tagged with: angularjs
type: Question
duplicate of: http://stackoverflow.com/q/19126994
has title: How to get AJAX Progress for an POST request?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83992774
has comment: http://stackoverflow.com/comment/83992721
has comment: http://stackoverflow.com/comment/83992019
has comment: http://stackoverflow.com/comment/83992888
score: 0
has comment: http://stackoverflow.com/comment/83991971
duplicate of: http://stackoverflow.com/q/27831228
answer count: 0
has comment: http://stackoverflow.com/comment/83992382
linked to: http://stackoverflow.com/q/19126994
tagged with: jquery
has body: I'm making an AJAX HTTP POST request to an Python flask REST api. Can I get the percentage of the request completed? Any suggestion using $ajax or $http? I have tried the below code. I'm getting the values along with the response. xhr.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; console.log(percentComplete * 100); $('.progress').css({ width: percentComplete * 100 + '%' }); if (percentComplete == 1) { $('.progress').addClass('hide'); } } }, false); return xhr;
tagged with: flask
tagged with: ajax

openmdao
tag name: openmdao
tags question: http://stackoverflow.com/q/48525825
type: Tag

http://stackoverflow.com/a/48500914
upvote count: 2
answers question: http://stackoverflow.com/q/48497133
score: 2
downvote count: 0
type: Answer
has body: This is nothing to do with django; it's a core Python feature. It's called a "default argument". Consider the following code: def f(x=3): print(x) f() # prints "3" f(4) # prints "4" As you can see, the value after the = is used if no value was provided. This is very useful for defining functions that have a default behaviour which can be customised with different arguments. In the django use case you've provided, they're simply allowing you to not define a password when creating a user.

http://stackoverflow.com/q/48616663
has body: This is how i upload file from form to FileField in the backend: the_file = request.FILES['newProfilePicture'] the_customer = Customer.objects.first() the_customer.profile_picture = the_file the_customer.save() But here is the problem, how do i get that filefield and then "copy paste" it to another object that has a different "upload_to" data? The Customer object: class Customer( models.Model ): profile_picture = models.FileField(upload_to='uploads/customer/%Y/%m/%d/') The Customer_Alternative object: class Customer_Alternative( models.Model ): profile_picture = models.FileField(upload_to='uploads/customer-alternative/%Y/%m/%d/') My current problem is that when i do the followings, it simply use the same picture instead of "copy-pasting" it to the new directory: old_customer = Customer.objects.all().first() new_customer_alternative = Customer_Alternative( profile_picture=old_customer.profile_picture, ) new_customer_alternative.save() So if i delete the FileField on that Customer object, it will also delete the data of the Customer_Alternative. Is there anyway to "copy paste" the data instead? I tried to do a deep copy, but failed? old_customer = Customer.objects.all().first() new_customer_alternative = Customer_Alternative( profile_picture=old_customer.profile_picture, ) new_customer_alternative.profile_picture.file = ContentFile(old_customer.profile_picture.read()) new_customer_alternative.save()
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/29270812
has title: How to copy paste FileField?
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48616875
score: 0
answer count: 1
tagged with: django-models
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/48530091
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/48530196
has body: I've recently been working on a project in the field of machine learning, and I'm having some trouble with a regular expression that is needed for my data. For some reason, instead of returning a decimal value as it should, it ends up returning a value of None. Any suggestions? Below is my code, and the file I'm trying to get data out of. for list_num in range(0,92): mach = [3,4,5,6,7] for j in range(0,4): if list_num &gt;= 0 and list_num &lt;= 4: if os.path.isfile('C://Users/avickers/Desktop/XFOIL_Training_Data/listofoutputs/listofoutputs0006'+str(mach[j])+'.pol'): tempaccess = os.listdir('C://Users/avickers/Desktop/XFOIL_Training_Data/listofoutputs') with open('C://Users/avickers/Desktop/XFOIL_Training_Data/listofoutputs/listofoutputs0006'+str(mach[j])+'.pol','r') as tempfile: lines = tempfile.readlines() file = tempfile.read() name = '0006' f = open('C://Users/avickers/Desktop/XFOIL_Training_Data/listofoutputs/data.pol','a+') Re = re.search(r'Re\s*=\s*(\d\.\d+)',file) AOA = [] Dl = [] Dd = [] num=0 for line in lines[12:]: columns = line.split() AOA.append(columns[0]) Dl.append(columns[1]) Dd.append(columns[2]) num += 1 for i in range(0,num): f.write(name+' ') f.write(str(mach[j]/10)+' ') f.write(str(Re)+' ') f.write(AOA[i]+' ') f.write(Dl[i]+' ') f.write(Dd[i]+'\n') The file: XFOIL Version 6.99 Calculated polar for: NACA 0006 1 1 Reynolds number fixed Mach number fixed xtrf = 1.000 (top) 1.000 (bottom) Mach = 0.300 Re = 2.213 e 6 Ncrit = 9.000 alpha CL CD CDp CM Cpmin XCpmin Top_Xtr Bot_Xtr ------ -------- --------- --------- -------- -------- -------- -------- ---- -10.000 -0.7244 0.11348 0.11239 0.0360 -3.2095 0.0001 1.0000 0.0032 -9.500 -0.7284 0.10263 0.10156 0.0311 -3.6224 0.0001 1.0000 0.0033 -9.000 -0.7330 0.09190 0.09085 0.0257 -3.9746 0.0001 1.0000 0.0036 The specific value I'm trying to extract is the Re. Thanks!
favorite count: 0
type: Question
has title: Why is this regular expression not returning anything?
has answer: http://stackoverflow.com/a/48530196
tagged with: python
tagged with: regex

http://stackoverflow.com/q/48585399
upvote count: 1
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
has title: Subtracting counts (DataFrame.count()) from a DataFrame entry in Pandas
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48585463
score: 1
has body: I have a counts on df1 that I want to subtract from an entry in df2. Specifically, I want to subtract the number of customers having zero income from the 2018 row in df2 : count = df1[df1['income']==0].count() df2.loc('2018', 'income') -= count I get the warning: "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 " The problem seems to be that DataFrame.counts() returns a Series and not a number. Any ideas?
answer count: 1
has answer: http://stackoverflow.com/a/48585463
downvote count: 0

http://stackoverflow.com/comment/84426653
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48632835
has text: Did this solve your problem?

http://stackoverflow.com/comment/84065452
has text: I m not sure if that makes much sense. Basically, you are trying to imply that your model is non-stationary (i.e. it is different at different time? ) in that case, I doubt even feeding the timestamp can help.
comment on: http://stackoverflow.com/q/48534636
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48549555
tagged with: pywin32
accepted answer: http://stackoverflow.com/a/48549912
has title: How to set font type and size for printing using windows GDI?
favorite count: 0
has answer: http://stackoverflow.com/a/48549912
type: Question
upvote count: 2
downvote count: 0
answer count: 1
has body: My python program only needs to print text in certain positions. I'm using the windows GDI to archive the goal. The following code does the job, but i need to set the font type and the size. import win32ui dc = win32ui.CreateDC() dc.CreatePrinterDC() dc.StartDoc('Test document') dc.StartPage() dc.TextOut(100,2000, 'HELLO WORLD!') dc.EndPage() dc.EndDoc()
tagged with: python
tagged with: gdi
score: 2
type: AnsweredQuestion
tagged with: printing

http://stackoverflow.com/q/48575298
tagged with: qtreewidget
has comment: http://stackoverflow.com/comment/84147441
has comment: http://stackoverflow.com/comment/84148918
accepted answer: http://stackoverflow.com/a/48576273
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84147463
has comment: http://stackoverflow.com/comment/84147261
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/84148862
tagged with: qradiobutton
has title: PyQt [QTreeWidget]: How to add Radiobutton for items?
has comment: http://stackoverflow.com/comment/84148892
has comment: http://stackoverflow.com/comment/84147518
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84147251
upvote count: 2
has body: To this question I am referring to the answer from @Andy PyQt Tree Widget, adding check boxes for dynamic removal There @Andy shows how to add CheckBox into the QTreeWidget, which works perfect. I would like ask here, how to add RadioButton into QTreeWidget? ----And, which is more difficult for me, how to make only one item selectable, although they are in different groups? I rewrite the code from @Andy into PyQt5: from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys def main(): app = QApplication (sys.argv) tree = QTreeWidget () headerItem = QTreeWidgetItem() item = QTreeWidgetItem() for i in range(3): parent = QTreeWidgetItem(tree) parent.setText(0, "Parent {}".format(i)) parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable) for x in range(5): child = QTreeWidgetItem(parent) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, "Child {}".format(x)) child.setCheckState(0, Qt.Unchecked) tree.show() sys.exit(app.exec_()) if __name__ == '__main__': main() The running result of the code above: UPDATE: The desired result should be like as followings... Any help will be highly appreciated! Thanks!
has answer: http://stackoverflow.com/a/48576273
downvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84147465
has comment: http://stackoverflow.com/comment/84147229
has comment: http://stackoverflow.com/comment/84147215
linked to: http://stackoverflow.com/q/31342228
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/48615403
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48615325
has body: You are trying to print strings, not your arguments. If you need to iterate through your function arguments, you can do something like this: Code: def printer(*args): for arg in args: print(arg, end="") printer('Hello', 'world') Results: Helloworld
downvote count: 0
type: Answer

http://stackoverflow.com/q/48522725
tagged with: deque
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/48522890
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84040216
has body: So I am making this program and I would like to get a list value from a thread outside of the thread. With the queue module I can get a value, but not a list. Deque seems to do what I want, but only works if the deque is being read inside another thread. What I got so far: from collections import deque import datetime values = deque() def addValues(values): while True: found = 1 now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') values.append((found,now)) time.sleep(5) t1 = threading.Thread(target=addValues, args=(values,)) t1.start() while True: print(values) time.sleep(5) At the moment it just prints an empty deque. I want it to print the deque with the added values EDIT: Nevermind, I asked the wrong question. The whole thread should be in a Flask site. when I at return to the while True, than it doesn't return anything. Sorry, I will make another question for this
has title: Python return deque from outside thread
tagged with: queue
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48522890
tagged with: python-3.x

http://stackoverflow.com/q/48521983
has answer: http://stackoverflow.com/a/48568269
tagged with: multiple-processes
tagged with: docker
has body: I am new to docker, trying to run multiple python processes in docker. Though it's not recommended, however, it should work as suggested here "https://docs.docker.com/engine/admin/multi-service_container/" My Dockerfile : FROM custom_image MAINTAINER Shubham RUN apt-get update -y COPY . /app WORKDIR /app RUN pip install -r requirements.txt ENTRYPOINT ["/bin/bash"] CMD ["start.sh"] start.sh : nohup python flask-app.py &amp; nohup python sink.py &amp; nohup python faceConsumer.py &amp; nohup python classifierConsumer.py &amp; nohup python demo.py &amp; echo lastLine run command : docker run --runtime=nvidia -p 5000:5000 out_image the same shell script worked when I go to terminal and run. tried without nohup, didn't work. tried python subprocess also to start other python processes, didn't work. Is it possible to run multiple processes without supervisord or docker-compose? update: not getting any error, only "lastLine" is getting printed and docker container exits.
type: AnsweredQuestion
answer count: 3
has title: Running Multiple python processes in Docker
accepted answer: http://stackoverflow.com/a/48522116
downvote count: 0
tagged with: shell
possible better answer: http://stackoverflow.com/a/48568269
has answer: http://stackoverflow.com/a/48545639
has answer: http://stackoverflow.com/a/48522116
tagged with: dockerfile
favorite count: 0
type: Question
score: 5
upvote count: 5
tagged with: python

http://stackoverflow.com/a/48517366
score: 3
has comment: http://stackoverflow.com/comment/84059279
has body: How do you know it runs only once? Have you debugged it or do you expect to have the correct result when code reaches this part? with open('datafile.csv', 'r') as fp: .... And in general, what do you expect to happen, and when is your program supposed to enter this part? I do not know how to fix this without knowing what you want it to do, but I think I know where your problem is. This is what your program does. I will call the main thread M: M: if __main__() matches and parseXML is called M: parseXML launches a new thread, which we call T1, with threading.Timer() M: parseXML finishes and with open... reached. T1: sleep(5) M: print(data_read) T1: still probably in sleep(5) M: exit - just waits for other threads to terminate T1: parseXML M: - T1: launches a new thread T2 M: - T1: completes parseXML T2: sleep(5) M: - T1: thread exits T2: still in sleep(5) M: - T1: - T2: parseXML M: - T1: - T2: launches a new thread T3 ... How your program is built, parseXML (probably - not able to run your code but it looks about right) does launch a delayed copy of itself in a new thread, but your main program that handles the results has already exited and does not read your datafile.csv anymore after a new timed thread has modified it. You can verify this by setting daemon=True on your threads (meaning the threads will exit as soon as your main program exits). Now your program does not "hang". It displays results after the first iteration of parseXML and it kills immediately the timed thread: #Parse the xml _t = threading.Timer(5.0, parseXML) _t.daemon = True _t.start() with urllib.request.urlopen(....) Do you really need threads here at all? Or could you just move the datafile.csv processing and display to parseXML, put a while True loop there and sleep 5 seconds between iterations? Another possibility is to move the data reader part to another thread that would sleep N seconds and then run the reader. BUT in this case you will need locks. If you process the same file in different…
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/84072823
has comment: http://stackoverflow.com/comment/84059479
has comment: http://stackoverflow.com/comment/84059334
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84073061
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48514640
has comment: http://stackoverflow.com/comment/84077701
answers question: http://stackoverflow.com/q/48514640

http://stackoverflow.com/comment/84234132
score: 0
has text: I haven't used websockets, so this is a comment rather than an answer. The problem might be that `add_audience_member` has _exited_ too soon. Instead. Try adding `await asyncio.Event()` at the end of `add_audience_member` and see if it fixes the problem. If it does, then you would store the even somewhere and use its `set()` method to cause `add_audience_member` to exit and remove the member from the global audience list. (A more proper name for the function would then be `communicate_with_audience_member`.)
type: QuestionComment
comment on: http://stackoverflow.com/q/48615031
type: Comment

pdf-generation
tags question: http://stackoverflow.com/q/48595018
tag name: pdf-generation
type: Tag

http://stackoverflow.com/a/48600433
answers question: http://stackoverflow.com/q/48600308
score: 0
has comment: http://stackoverflow.com/comment/84197612
has comment: http://stackoverflow.com/comment/84197684
has body: SettingWithCopyWarning was created to flag chained assignments, which are discouraged for reasons provided in pandas documentation. The documentation also includes the warning: The chained assignment warnings / exceptions are aiming to inform the user of a possibly invalid assignment. There may be false positives; situations where a chained assignment is inadvertently reported. In my view, your logic and what you expect from it is clear. To disable the warning you can use: pd.options.mode.chained_assignment = None # default='warn' You may wish to disable it only for the part of your code which uses groupby + transform operations, so that useful warnings are not missed.
type: Answer

http://stackoverflow.com/a/48630899
upvote count: 2
has comment: http://stackoverflow.com/comment/84258874
has comment: http://stackoverflow.com/comment/84258933
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/84259352
has body: You can use a generater-comprehension with str.join. I believe that this is the most efficient solution: def alternate(s): return ''.join(c.upper() if i &amp; 1 else c.lower() for i, c in enumerate(s)) and a test shows it works: &gt;&gt;&gt; alternate('testing') 'tEsTiNg'
answers question: http://stackoverflow.com/q/48630603
type: Answer

http://stackoverflow.com/a/48541770
score: 0
answers question: http://stackoverflow.com/q/48541552
type: Answer
has body: Your code is not a valid python dictionary. This is a valid dictionary: dict = { 'a': ([2,4],[5,6]), 'b': ([1,1],[1,7,9],[6,2,3]), 'c': ([a],[4,5]) } Use tuples to group multi-value items with fixed size (they have better performance than lists). The answer to the question, using the correct dictionary, is sum([len(e) for e in dict.values()])

http://stackoverflow.com/comment/84023363
type: Comment
type: QuestionComment
score: 0
has text: Thanks for all of the answers
comment on: http://stackoverflow.com/q/48514282

http://stackoverflow.com/a/48575127
downvote count: 0
has comment: http://stackoverflow.com/comment/84147171
upvote count: 5
answers question: http://stackoverflow.com/q/48574930
type: Answer
has comment: http://stackoverflow.com/comment/84155879
has comment: http://stackoverflow.com/comment/84147073
has comment: http://stackoverflow.com/comment/84147069
has body: The array array([ 151.26, 132.18, 131.64, 146.55, 147.87, 137.87]) is the equilibrium of your system (approximately). You can find this by setting the right-hand side of your system of equations to 0, which leads to Teq = inv(K)*Q: In [9]: Teq = np.linalg.solve(K, Q) In [10]: Teq Out[10]: array([ 151.25960795, 132.17972469, 131.6402527 , 146.55025359, 147.87025015, 137.87029892]) That's why your solution appears to be stable when you use these values for the starting point. The solution is very close to the equilibrium, so it doesn't change much. Long term, however, the solution will eventually diverge away from Teq, because that equilibrium point is unstable. Your system, T' = inv(C)*(Q - K*T), is linear in T, so you can determine the stability by computing the eigenvalues of the coefficient matrix of T. That is, write T = inv(C)*Q - inv(C)*K*T. The coefficient matrix of T is -inv(C)*K. Here's how you can find the eigenvalues of that matrix: In [11]: A = -C_invers.dot(K) In [12]: np.linalg.eigvals(A) Out[12]: array([-0.2089754 , 0.12257481, -0.06349952, -0.01489581, 0.00146708, 0.05878143]) The coefficent matrix A has three positive eigenvalues. Those correspond to modes that will grow exponentially in time. That is, the equilibrium is unstable, so the growth that you see is to be expected.
score: 5

http://stackoverflow.com/a/48651318
accepted answer of: http://stackoverflow.com/q/48579134
score: 0
has body: To load matrices from a .mat file into a PCollection, derive a PTransform wrapper around scipy.io.loadmat from beam.Create: class LoadMat(beam.Create): def __init__(self, file_name, mdict=None, appendmat=True, **kwargs): mat_dict = scipy.io.loadmat(file_name, mdict, appendmat, **kwargs) super(LoadMat, self).__init__([mat_dict]) Call this transform as follows: with beam.Pipeline(options=pipeline_options) as p: matrices = (p | 'LoadMat' &gt;&gt; LoadMat(FileSystems.open(known_args.input)) | ...)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48579134
type: Answer

http://stackoverflow.com/q/48558968
has title: delete session of a specific user in django?
score: 1
answer count: 1
has body: I am trying to delete the session of some specific user in Django.The code seems to run perfectly fine but I believe session is not deleted as the user is still logged in. The code I am using to delete session is:- user = User.objects.get(id=id) for s in Session.objects.all(): if s.get_decoded().get('_auth_user_id') == user.id: s.delete()
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/62115489
type: UnansweredQuestion
tagged with: session
tagged with: django
tagged with: python

http://stackoverflow.com/q/48625279
linked to: http://stackoverflow.com/q/14463277
tagged with: time-series
accepted answer: http://stackoverflow.com/a/48625856
tagged with: python
has answer: http://stackoverflow.com/a/48625856
has body: I am doing some statistical tests using the Dickey-Fuller method. After I made the import: from statsmodels.tsa.stattools import adfuller I am receiving this FutureWarning: /env/lib/python3.5/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead. from pandas.core import datetools The thing is I can't find the implementation for the adfuller() in pandas.tseries as mentioned in the deprecation warning. Statsmodels version is statsmodels==0.8.0 Any clues how to solve this?
has comment: http://stackoverflow.com/comment/84247588
score: 2
type: AnsweredQuestion
has title: Python statmodels lib deprecation warning
tagged with: pandas
upvote count: 2
has comment: http://stackoverflow.com/comment/84248212
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: statistics
tagged with: python-3.x

http://stackoverflow.com/q/48642096
has answer: http://stackoverflow.com/a/48649701
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/84280845
has comment: http://stackoverflow.com/comment/84281362
type: AnsweredQuestion
score: 1
tagged with: web-scraping
has title: How to set the size for Amazon product page using selenium?
has comment: http://stackoverflow.com/comment/84294613
favorite count: 0
has body: I made a python program and I would like to set the size of the product to click on the add to cart button. So to enable I should set the size. How can I set the size using selenium keys? Also, I would like this program to work for products that don't require to set the size, this program is working for this kind of products(for example this product) So I would like to set the size to enable add to cart. The code should be after this line (driver.get(url)). I attached the program. I will appreciate any help. from selenium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys proxies = { 'http': 'http://217.119.82.14:8080', 'https': 'http://196.27.107.30:8080', } url = "https://www.amazon.com/Disney-Stitch-Surfer-Adult-T-shrt/dp/B072VPQ1BG/ref=sr_1_4?ie=UTF8&amp;qid=1517916607&amp;sr=8-4&amp;keywords=t+shrt" chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=%s' % proxies) driver = webdriver.Chrome(executable_path="C:\\Users\Andrei\Downloads\chromedriver_win32\chromedriver.exe", chrome_options=chrome_options) driver.get(url) driver.find_element_by_xpath('//*[@id="submit.add-to-cart"]/span/input').click()
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/48649672
answer count: 2
has comment: http://stackoverflow.com/comment/84281517
accepted answer: http://stackoverflow.com/a/48649701
tagged with: python
has answer: http://stackoverflow.com/a/48649672
has comment: http://stackoverflow.com/comment/84294417
downvote count: 1
has comment: http://stackoverflow.com/comment/84280970

http://stackoverflow.com/comment/84223868
type: Comment
has text: How does this solve the *I want to call it like a function*?
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48613532

http://stackoverflow.com/q/48504649
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/84004336
has comment: http://stackoverflow.com/comment/84004459
answer count: 2
has title: Django url patterns, redirect from root to other url
has body: This should be an easy enough problem to solve for you guys: I just started working with Django, and I'm doing some routing. This is my urls.py in the root of the project: urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')), ] This is the routing in my dashboard app: urlpatterns = [ path('dashboard', views.index, name='index'), path('', views.index, name='index'), ] Now let's say I want my users to be redirected to /dashboard if they go to the root of the website. So I would use '' as a route in the urls.py in the root, and then have everyone sent to /dashboard from the urls.py in the dashboard app. But when I do this I get the following warning: ?: (urls.W002) Your URL pattern '/dashboard' [name='index'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. So I tried to use '/' instead of '', but since a trailing / is automatically removed from an url, the url wouldn't match the pattern. Should I ignore/mute this warning or is there another way to go about it? This is the code that worked perfectly but gave me a warning earlier: urlpatterns = [ path('/dashboard', views.index, name='index'), path('', views.index, name='index'), ] urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')) ]
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48504747
has comment: http://stackoverflow.com/comment/84004607
tagged with: django
tagged with: python
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48505513
score: 3
has comment: http://stackoverflow.com/comment/84004719
has comment: http://stackoverflow.com/comment/84003523

http://stackoverflow.com/comment/84281700
type: AnswerComment
score: 1
has text: I just can have some ideas, like find a way to draw the circle and for each predictions location you ask IF the location is inside the circle then you show it, if not the don't show it, I think there are methods for this but can't remember by heart. If i find something ill let you know
comment on: http://stackoverflow.com/a/48642536
type: Comment

http://stackoverflow.com/q/48613494
type: Question
has title: How to convert old-style Fortran DO loop with conditionals to Python?
has answer: http://stackoverflow.com/a/48613615
accepted answer: http://stackoverflow.com/a/48613615
has comment: http://stackoverflow.com/comment/84224267
tagged with: fortran
score: -2
has body: My question is about converting Fortran to Python language but I couldn't understand the working principle of this part of code. How can I rewrite the code in Python and which statement should I use instead of do if then write statement ? #FOR GEAR CONVEX SIDE I = l, FOR GEAR CONCAVE SIDE I = 2. DO 99999 I=1,2 IF(I .EQ. 1)THEN WRITE (72,*)'GEAR CONVEX SIDE' DLTA=DLTX M21PRM=M21XPR AXIL=AXILX ELSE WRITE(72,*)'GEAR CONCAVE SIDE' DLTA=DLTV M21PRM=M21VPR END IF WRITE (72, *) AXIA=DEF/(AXIL*AXIL) #CALCULATE GEAR BLADE ANGLE IF(I .EQ. 2)THEN PSIG=180. D00*CNST-PSIG END IF CSPSIG=DCOS(PSIG) SNPSIG=DSIN(PSIG) CTPSIG=CSPSIG/SNPSIG ##CALCULATE CUTTER TIP RADIUS IF(I .EQ. 1)THEN RG = (ADIA-W)/2.DO0 ELSE RG = (ADIA+W)/2.D00 END IF It is just a part of the main code and I couldn't understand the DO 9999 i=1,2 section and the following code (the relation of if, then and write).
tagged with: python
tagged with: code-translation
has comment: http://stackoverflow.com/comment/84224242
downvote count: 4
has comment: http://stackoverflow.com/comment/84223753
upvote count: 2
type: AnsweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/84223970
favorite count: 0

http://stackoverflow.com/comment/84144987
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48574059
type: Comment
has text: I would guess that this would beat apply in terms of speed. Also, note that creating a list for each row leads to additional memory overhead.

http://stackoverflow.com/comment/84174964
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48587769
type: Comment
has text: Well, it is simply incorrect, so readability may count, but correctness is more important. `is` is only interchangable with `==` if you are working with singleton's, which are pretty rare in Python, but could include `None`, module-objects, and class objects.

http://stackoverflow.com/comment/106398290
type: QuestionComment
type: Comment
has text: Not for me.... I'm still looking.
score: 0
comment on: http://stackoverflow.com/q/48506093

http://stackoverflow.com/comment/84245264
comment on: http://stackoverflow.com/q/48610767
type: Comment
score: 0
has text: Btw, one can discard the threading in those SO posts for my needs. I'm looking for a synchronous/blocking solution, not a real time ui stream. The value of those examples is just in how one can poll both streams independently in pseudo real-time and thus sort of determine the order of events.
type: QuestionComment

static-libraries
tag name: static-libraries
tags question: http://stackoverflow.com/q/48545255
type: Tag

http://stackoverflow.com/comment/84113148
has text: Would you like to get documents or specific entries of `entries` array?
type: Comment
comment on: http://stackoverflow.com/q/48558665
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84181004
has text: @ Barmar yes sorry I don't do this str conversion its actually a logical test of a numpy array value, I used str(x) to simplify the post.
type: QuestionComment
comment on: http://stackoverflow.com/q/48591755
type: Comment
score: 0

http://stackoverflow.com/q/48605961
score: 2
tagged with: numpy
tagged with: random
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48606040
has answer: http://stackoverflow.com/a/48606040
has title: how to change the datatype of numpy.random.rand array in python?
has body: I'm learning Numpy module from scratch going through the official Numpy documentation. Now my goal is to create a random (3, 3) array. &gt;&gt;&gt; np.random.rand(3,3) However the output I recieved is a bunch of random float values. array([[ 0.33519419, 0.53502883, 0.35485002], [ 0.73419236, 0.85315716, 0.64135169], [ 0.51732791, 0.27411508, 0.32482598]]) I wonder how can I do the same with int Referring the Official documentation of Numpy for the numpy.random.rand here I don't find a clue on converting or specifying the data type from float values to integer. How can I achieve random values in int?
tagged with: python
type: Question

http://stackoverflow.com/q/48621360
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84249438
has answer: http://stackoverflow.com/a/48625510
accepted answer: http://stackoverflow.com/a/48625510
has body: I was browsing the python asyncio module documentation this night looking for some ideas for one of my course projects, but I soon find that there might be a lack of feature in python's standard aysncio module. If you look through the documentation, you'll find that there's a callback based API and a coroutine based API. And the callback API could be used for building both UDP and TCP applications, while it looks that the coroutine API could only be used for building TCP application, as it utilizes the use of a stream-style API. This quite causes a problem for me because I was looking for a coroutine-based API for UDP networking, although I did find that asyncio supports low-level coroutine based socket methods like sock_recv and sock_sendall, but the crucial APIs for UDP networking, recvfrom and sendto are not there. What I wish to do is to write some codes like: async def handle_income_packet(sock): await data, addr = sock.recvfrom(4096) # data handling here... await sock.sendto(addr, response) I know that this could be equivalently implemented using a callback API, but the problem here is that callbacks are not coroutines but regular functions, so that in it you cannot yield control back to the event loop and preserve the function execution state. Just look at the above code, if we need to do some blocking-IO operations in the data handling part, we won't have a problem in the coroutine version as long as our IO operations are done in coroutines as well: async def handle_income_packet(sock): await data, addr = sock.recvfrom(4096) async with aiohttp.ClientSession() as session: info = await session.get(...) response = generate_response_from_info(info) await sock.sendto(addr, response) As long as we use await the event loop would take the control flow from that point to handle other things until that IO is done. But sadly these codes are not usable at this moment because we do not have a coroutined version of socket.sendto and socket.recvfrom in asyncio. What we cou…
score: 18
downvote count: 1
has answer: http://stackoverflow.com/a/75123667
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/48629007
linked to: http://stackoverflow.com/q/34040658
tagged with: python-asyncio
has title: Does asyncio from python support coroutine-based API for UDP networking?
has comment: http://stackoverflow.com/comment/84249792
has comment: http://stackoverflow.com/comment/84245173
has answer: http://stackoverflow.com/a/67557650
possible better answer: http://stackoverflow.com/a/67557650
tagged with: python
answer count: 4

http://stackoverflow.com/comment/84061491
has text: @SethMMorton `namedtuples` are not tuples, but a subclass of the tuples.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48532751

http://stackoverflow.com/q/48640739
tagged with: python-typing
favorite count: 0
score: 30
upvote count: 30
has answer: http://stackoverflow.com/a/69215932
type: Question
tagged with: mypy
has comment: http://stackoverflow.com/comment/119202826
has comment: http://stackoverflow.com/comment/116224737
has comment: http://stackoverflow.com/comment/84278978
has comment: http://stackoverflow.com/comment/92309185
type: UnansweredQuestion
has title: Inherit generic type in python 3 with typing
tagged with: python
has answer: http://stackoverflow.com/a/68111192
answer count: 2
has body: I'm doing some experiments with typing in Python 3.6 and mypy. I want to design an entity class that can be instantiated in two ways: By the use of an ordinary initializer (p = Person(name='Hannes', age=27)) Statically from a state object (p = Person.from_state(person_state)). The Entity class, from which Person derives, has the state class as a generic parameter. However, when validating the code with mypy, I receive an error that Person.from_state doesn't pick up the state type from the class it inherits from: untitled2.py:47: error: Argument 1 to "from_state" of "Entity" has incompatible type "UserState"; expected "StateType" I thought that by inheriting from Entity[UserState], StateType would be bound to UserState and the method signatures in the child classes would update accordingly. This is the full code. I have marked the line where I suspect I'm doing things wrong with ?????. Line 47 is almost at the bottom and marked in the code. from typing import TypeVar, Generic, NamedTuple, List, NewType EntityId = NewType('EntityId', str) StateType = TypeVar('StateType') class Entity(Generic[StateType]): id: EntityId = None state: StateType = None @classmethod def from_state(cls, state: StateType): # ????? ret = object.__new__(cls) ret.id = None ret.state = state return ret def assign_id(self, id: EntityId) -> None: self.id = id class UserState(NamedTuple): name: str age: int class User(Entity[UserState]): def __init__(self, name, age) -> None: super().__init__() self.state = UserState(name=name, age=age) @property def name(self) -> str: return self.state.name @property def age(self) -> int: return self.state.age def have_birthday(self) -> None: new_age = self.state.age+1 self.state = self.state._replace(age=new_age) # Create first object with constructor u1 = User(name='Anders', age=47) # Create second object from state user_state = UserState(name='Hannes', age=27) u2 = User.from_state(user_state) # Line 47 print(u1.state) print(u2.state)
downvote count: 0
has comment: http://stackoverflow.com/comment/117185274
has comment: http://stackoverflow.com/comment/84278734
tagged with: generics

del
tag name: del
tags question: http://stackoverflow.com/q/48490503
type: Tag

http://stackoverflow.com/comment/83978926
type: Comment
comment on: http://stackoverflow.com/a/48492694
type: AnswerComment
score: 1
has text: Actually never mind I figured it out! I had to do (first,), (second1,second2), third for the unpacking since the second tuple has two values! Thank you for the detailed explanation

http://stackoverflow.com/comment/84021412
has text: @DYZ, ah got you. The name is the parameter only, not the actual result.
comment on: http://stackoverflow.com/a/48513132
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48552397
has comment: http://stackoverflow.com/comment/84103339
has comment: http://stackoverflow.com/comment/84102119
has title: encrypted password file which expires after 24 hours
has comment: http://stackoverflow.com/comment/84102438
type: UnansweredQuestion
tagged with: encryption
has comment: http://stackoverflow.com/comment/84102919
tagged with: python
has comment: http://stackoverflow.com/comment/84101551
has comment: http://stackoverflow.com/comment/84103020
has body: I am using python scripts to login to various sites to download sensitive data. Password credentials are passed to the scripts when they are run. Is it possible to have the password read from an encrypted file? Further, can that encrypted password file 'expire' after say 24 hours? USE Case 1: Deploy the script to production without hard coding the password in a batch file (windows/azure/python/SQL Server) In this case the encrypted password file is set to never expire. USE Case: I give an existing script to developer who must modify it against the production site (in this case the production site is the site where I download the sensitive data). I can NOT change my password at the target site. Assume the developer will not need to login to the site to do the work; when the developer runs python-selenium script, it logs in using the encrypted password file the developer will see enough to identify where it breaks then make the modifications.
tagged with: passwords
score: 0
answer count: 0
tagged with: selenium
type: Question

http://stackoverflow.com/q/48564834
tagged with: google-app-engine
upvote count: 3
has answer: http://stackoverflow.com/a/48564924
has answer: http://stackoverflow.com/a/56054799
has title: import cloudstorage, ImportError: No module named google.appengine.api
linked to: http://stackoverflow.com/q/42338094
tagged with: python
tagged with: google-cloud-storage
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90760211
possible better answer: http://stackoverflow.com/a/56054799
accepted answer: http://stackoverflow.com/a/48565916
linked to: http://stackoverflow.com/q/48560171
downvote count: 0
has body: I would like to use Google Cloud Storage Client Library Functions. For that I have to import the cloudstorag. To get the cloudstorage I download Google Cloud Storage client library. I try to import cloudstorage using python -c "import cloudstorage". I get the following error: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "cloudstorage/__init__.py", line 20, in &lt;module&gt; from .api_utils import RetryParams File "cloudstorage/api_utils.py", line 45, in &lt;module&gt; from google.appengine.api import app_identity ImportError: No module named google.appengine.api Am I missing something?
has answer: http://stackoverflow.com/a/48565916
has comment: http://stackoverflow.com/comment/84126686
type: AnsweredQuestion
score: 3
answer count: 3

http://stackoverflow.com/q/48552475
tagged with: python-3.x
has body: In this link, I want to get 302621221479 from the url, Can I do it faster? I am asking for learning how to improve my code not how to do it. url = 'https://www.ebay.com/itm/Deep-V-Neck-Sequin-Bodycon-Cocktail-Dress-Women-Clubwear-Sexy-Party-Dress-/302621221479?var=&amp;hash=item8c09eb2518' u = url.split('/') id_product = u[-1].split('?') print(id_product[0])
has title: How to get the number after certain slash faster in string?
score: -2
tagged with: python
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/84101420
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48639481
answer count: 1
tagged with: web-scraping
favorite count: 0
type: Question

http://stackoverflow.com/q/48573715
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48573763
tagged with: pandas
upvote count: 3
has body: I have a pandas df containing a time series, and from t(0), I need to look ahead to t(n) and see what are the maximum and minimum values that are ahead, in a slice of size defined by columns “from” and “to”. This is my df: This is my solution, which works but it is extremely slow: df[‘max_ahead’] = df.apply(lambda x: df[‘value’][int(df[‘from’]):int(df[‘to’])].max(), axis=1) df[‘min_ahead’] = df.apply(lambda x: df[‘value’][int(df[‘from’]):int(df[‘to’])].min(), axis=1) Is there a way to speed this up in pandas or a numpy array? My df contains millions of rows, and the code above takes too long.
has title: Efficient way to “look ahead” values in a pandas df
favorite count: 0
type: Question
tagged with: numpy
tagged with: time-series
answer count: 2
accepted answer: http://stackoverflow.com/a/48573763
has answer: http://stackoverflow.com/a/48573764
possible better answer: http://stackoverflow.com/a/48573764
has comment: http://stackoverflow.com/comment/84144228
downvote count: 0

http://stackoverflow.com/q/48511766
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: conditional-statements
tagged with: pandas
has title: Conditional Function to a pandas dataframe, if vs else change the value
tagged with: python
accepted answer: http://stackoverflow.com/a/48511802
type: Question
has answer: http://stackoverflow.com/a/48511802
has body: I been trying to get my code to work but I am having some trouble here. It would be great if someone could assist me DF Col1 Col2 2017-01-01 Coffee 2017-01-01 Muffin 2017-01-01 Donut 2017-01-01 Toast How can I change Col2 so that every value that isn't Coffee or Muffin becomes 'Other'? Col1 Col2 2017-01-01 Coffee 2017-01-01 Muffin 2017-01-01 Other 2017-01-01 Other
score: 1
answer count: 1

deployment
tags question: http://stackoverflow.com/q/48566256
tag name: deployment
tags question: http://stackoverflow.com/q/48501832
tags question: http://stackoverflow.com/q/48591476
type: Tag
tags question: http://stackoverflow.com/q/48545942

http://stackoverflow.com/comment/84183379
comment on: http://stackoverflow.com/q/48591045
type: Comment
score: 0
has text: Why do you need bs4? Does the form have dynamic fields? If not, just use `files` for your file and `data` for the rest inputs.
type: QuestionComment

http://stackoverflow.com/a/64689845
downvote count: 0
has body: You need to set the local image from the bot's root dir as an attachment and you need to mention the file in ctx.send aswell! I tried doing attachment only, but it shows a blank embed. So take mention the file and take the same file into the set_image as an attachment and try running the code. It works file = discord.File("output.png") e = discord.Embed() e.set_image(url="attachment://output.png") await ctx.send(file = file, embed=e) Let me know if you still face an issue!
upvote count: 9
type: Answer
score: 9
answers question: http://stackoverflow.com/q/48530423

http://stackoverflow.com/comment/84262342
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48632542
type: Comment
has text: True. but looking at the file in the example, i don't think that really matters.

http://stackoverflow.com/q/48588250
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84173908
has comment: http://stackoverflow.com/comment/84174069
has comment: http://stackoverflow.com/comment/84175298
tagged with: python
has comment: http://stackoverflow.com/comment/84174740
linked to: http://stackoverflow.com/q/48568649
score: 0
has comment: http://stackoverflow.com/comment/84173614
has answer: http://stackoverflow.com/a/48589494
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/84173864
has body: I have a python script that looks at a json file and lists variables to a CSV. The problem I am having is latitude and logitude are listed twice. Therefore, when I write the row, it looks at those variables and creates an output with duplicate values. import csv, json, sys def find_deep_value(d, key): # Modified from https://stackoverflow.com/questions/48568649/convert-json-to-csv-using-python/48569129#48569129 if key in d: return d[key] for k in d.keys(): if isinstance(d[k], dict): for j in find_deep_value(d[k], key): return j inputFile = open("pywu.cache.json", 'r') # open json file outputFile = open("CurrentObs.csv", 'w') # load csv file data = json.load(inputFile) # load json content inputFile.close() # close the input file output = csv.writer(outputFile) # create a csv.write # Gives you latitude coordinates from within the json lat = find_deep_value(data, "latitude") # Gives you longitude coordinates from within the json lon = find_deep_value(data, "longitude") # Gives you a list of weather from within the json weather = find_deep_value(data, "weather") # Gives you a list of temperature_strings from within the json temp = find_deep_value(data, "temperature_string") output.writerow([lat, lon, weather, temp]) outputFile.close() Is there a way to only list them once?
has title: List Multiples of the Same Variable only Once

http://stackoverflow.com/q/48592882
accepted answer: http://stackoverflow.com/a/48593613
downvote count: 0
tagged with: python
tagged with: travis-ci
has answer: http://stackoverflow.com/a/48593613
type: AnsweredQuestion
score: 2
tagged with: pytest
has title: Travis CI defaults to wrong language
answer count: 1
favorite count: 0
type: Question
tagged with: continuous-integration
upvote count: 2
has body: I have a very simple Python project and I'm trying to run tests using Travis CI. Here's my .travis.yml language: python python: - "3.6" # command to install dependencies install: - pip install -r python/01/requirements.txt script: - cd python/01 &amp;&amp; pytest And this is the output that Travis gives my build fails: Worker information hostname: f12d83b9-c642-4a3c-93fc-37744ce7a718@1.i-08a3b12-production-2-worker-org-ec2.travisci.net version: v3.4.0 https://github.com/travis-ci/worker/tree/ce0440bc30c289a49a9b0c21e4e1e6f7d7825101 instance: 96b6e8e travisci/ci-garnet:packer-1512502276-986baf0 (via amqp) startup: 444.820256ms mode of ‘/usr/local/clang-5.0.0/bin’ changed from 0777 (rwxrwxrwx) to 0775 (rwxrwxr-x) system_info Build system information Build language: ruby Build group: stable Build dist: trusty Build id: 336792661 Job id: 336792662 Runtime kernel version: 4.14.12-041412-generic travis-build version: c08e7e0bc Build image provisioning date and time Tue Dec 5 20:11:19 UTC 2017 Operating System Details Distributor ID: Ubuntu Description: Ubuntu 14.04.5 LTS Release: 14.04 Codename: trusty Cookbooks Version 7c2c6a6 https://github.com/travis-ci/travis-cookbooks/tree/7c2c6a6 git version git version 2.15.1 bash version GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu) gcc version gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 Copyright (C) 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. docker version Client: Version: 17.09.0-ce API version: 1.32 Go version: go1.8.3 Git commit: afdb6d4 Built: Tue Sep 26 22:39:28 2017 OS/Arch: linux/amd64 clang version clang version 5.0.0 (tags/RELEASE_500/final) Target: x86_64-unknown-linux-gnu Thread model: posix InstalledDir: /usr/local/clang-5.0.0/bin jq version jq-1.5 bats version Bats 0.4.0 shellcheck version 0.4.6 shfmt version v2.0.0 ccache version ccache version 3.1.9 Copyright (C) …

http://stackoverflow.com/comment/84262508
score: 1
type: QuestionComment
type: Comment
has text: Not a solution but a nit, you're not actually calculating the semantic similarity of two lists with this method. This in no way captures the _meaning_ of the two pieces of text and whether they are similar.
comment on: http://stackoverflow.com/q/48631791

http://stackoverflow.com/comment/84230419
type: AnswerComment
type: Comment
has text: thanks mohsen, for one of my project i designed a django middle-ware to do that, but it seems there is no django package for this problem
comment on: http://stackoverflow.com/a/48606217
score: 0

http://stackoverflow.com/a/56597071
score: 0
answers question: http://stackoverflow.com/q/48539900
type: Answer
has body: Installing Git Bash for Windows did it to me. After that, run the jupyter notebook from there.

http://stackoverflow.com/comment/84099261
has text: @Richard_wth Thanks! I've had lots of fun learning about leaky relus and elu's. I think I prefer the elu as I don't like having to set the parameter of the leaky relu. It makes me think of bowels.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48511365
type: Comment

http://stackoverflow.com/comment/84322253
score: 0
has text: @MarkDickinson Yes, that's a problem. The best thing I could think of is `round((round(1.09*100)/2))/100 == 0.54`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48659524

http://stackoverflow.com/comment/84252511
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48611973
type: Comment
has text: Did you use the same data ?... Try using a sigmoid layer before softmax.... Use tf.clip ... Use dropouts

http://stackoverflow.com/comment/84202216
has text: @Robert no way to get (B,B) from your reduced list.
type: Comment
comment on: http://stackoverflow.com/q/48602709
type: QuestionComment
score: 1

http://stackoverflow.com/comment/84106286
comment on: http://stackoverflow.com/q/48554606
score: 0
type: Comment
type: QuestionComment
has text: @KlausD. using version of Django 2.0.1

http://stackoverflow.com/q/48561960
type: UnansweredQuestion
has body: Looking for a tag that I could parse either in Python and in some other languages without bugging anything, I found this strange thing In [15]: print('standard python') In [16]: //#:: ...: ...: hello ...: print('hey') ...: exit() ...: ...: seems to wait for something ...: &amp; I have no idea what ??? ...: Anybody got any clue?
tagged with: tags
has comment: http://stackoverflow.com/comment/84119949
tagged with: python
has comment: http://stackoverflow.com/comment/117983500
has answer: http://stackoverflow.com/a/59363796
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: ipython
favorite count: 0
type: Question
has title: python mysterious command //#::

http://stackoverflow.com/comment/84052231
comment on: http://stackoverflow.com/a/48528391
score: 0
type: AnswerComment
has text: regex is used to split by words
type: Comment

http://stackoverflow.com/q/48495282
downvote count: 0
type: UnansweredQuestion
has title: Camera calibration Open CV-Python
has answer: http://stackoverflow.com/a/52921427
tagged with: camera-calibration
favorite count: 0
type: Question
tagged with: opencv
score: 2
has comment: http://stackoverflow.com/comment/100321454
has body: I'm trying to do camera calibration, I have taken the code from open cv documentation. Here is my code - import numpy as np import cv2 import glob criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) objp = np.zeros((6*7,3), np.float32) objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2) objpoints = [] imgpoints = [] images = glob.glob('/usr/local/share/OpenCV/samples/cpp/chess*.jpg') img = cv2.imread("2.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret = False ret, corners = cv2.findChessboardCorners(gray, (7, 6)) print (ret) if ret == True: objpoints.append(objp) cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria) imgpoints.append(corners) # Draw and display the corners cv2.drawChessboardCorners(img, (7,6), corners, ret) cv2.imshow('img',img) cv2.imwrite('Corners_detected.jpg', img, None) cv2.waitKey(0) cv2.destroyAllWindows() ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None) img = cv2.imread('2.jpg') h, w = img.shape[:2] newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h)) # undistort dst = cv2.undistort(img, mtx, dist, None, newcameramtx) cv2.imwrite('calibration_result.png',dst) In this code image 2.jpg is taken for calibration, This is the image considered for understanding of calibration My code is detecting corners for only this image. It is not working fine with other checker board image.It is not able to detect corners. Why is it so ?
tagged with: python
has answer: http://stackoverflow.com/a/57086089
upvote count: 2
answer count: 2

http://stackoverflow.com/q/48640098
has title: Regex also takes index with for loop
favorite count: 0
has answer: http://stackoverflow.com/a/48641238
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/48641231
tagged with: regex
has comment: http://stackoverflow.com/comment/84277195
has answer: http://stackoverflow.com/a/48641231
has comment: http://stackoverflow.com/comment/84277618
has comment: http://stackoverflow.com/comment/84277186
has comment: http://stackoverflow.com/comment/84276737
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84276831
upvote count: 3
score: 3
has body: The following regex does exactly what I want it to do, except that it also outputs the index as a digit ( I think it's the index). This messes up my output. So how can I tell it not to take the index ? import re import pandas as pd df = pd.read_excel("tstfile.xlsx", names=["col1"]) for index, row in df.iterrows(): # print(index) if str(row[0]).split(): if not re.findall("(.[A-Z]\d+\-\d+)", str(row)): for i in re.findall("(\d+)", str(row)): print(i) Input data would look like: 123, 456 111 * 222 LL123-456 35 I get an output that looks like this: 123 0 456 1 111 2 222 3 35 4 The final desired output should be: 123 456 111 222 35 So only the data that is actually given in as input.
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48641238

http://stackoverflow.com/comment/83976394
has text: @CEamonn: I added some more explanation. Hope that helps :)
type: Comment
comment on: http://stackoverflow.com/a/48491179
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84105286
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48552986
type: Comment
has text: Thank you, roganjosh! But I still get an error message "name 'MFDataset" is not defined"

http://stackoverflow.com/comment/84168332
comment on: http://stackoverflow.com/q/48585577
has text: If you need to use the keys and values separately then use the first approach, this is the most common case for iterating over a `dict`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50403829
score: 2
type: Answer
answers question: http://stackoverflow.com/q/48544720
upvote count: 2
downvote count: 0
has body: The problem here (as you noticed) is likely that pysipp.client() sets the -sn uac flag and sipp fails having both -sn and -sf. To see the actual error you can enable logging before running the client: import pysipp pysipp.utils.log_to_stderr("DEBUG") uac = pysipp.client(destaddr=('mysipdomain.net', 5060)) uac.uri_username = '12345' uac.auth_password = '' uac.scen_file = './numeric.xml' uac() The hack is to simply do uac.scen_name = None but the proper way to do this is to either use pysipp.scenario() (docs here) and rename your numeric.xml to have uac in the file name (i.e. uac_numeric.xml) or use instead pysipp.ua(scen_file=&lt;path/to/numeric.xml&gt;). To understand the problem the client is currently applying a default scenario name argument when really the user should be able to override that (though in that case there'll be no guarantee that the user actually is sending client traffic which renders the name client kind of pointless).

http://stackoverflow.com/a/48641796
type: AcceptedAnswer
has body: The error message indicates that you can’t connect to the target machine (smtp.gmail.com): ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it I would suspect that you have some sort of firewall or anti-virus that blocks connections to the SMTP Submission Port as both the specified hostname (smtp.gmail.com) and port number are correct (587). There’s also an (unrelated) error in your code: s.starttls() should be server.starttls().
has comment: http://stackoverflow.com/comment/95251032
type: Answer
accepted answer of: http://stackoverflow.com/q/48640388
answers question: http://stackoverflow.com/q/48640388
score: 0

http://stackoverflow.com/q/48610130
score: 0
has comment: http://stackoverflow.com/comment/84216828
answer count: 1
has body: sorry for my nooby question; I had a python application with only functions but now I have to revise it with classes that I am not expert on. Here is my basic user Class; class User: def __init__(self,username,password,basket): self.username=username self.password=password self.basket=basket and the input function that I want to put inside the class; def Login(self): while True: username = raw_input('\nPlease log in by providing your user credentials \nUser Name :') if (username == users[0]['username'] or username == users[1]['username']): password = raw_input('Password : ') if (password == users[0]['password'] or password == users[1]['password']): print('Successfully logged in!') print ( 'Welcome,' + username + '! Please choose of the following options by entering the corresponding menu number.') global LoggedUserName LoggedUserName = username; return True; break; else: print('Your password is not correct. Please try again!') else: print ('Your username is not correct. Please try again!') Thank you for your precious helps!
has answer: http://stackoverflow.com/a/48610741
type: Question
has comment: http://stackoverflow.com/comment/84217367
tagged with: orientation
type: UnansweredQuestion
tagged with: python
tagged with: class
has title: Integrating login function inside a Class
has comment: http://stackoverflow.com/comment/84217292
tagged with: object

datetime
tags question: http://stackoverflow.com/q/48587595
tags question: http://stackoverflow.com/q/48560624
tags question: http://stackoverflow.com/q/48598599
tags question: http://stackoverflow.com/q/48565990
tags question: http://stackoverflow.com/q/48542674
tags question: http://stackoverflow.com/q/48621852
tags question: http://stackoverflow.com/q/48528519
tag name: datetime
tags question: http://stackoverflow.com/q/48527876
tags question: http://stackoverflow.com/q/48602954
tags question: http://stackoverflow.com/q/48612089
tags question: http://stackoverflow.com/q/48510058
tags question: http://stackoverflow.com/q/48535997
tags question: http://stackoverflow.com/q/48607132
tags question: http://stackoverflow.com/q/48588498
tags question: http://stackoverflow.com/q/48536493
tags question: http://stackoverflow.com/q/48599923
tags question: http://stackoverflow.com/q/48534114
tags question: http://stackoverflow.com/q/48567056
tags question: http://stackoverflow.com/q/48542954
tags question: http://stackoverflow.com/q/48591644
type: Tag
tags question: http://stackoverflow.com/q/48498467
tags question: http://stackoverflow.com/q/48553824
tags question: http://stackoverflow.com/q/48627387
tags question: http://stackoverflow.com/q/48619194
tags question: http://stackoverflow.com/q/48512090
tags question: http://stackoverflow.com/q/48489694
tags question: http://stackoverflow.com/q/48584465
tags question: http://stackoverflow.com/q/48589705
tags question: http://stackoverflow.com/q/48622150
tags question: http://stackoverflow.com/q/48515176
tags question: http://stackoverflow.com/q/48645217
tags question: http://stackoverflow.com/q/48626998
tags question: http://stackoverflow.com/q/48544798
tags question: http://stackoverflow.com/q/48632242
tags question: http://stackoverflow.com/q/48625899
tags question: http://stackoverflow.com/q/48515334
tags question: http://stackoverflow.com/q/48543979
tags question: http://stackoverflow.com/q/48617580
tags question: http://stackoverflow.com/q/48574003
tags question: http://stackoverflow.com/q/48638618
tags question: http://stackoverflow.com/q/48620587
tags question: http://stackoverflow.com/q/48640622
tags question: http://stackoverflow.com/q/48531163
tags question: http://stackoverflow.com/q/48631087
tags question: http://stackoverflow.com/q/48568243
tags question: http://stackoverflow.com/q/48602892
tags question: http://stackoverflow.com/q/48553847

http://stackoverflow.com/q/48632882
has answer: http://stackoverflow.com/a/51503182
has comment: http://stackoverflow.com/comment/84273349
type: AnsweredQuestion
tagged with: linux
tagged with: anaconda
upvote count: 7
has body: I create a virtual environment with conda $ conda create test_env numpy ..... It gets created successfully. $ conda env list # conda environments: # base * /home/myname/anaconda3 my_project_env /home/myname/anaconda3/envs/my_project_env test_env /home/myname/anaconda3/envs/test_env but I can not activate it $ source activate my_project_env returns - activate: No such file or directory The only place I find activate is within the whole anaconda3 is in /common folder source anaconda3/envs/my_project_env/lib/python3.6/venv/scripts/common/activate my_project_env When I run it with this path I get VENV_PROMPT "kind of environment" but when I check libraries with pip list it returns a global list of installed libraries instead of the selected few. $ source anaconda3/envs/my_project_env/lib/python3.6/venv/scripts/common/activate my_project_env __VENV_PROMPT__myname@box:~$ pip3 list
score: 7
tagged with: python
possible better answer: http://stackoverflow.com/a/51503182
has answer: http://stackoverflow.com/a/55862350
has answer: http://stackoverflow.com/a/51623576
has comment: http://stackoverflow.com/comment/84288275
answer count: 4
accepted answer: http://stackoverflow.com/a/51623576
has answer: http://stackoverflow.com/a/59936778
tagged with: conda
favorite count: 0
has comment: http://stackoverflow.com/comment/84288476
type: Question
has comment: http://stackoverflow.com/comment/84262952
has title: I can not activate virtual environment in conda
downvote count: 0
tagged with: virtualenv

http://stackoverflow.com/q/48610439
favorite count: 0
type: Question
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/48610827
has answer: http://stackoverflow.com/a/48610827
answer count: 1
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/17129947
has title: How to make xticklabel only the points of data list?
has body: I am creating a python application to show a Gantt chart of data list. But when I run the application I get this --> Actually, I need the xticklabels should only be the points in the data list at the same end point from the graph. Something similar to this--> (sorry for the poor picture edit) This what I have done so far: self.f = Figure(figsize=(10, 8), dpi=100) self.ax = self.f.add_subplot(2,1,2) ind = numpy.arange(1) # the x locations for the groups width = .95 data = [2,4,5,7,8,12,16] patch_handles = [] left = 1 for i, d in enumerate(data): patch_handles.append(self.ax.barh(ind, d, align='center', left=left, yerr=0.4, color='y')) left += d for j in range(len(patch_handles)): for i, patch in enumerate(patch_handles[j].get_children()): bl = patch.get_xy() x = 0.5 * patch.get_width() + bl[0] y = 0.5 * patch.get_height() + bl[1] self.ax.text(x, y, "dd", ha='center') self.ax.set_yticks(ind) self.ax.set_yticklabels("G") self.ax.set_xticklabels(data) self.ax.set_xlabel('Scores') canvas = FigureCanvasTkAgg(self.f, master=root) canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) EDIT: Screenshot after changing the codes from @scroopy noopers's the answer
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84225994
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84225960
downvote count: 1

http://stackoverflow.com/comment/84094233
has text: Amazing those are clickable! Thank you!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48535520

http://stackoverflow.com/comment/84273742
has text: add access right to this group for `hr.employee`
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48635607

http://stackoverflow.com/comment/83970810
score: 1
has text: Please show your code. We can't diagnose code we can't see. If your code is simply putting new buttons on top, then clearly, you're not destroying the old widgets.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48488902

http://stackoverflow.com/comment/84810839
comment on: http://stackoverflow.com/q/48641406
score: 0
has text: @wim Updated question with code. I've ended up using a python.fixture with scope='class' and using MonkeyPatch() form _pytest.monkeypatch import MonkeyPatch. I've posted my solution, but I'm happy to accept your if it's more elegant!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48525582
has comment: http://stackoverflow.com/comment/84048905
has title: Minimizing if statements in python function
linked to: http://stackoverflow.com/q/16789776
has answer: http://stackoverflow.com/a/48525705
type: Question
has body: I have following function, which takes values from pandas dataframe columns and supplies arguments(s0_loc,s1_loc,.. upto ..,s12_loc if and only if their respective s0,s1,s2...,s12 is not-null) to another function. Also It will check whether s1 is null or not if and only if s0 is not null... Similarly it will check whether s2 is null or not iff s0,s1 is not null.. So on.. Based on above criteria I have written following function. But it's lengthy function... I want to reduce the piece of code in this function. def compare_locality(p,p_loc,s0,s0_loc,s1,s1_loc,s2,s2_loc,s3,s3_loc,s4,s4_loc,s5,s5_loc,s6,s6_loc,s7,s7_loc,s8,s8_loc,s9,s9_loc,s10,s10_loc,s11,s11_loc,s12,s12_loc): loc = [] if s0 != '' : loc.append(s0_loc) if s1 != '' : loc.append(s1_loc) if s2 != '' : loc.append(s2_loc) if s3 != '' : loc.append(s3_loc) if s4 != '' : loc.append(s4_loc) if s5 != '' : loc.append(s5_loc) if s6 != '' : loc.append(s6_loc) if s7 != '' : loc.append(s7_loc) if s8 != '' : loc.append(s8_loc) if s9 != '' : loc.append(s9_loc) if s10 != '' : loc.append(s10_loc) if s11 != '' : loc.append(s11_loc) if s12 != '' : loc.append(s12_loc) if len(loc) == 0: return '' else: return compare(p_loc,*loc) Can I get any suggestion on how to achieve this??
answer count: 3
possible better answer: http://stackoverflow.com/a/48525637
has comment: http://stackoverflow.com/comment/84046392
downvote count: 0
has answer: http://stackoverflow.com/a/48525637
upvote count: 1
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48525774
tagged with: pandas
has comment: http://stackoverflow.com/comment/84081163
score: 1
has comment: http://stackoverflow.com/comment/84046120
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/48525705
has comment: http://stackoverflow.com/comment/84046094

http://stackoverflow.com/a/48566883
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48566406
accepted answer of: http://stackoverflow.com/q/48566406
type: Answer
upvote count: 1
has body: for ind, val in enumerate(str(mybinary)): ws.write(r, ind + 2, val) replacing your ws.write(r,2,mybinary) statement with above two lines will do your job.
score: 1

http://stackoverflow.com/comment/84130502
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48507879
score: 0
has text: Why don't you use "print sta1.params['rssi']", directly?

http://stackoverflow.com/comment/136193613
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/71068225
has text: Any solution to get the PROXY IP address Binded with WebDriver ?

http://stackoverflow.com/comment/84180815
has text: Here are a couple example websites: http://www.rickcaseacura.com http://www.goodsonacura.com http://www.edvoylesacura.com/
comment on: http://stackoverflow.com/a/48580729
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48505502
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84006189
has title: Output variable number of string values to rows within an excel worksheet
has comment: http://stackoverflow.com/comment/84007778
has answer: http://stackoverflow.com/a/48505664
accepted answer: http://stackoverflow.com/a/48505664
type: Question
has body: I'm "playing" little bit with python on a beginner level. My question: I created a xlsx workbook where I will write data which I have parsed in other files, First I do: myworkbook = xlsxwriter.Workbook('MyWorkbook.xlsx') worksheet = workbook.add_worksheet('MyWorksheet') Than after parsing my file, I have the data (type: str) of interest stored within my variable "X": print(X) 0x100 0x200 0x300 0x400 0x500 .. .. Just for information: print(type(X)): &lt;type 'str'&gt; &lt;type 'str'&gt; &lt;type 'str'&gt; &lt;type 'str'&gt; &lt;type 'str'&gt; Now I need just to output this data into myWorksheet The number of string values can be variable each time. i would like to output all these values one after each other to excel rows starting for example from B5 and than B5++ until there are values. Something like: worksheet.write_string('B5:Bn', X) Expected output in out.xlsx: B5 0x100 B6 0x200 B7 0x300 B8 0x400 B9 0x500 Bn 0x... What is the easiest way to do this?
has comment: http://stackoverflow.com/comment/84005061
has comment: http://stackoverflow.com/comment/84005128
answer count: 2
possible better answer: http://stackoverflow.com/a/48505989
tagged with: python
has answer: http://stackoverflow.com/a/48505989

http://stackoverflow.com/q/48644212
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: lda
has comment: http://stackoverflow.com/comment/84292402
type: UnansweredQuestion
has title: How to make dictionary of lda outputs and then save it into json
tagged with: python
tagged with: gensim
has comment: http://stackoverflow.com/comment/84293051
has comment: http://stackoverflow.com/comment/84293272
score: 0
has body: I am trying to save lda output in a dictionary, in which words and their probabilities will be keys and values and then save this dictionary in json but I don't know how to achieve this. When I simply try to save it in json it is some kind of binary format. Here is the code which I have tried so far: filename = sys.argv[1] lda = gensim.models.LdaModel(corpus, num_topics=num_topics, id2word=dictionary,alpha = 0.001, , passes=50,iterations=300) for i in range(0, lda.num_topics): with open(filename, 'w') as outfile: outfile.write(json.dumps('{}\n'.format('Topic #' + str(i + 1) + ': '))) for word, prob in lda.show_topic(i, topn=10): outfile.write(json.dumps('{}:{}\n'.format(word,prob))) outfile.write('\n')
answer count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84286831
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/84004382
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48505005
score: 1
has text: You can take a look [here](https://stackoverflow.com/questions/46329455/anaconda-an-unexpected-error-ocurred-on-navigator-start-up).

http://stackoverflow.com/q/48575889
has answer: http://stackoverflow.com/a/48575978
type: AnsweredQuestion
score: 0
has title: Python 3: subprocess, changing directory
possible better answer: http://stackoverflow.com/a/48575978
has body: I have a main project in C:/myproject/harry.py harry.py is launching threads. harry.py is saving and loading text documents every few seconds using an already established path self.relativePath = os.path.dirname(sys.argv[0]) Inside each thread, a subprocess is being called to activate a command line .exe file found in C:/myproject/betty/here.exe I have tried all sorts of things to achieve this such as: my_env = os.environ my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"] doit = subprocess.Popen('cd betty/', 'here.exe -command', env=my_env) doit.wait() or my_env = os.environ my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"] doit = subprocess.Popen('here.exe -command', cwd='C:/myproject/betty/') doit.wait() Response: FileNotFoundError: [WinError 2] The system cannot find the file specified Is it possible to run the subprocess inside the subfolder with the custom path ... that will not interfere with the already established path self.relativePath Thanks,
type: Question
tagged with: python-3.x
answer count: 2
tagged with: subprocess
accepted answer: http://stackoverflow.com/a/48611806
has answer: http://stackoverflow.com/a/48611806
tagged with: python

http://stackoverflow.com/comment/84243524
comment on: http://stackoverflow.com/a/48623059
has text: why not? What is the problem with it?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48542291
has comment: http://stackoverflow.com/comment/128130826
score: 0
has comment: http://stackoverflow.com/comment/84080164
has body: Yes it is bad practice. All of these decisions are very subjective and can be interpreted differently therefore I suggest reading the official PEP8 style guide. You can even include it with your editor to suggest changes! Another massive reason why this is really bad practice is; while it works in Python3 as expected, in Python2 print was a name which precludes you from using it as an identifier, including a method name.
downvote count: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48541691

http://stackoverflow.com/a/48591471
type: Answer
score: 1
has body: You also need to handle the case if nothing is found. Therefore, return an empty dict instead of None, i.e. having no return that is executed: def find_deep_value(d, key): if key in d: return d[key] for k in d.keys(): if isinstance(d[k], dict): for j in find_deep_value(d[k], key): return j return {}
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48591296

http://stackoverflow.com/q/48623256
upvote count: 0
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/84243432
has body: I'm trying to do an online course in computer programming and this is one of the first tasks to complete. I understand it so far, so I don't get it why the object Bucket is not callable when the code is pretty clear? # [ ] show the type after assigning bucket = a whole number value such as 16 bucket = (16) type (bucket) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-57-a98943f63825&gt; in &lt;module&gt;() 1 # [ ] show the type after assigning bucket = a whole number value such as 16 2 bucket = (16) ----&gt; 3 type (buckets) TypeError: 'int' object is not callable Why is this giving me issues? If anyone could explain this to me I would be very thankful.
has title: Type error: 'int' object not callable - yes it is?
has answer: http://stackoverflow.com/a/48623796
has comment: http://stackoverflow.com/comment/84243293
favorite count: 0
type: Question
type: UnansweredQuestion
score: -3
tagged with: python

http://stackoverflow.com/comment/84091278
type: AnswerComment
comment on: http://stackoverflow.com/a/48547577
has text: Thank you. I was trying the executemany after many failed attempts using execute. I completely overlooked inserting `i` as a list.
type: Comment
score: 0

http://stackoverflow.com/comment/84201672
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48602058
has text: Yeah, you can leverage python to do anything. On the email, it looks like you already made sure it's of the proper format. For the phone I would do a check to make sure it's at least a proper length: if len(form.phone.data) < 10 or something like that. I would also make sure there aren't any letters in it. using something like all([x.isdigit() for x in form.phone.data.split("-")])

http://stackoverflow.com/a/48625516
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84248131
type: Answer
accepted answer of: http://stackoverflow.com/q/48625403
has body: Should I break it out into their own tables and get rid of the relationship? The Job_Prediction is already its own table. Or is there a way to add them? yes, add predictions to the descriptions at the same time you're adding the descriptions to the jobs: job_description = Job_Description(description) job_description.job_predictions.append(...) # ^^^ whetever you need, here profile_record.job_descriptions.append(job_description)
answers question: http://stackoverflow.com/q/48625403
score: 0

http://stackoverflow.com/q/48547818
has title: How to get to last record of large dataframe in Spyder window?
tagged with: spyder
has answer: http://stackoverflow.com/a/48549176
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48556088
has body: I want to be able to open a dataframe in a Spyder (Python IDE) window and quickly scroll down to the last record of a relatively large pandas dataframe (134,890 records in table). It's frustrating because Spyder only loads a certain number of records from large tables, and scrolling down takes a while. Does anyone know a shortcut or option to quickly get to the end of the dataframe, without writing any code like df.tail()? The following image shows a dataframe with data extending into 2018, but it takes me quite a while to scroll to the end. Every time I scroll to what should be the bottom, Spyder loads a few more records from the table, and I start scrolling down again...
has comment: http://stackoverflow.com/comment/84094307
favorite count: 0
has answer: http://stackoverflow.com/a/48556088
type: Question
answer count: 2
upvote count: 2
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84093818
has comment: http://stackoverflow.com/comment/84093382
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48549176
has comment: http://stackoverflow.com/comment/84094243
tagged with: pandas

http://stackoverflow.com/comment/84191231
comment on: http://stackoverflow.com/q/48596882
type: QuestionComment
has text: I know that,but I think anything in **type()** will only print the type before :p. And thank everyone's description!
type: Comment
score: 0

http://stackoverflow.com/q/48606286
has body: I am looking for a code shortcut to access member functions of multiple instances of python class to avoid code redundancy. For instance, class my_class: def __init__(self): ... def set_parameter(self): #sets some parameter Now I create multiple instances of my_class instance1 = my_class() instance2 = my_class() I would like to as if it is possible to access use set_parameter member function for both of the above instances in the same line of code?
tagged with: python
accepted answer: http://stackoverflow.com/a/48606520
score: 2
type: AnsweredQuestion
upvote count: 3
has title: Accessing member functions of multiple instances of a python class
has comment: http://stackoverflow.com/comment/84208963
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48606520
type: Question
has comment: http://stackoverflow.com/comment/84208805

http://stackoverflow.com/q/48522206
favorite count: 0
possible better answer: http://stackoverflow.com/a/48523039
type: AnsweredQuestion
has body: I have this dataframe: In excel I have the simple count if =if((COUNTIFS(B:B,B2,A:A,"=A"))=0,"No","Yes") So essentially, how do I loop through all of the rows, countif the Cell in MatchID against Range(MatchID) AND if Range(provider) = "A". Whilst recording the entry in a new column. Simply enough to do in VBA and excel but python/Pandas is new to me and still slightly beyond my mental grasp. Is this possible? Thanks for any help.
has comment: http://stackoverflow.com/comment/84038964
has title: Pandas - Multiple criteria Countifs row by row
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48523337
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84039772
type: Question
has answer: http://stackoverflow.com/a/48523039
linked to: http://stackoverflow.com/q/20109391
accepted answer: http://stackoverflow.com/a/48522700
downvote count: 0
has answer: http://stackoverflow.com/a/48522700
upvote count: 1

http://stackoverflow.com/comment/84039935
score: 0
has text: You're absolutely right no doubt in that but in development phase i wanted to do this not after launching it so the problem you stated will not be a problem indeed :)
type: Comment
comment on: http://stackoverflow.com/q/48522081
type: QuestionComment

http://stackoverflow.com/q/48526454
tagged with: django
tagged with: python
has title: How eliminate selection in ManytoMany form field
type: AnsweredQuestion
score: 0
has body: I have this model: class Transaction(models.Model): date = models.DateTimeField(auto_now_add=True) buyer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="buyer") smokers = models.ManyToManyField(UserProfile) price = models.FloatField(blank=True) And have this form: class TransactionForm(ModelForm): class Meta: model = Transaction fields = ['smokers', 'price',] I would like to access smokers field and eliminate few options (that user won't be able to select it or even see it in HTML). Is that even possible?
answer count: 1
accepted answer: http://stackoverflow.com/a/48526877
type: Question
has answer: http://stackoverflow.com/a/48526877

http://stackoverflow.com/comment/84152270
type: QuestionComment
score: 0
has text: the content in the file is 1,9 2,8 3,7 4,6 5,5 6,4 7,3 8,2 9,1
type: Comment
comment on: http://stackoverflow.com/q/48575657

http://stackoverflow.com/a/48548170
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Use re.sub: import re s = 'ref:_00D30jPy._50038vQl5C:ref' result = re.sub(r'^[^5]*(5.{4})(.*?):ref$', r'\g&lt;1&gt;00000\g&lt;2&gt;', s, 0, re.MULTILINE) print(result) Output: 5003800000vQl5C Explanation: ^[^5]*: match characters except 5 from the beginning (5.{4}): capture the first 5 characters to group 1 (.*?):ref$: capture the remaining to group 2 except the :ref at the end \g&lt;1&gt;00000\g&lt;2&gt;: replace the whole line with \g&lt;1&gt;00000\g&lt;2&gt; where \g&lt;1&gt; and \g&lt;2&gt; are substituted by group 1 and 2 repsectively. Demo has a Python 2-compatible code generator and detailed explanation.
answers question: http://stackoverflow.com/q/48534703
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48534703

http://stackoverflow.com/comment/84163244
type: Comment
has text: @sunboy612 you did not specify, and when asked you replied Win10. The answers you are looking for are already mentioned in the comments section.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48579845

http://stackoverflow.com/comment/84078564
comment on: http://stackoverflow.com/q/48541711
type: QuestionComment
has text: Have a look at the `'x'`flag to `open` - this should try to create the file, but raise `FileExistsError` if it already exists: https://docs.python.org/3.6/library/functions.html#open
score: 0
type: Comment

http://stackoverflow.com/q/48505575
tagged with: python
has comment: http://stackoverflow.com/comment/84006139
has comment: http://stackoverflow.com/comment/84005693
has comment: http://stackoverflow.com/comment/84169808
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/84006276
has comment: http://stackoverflow.com/comment/84005764
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/48358084
tagged with: tkinter
answer count: 0
tagged with: canvas
has title: Display thousands of records in CSV data in Tkinter
type: UnansweredQuestion
tagged with: user-interface
downvote count: 0
has body: I want to load the data from a CSV file which have around 20,000 records and want to display it in tkinter in a scrollable table format. I used canvas, labels, grids, and scrollbar to achieve this. However, it can load only around 100-300 records in Tkinter without hanging. What could be the possible reason for this? I find that parsing through CSV is not the culprit. Is it the canvas and scrollable area? Can Tkinter show huge data as tables? class Table(Frame): def __init__(self, parent, csv_data, start=0): Frame.__init__(self, parent, background="#EEEEEE", height=400) self._widgets = [] self._canvas = Canvas(self, width=1300, height=500) self._canvas.grid(row=0, column=0, sticky="news") # changed self._vertical_bar = Scrollbar(self, orient="vertical", command=self._canvas.yview) self._vertical_bar.grid(row=0, column=1, sticky="ns") self._canvas.configure(yscrollcommand=self._vertical_bar.set) self._horizontal_bar = Scrollbar(self, orient="horizontal", command=self._canvas.xview) self._horizontal_bar.grid(row=1, column=0, sticky="we") self._canvas.configure(xscrollcommand=self._horizontal_bar.set) self.frame = Frame(self._canvas) self._canvas.create_window((0, 0), window=self.frame, anchor="nw") self.frame.bind("&lt;Configure&gt;", self.resize) lineNum = start-1; for row in csv_data: print(lineNum) lineNum += 1; if lineNum &lt; start: continue; if lineNum == start+200: break; current_row = [] #index for column in range(len(row)+1): v = StringVar() label = Label(self.frame, textvariable=v) label.config(font=("Calibri", 10), background="white",highlightcolor='white', highlightbackground='white', borderwidth=0) label.grid(row=lineNum, column=column+1, sticky="nsew", padx=1, pady=1) current_row.append(label) if column == 0: v.set(lineNum) else: v.set(row[column-1]) self._widgets.append(current_row) for column in range(lineNum): self.grid_columnconfigure(column, weight=1) def resize(self, event=None): self._canvas.configure(scrollregion=self._canvas.bbox("all")) #self._…
upvote count: 1

http://stackoverflow.com/comment/100920752
has text: @JackStrosahl thanks for noticing that the answer was outdated! I've now updated it.
score: 0
comment on: http://stackoverflow.com/a/48529954
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84294815
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48639552
has text: I see what's going on. However, does this mean the signal is arriving at the same time `sleep()` is waiting every single time? Would this happen just by "luck", or can I expect the `sleep()` to be consistently interrupted in this case?
type: Comment

http://stackoverflow.com/q/48511034
linked to: http://stackoverflow.com/q/1420839
has comment: http://stackoverflow.com/comment/84017166
tagged with: python
has title: Raspberry pi3 Mysql Python ERROR
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48511225
score: 1
has answer: http://stackoverflow.com/a/48511225
has body: Hi I'm trying to connect from python to MySQL but I can't apparently due to below error. I tried it with this... import MySQLdb cnx = MySQLdb.connect(user ='phpmyadmin', passwd ='raspberry', host ='192.168.0.58', database ='freddy') print 'connected' cnx.close() and then i changed "Mysqldb" to "Mysql.connector" but doesnt work. This is the error showing : Traceback (most recent call last): File "test.py", line 2, in cnx = MySQLdb.connect(user='phpmyadmin',passwd='raspberry',host='192.168.0.58',database='freddy') File "/usr/lib/python2.7/dist-packages/MySQLdb/init.py", line 81, in Connect return Connection(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 204, in init super(Connection, self).init(*args, **kwargs2) TypeError: 'database' is an invalid keyword argument for this function .... what should i do? i know my password its fine, but must be somethig else...
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/2482234
tagged with: mysql
upvote count: 1
has comment: http://stackoverflow.com/comment/84017047
has comment: http://stackoverflow.com/comment/84017349
favorite count: 0
type: Question
tagged with: raspberry-pi

http://stackoverflow.com/comment/84143648
comment on: http://stackoverflow.com/q/48573117
has text: How many levels of nesting are these dicts supposed to have? It could be interpreted as either two or three.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48564313
answers question: http://stackoverflow.com/q/48564067
has body: You should put all the code with business logic in services.py of your Django app. For example, your case should go like, from .models import H, P def calculate_y(x, par): obj = H.objects.get(x=x) # if x is unique else use id obj.y = 2 * x + par obj.save(update_fields['y']) You can call this function right after creating an object for H.
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/84060155
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48532130
has text: Great that it helped. BTW, you have the privilege to [upvote](http://stackoverflow.com/help/privileges/vote-up). ;)

http://stackoverflow.com/a/48504285
type: Answer
has comment: http://stackoverflow.com/comment/84002470
has comment: http://stackoverflow.com/comment/84002359
has comment: http://stackoverflow.com/comment/84002504
has comment: http://stackoverflow.com/comment/84002844
answers question: http://stackoverflow.com/q/48503558
has comment: http://stackoverflow.com/comment/84002625
has body: The interpreter is telling you exactly what the problem is: File.write returns nothing, i.e. it returns None, and you can't call the read() method on a None type. Remove "abb = ", and change print abb.read() To print abc.read() It should work fine then.
score: 0
has comment: http://stackoverflow.com/comment/84002581

http://stackoverflow.com/a/61508765
has body: First run the command conda install -c anaconda git then run git clone https://github.com/Theano/Theano.git
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/138740912
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48568090

http://stackoverflow.com/q/48495015
has comment: http://stackoverflow.com/comment/83983017
type: Question
has title: Python calling math.log on big number returns number with 1 in last decimal place instead of whole number
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83983355
score: 0
has comment: http://stackoverflow.com/comment/83983185
has comment: http://stackoverflow.com/comment/83983059
answer count: 0
has comment: http://stackoverflow.com/comment/83983094
has body: So I was doing the following programming problem: Find if the given number is power of 2 or not. Since log is inverse of exponent, I came up with a solution where I would get the log2 of the number, and if that result was a whole number (by testing with % 1) then it is a power of 2. def isPowerOfTwo(n): if n == 1: return 0 if math.log(n, 2) % 1 == 0: return True else: return False However this fails on the number 5070602400912917605986812821504, since math.log(5070602400912917605986812821504, 2) returns 102.00000000000001 for some reason. What is going on here for there to be that 1 in the last decimal place? According to every calculator I tried, log base 2 of 5070602400912917605986812821504 is just 102.

http://stackoverflow.com/comment/84186373
comment on: http://stackoverflow.com/a/48594443
type: AnswerComment
has text: Programmers that are new Python often first encounter this kind of issue when they try to use a mutable default value (like an empty list) for an argument that they later modify in place (e.g. by calling the `append` menthod of the list). A function declared like `def foo(x=[])` always uses the same list as the default argument, so calls after the first will see the values added to the list on all the previous calls. The situation you ran into is not as common, but it comes from the same root cause.
score: 1
type: Comment

http://stackoverflow.com/a/69995561
answers question: http://stackoverflow.com/q/48491566
has body: You should insert a cell just before your present code cell and then type the following code from sklearn.base import BaseEstimator, TransformerMixin class DataFrameSelector(BaseEstimator, TransformerMixin): def __init__(self, attribute_names): self.attribute_names = attribute_names def fit(self, X, y=None): return self def transform(self, X, y=None): return X[self.attribute_names].values By this way your DataFrameSelector class will be defined beforehand
type: Answer
score: 0

http://stackoverflow.com/a/48510302
answers question: http://stackoverflow.com/q/48510058
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Here is a little hacky solution. If the date column is called 'date', try df['date'] = pd.to_datetime(df['date'] - 315619200, unit = 's') Here 315619200 is the number of seconds between Jan 1 1960 and Jan 1 1970. You get 0 2004-11-15 00:00:00 1 2005-03-22 00:03:20 2 2005-06-05 23:56:40 3 2005-04-09 00:00:00 4 2005-05-31 00:03:20
type: Answer
accepted answer of: http://stackoverflow.com/q/48510058

http://stackoverflow.com/comment/84195566
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48598904
type: AnswerComment
has text: @WillemVanOnsem Actually, it would be a problem. My program is counting the word frequency. For example, what if the word "words" can be caught and "words." can't be because the latter has a dot in the end? That's what I'm concerned about.

http://stackoverflow.com/comment/84184387
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48593578
has text: Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters)
score: 0

http://stackoverflow.com/comment/84098935
comment on: http://stackoverflow.com/q/48551165
type: Comment
type: QuestionComment
has text: So much dread looking at this line: `rm -rf ~`
score: 0

http://stackoverflow.com/a/48574713
upvote count: 1
has body: I am not sure the speed, but this will achieve what you need , you need groupby+cumsum+shift df['New']=df.groupby('ID').\ apply(lambda x : x.groupby(x.Count.ne(0).cumsum().shift().fillna(False)).cumcount()).\ sort_index(level=1).values df Out[323]: ID Count New 0 1234 1 0 1 1234 2 0 2 1234 0 0 3 1234 0 1 4 1234 0 2 5 1234 1 3 6 1234 1 0 7 5678 1 0 8 5678 5 0 9 5678 4 0 10 5678 0 0 11 1111 0 0 12 1111 0 1 13 1111 1 2 14 1111 2 0 15 1111 0 0 16 1111 0 1 17 1111 2 2
answers question: http://stackoverflow.com/q/48574444
score: 1
accepted answer of: http://stackoverflow.com/q/48574444
type: Answer
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87302021
type: AnswerComment
has text: Earlier answers already showed about `__args__` attribute. This answer just seems to add unnecessary waffle on top of that.
type: Comment
comment on: http://stackoverflow.com/a/50111244
score: 2

http://stackoverflow.com/comment/83995604
type: AnswerComment
has text: No, `Comment.objects.filter()...` will most certainly be `QuerySet<Comment>`. I'm saying that if you do `.values_list('user__id')`, you can then use _that_ queryset as an argument to `User.objects.filter()`, and save a database query. Please read my [comment](https://stackoverflow.com/questions/48499551/how-to-get-user-queryset-who-commented-to-certain-post-in-python-django/48500054?noredirect=1#comment83995257_48500054) carefully, and see that I am filtering on `User` at the top level.
score: 0
comment on: http://stackoverflow.com/a/48500054
type: Comment

http://stackoverflow.com/q/48568391
score: -5
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84133063
has body: For a School Project i am coding a naughts and crosses game. I am trying to create it in a way that an existing tile cannot be overwritten, but my code does not seem to be working and i cannot find the solution to fix it. Below is the code: import random y = 0 Tic_Tac = ['null','null','null', 'null','null','null', 'null','null','null' ] def basic_computer_UI(Tic_Tac_Toe_list,list_of_taken_numbers): x = 1 while x == 1: place_tic_tac = random.randint(0,8) if place_tic_tac not in list_of_taken_numbers: Tic_Tac_Toe_list[place_tic_tac] = 'o' list_of_taken_numbers.append(str(place_tic_tac)) print(Tic_Tac_Toe_list) x = 0 else: x = 1 while y == 0: change_var = input("enter the number you want to change") change_var_int = int(change_var) list_change = [] if change_var not in list_change: list_change.append(change_var) Tic_Tac[change_var_int - 1] = 'x' print('\n',Tic_Tac[0],'\t',Tic_Tac[1],'\t',Tic_Tac[2],'\n', Tic_Tac[3],'\t',Tic_Tac[4],'\t',Tic_Tac[5],'\n', Tic_Tac[6],'\t',Tic_Tac[7],'\t',Tic_Tac[8]) basic_computer_UI(Tic_Tac,list_change) else: print("you cannot overwrite a pre-existing number") Thanks in advance for any help
has comment: http://stackoverflow.com/comment/84133031
has comment: http://stackoverflow.com/comment/84133137
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/84133166
accepted answer: http://stackoverflow.com/a/48568468
has title: I'm Coding A Naughts and Crosses Game
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48568468
tagged with: function
upvote count: 0

http://stackoverflow.com/q/48644689
score: 0
has answer: http://stackoverflow.com/a/48645776
tagged with: apache-spark
answer count: 1
has comment: http://stackoverflow.com/comment/84286954
has body: I wrote below code : import pyspark def getHub(sc, ClientId): sqlContext = pyspark.sql.SQLContext(sc) return sqlContext.table("myTable").where("ClientId = "+ClientId) sc = pyspark.SparkContext() df = getHub(sc, 1).union(getHub(sc, 2)) I know I cannot create several SparkContext but is there any problem in creating several SQLContext ? Or is it better to create only 1 SQLContext and then pass it as an arg ?
accepted answer: http://stackoverflow.com/a/48645776
has title: use several sqlContext in one execution
type: Question
has comment: http://stackoverflow.com/comment/84287146
has comment: http://stackoverflow.com/comment/84288045
has comment: http://stackoverflow.com/comment/84288106
has comment: http://stackoverflow.com/comment/84287900
has comment: http://stackoverflow.com/comment/84287952
tagged with: pyspark
has comment: http://stackoverflow.com/comment/84288610
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84287861

http://stackoverflow.com/q/48548231
tagged with: valueerror
has answer: http://stackoverflow.com/a/50106705
score: 0
has comment: http://stackoverflow.com/comment/84093027
has comment: http://stackoverflow.com/comment/84092781
answer count: 1
has comment: http://stackoverflow.com/comment/84093092
tagged with: codeblocks
type: Question
tagged with: debugging
has comment: http://stackoverflow.com/comment/84093033
type: UnansweredQuestion
has title: python valueerror in learn python the hard way Ex41
has body: I'm learning to code with Learn Python the Hard Way. I'm getting a "valueError" in Ex 41 that I can't seem to figure out why. I have googled how to debug the code using python's built in debugger import PDB but I still can't figure out the error. I have triple checked my code against the code in the text book and it's exact. This is the error I get: Traceback (most recent call last): File "ex41.py", line 72, in &lt;module&gt; question, answer = convert(snippet, phrase) ValueError: not enough values to unpack (expected 2, got 0) This is the part of the code that throws: # keep going until they hit CTRL-D try: while True: snippets = list(PHRASES.keys()) random.shuffle(snippets) for snippet in snippets: phrase = PHRASES[snippet] question, answer = convert(snippet, phrase) if PHRASE_FIRST: question, answer = answer, question print(question) input("&gt; ") print(f"ANSWER: {answer}\n\n" ) except EOFError: print("\nBye") The entire code for the exercise is below minus the code that is above that throws the error. import random from urllib.request import urlopen import sys WORD_URL = "http://learncodethehardway.org/words.txt" WORDS = [] PHRASES = { "class %%%(%%%):": "Make a class named %%% tht is-a %%%.", "class %%%(object):\n\tdef __init__(self, ***)" : "class %%% has-a __init__ that takes self and *** params.", "class %%%(object):\n\tdef ***(self, @@@)": "class %%% has-a function *** that takes self and @@@ params.", "*** = %%%()": "Set *** to an instance of class %%%.", "***.*** (@@@)": "From *** get the *** function, call it with params self, @@@.", "***.*** = '***'": "From *** get the *** attribute and set it to '***'." } # do the want to drill phrases first if len(sys.argv) == 2 and sys.argv[1] == "english": PHRASE_FIRST = True else: PHRASE_FIRST = False # load up the words from the website for word in urlopen(WORD_URL).readlines(): WORDS.append(str(word.strip(), encoding="utf-8")) def convert(snippet, phrase): class_names = [w.capitalize() for w in random.sample(WOR…
tagged with: python

http://stackoverflow.com/q/48595155
type: Question
tagged with: elasticsearch
tagged with: python
has comment: http://stackoverflow.com/comment/84187530
accepted answer: http://stackoverflow.com/a/48595516
type: AnsweredQuestion
has title: Why my pipeline return previous modified items?
score: 0
tagged with: function
answer count: 1
has body: I created a pipeline to save each item on ElasticSearch. On this pipeline I check if item already exist to check if administrator override some field, to force a reindex (got this field and save/override it on new item) class InsertItemOnElasticSearch(object): buffer = [] @classmethod def from_crawler( cls, crawler ): # Init ES connection # Get uniq ID def got_id( self, item ): # Return uniq ID of item # Check if insert or update def check_item( self, item ): item_id = self.got_id( item ) type = 'create' is_exist = self.es.search(...) if is_exist[ 'hits' ][ 'total' ] == 1: type = 'index' item_tmp = is_exist[ 'hits' ][ 'hits' ][0][ '_source' ] is_override_by_admin = item_tmp.get( 'is_override_by_admin', False ) if is_override_by_admin: ... try: my_field = item_tmp.get( 'my_field' ) if my_field: item[ 'my_field' ] = my_field except: pass return self.index_item( item, type, item_id ) # Format indexation def index_item( self, item, op_type, item_id ): # Add es_action to buffer # Send buffer to ES def save_items( self ): helpers.bulk( self.es, self.buffer ) # Process item send to pipelines def process_item( self, item, spider ): return self.check_item( item ) # Send buffer when spider closed def close_spider( self, spider ): if len( self.buffer ): self.save_items() But, when a product exist and have my_field fill, script save same content on all next item, despite not having this field existed. So all my data is corrupted.. Someone know why ?
has answer: http://stackoverflow.com/a/48595516
tagged with: scrapy
tagged with: scrapy-pipeline

http://stackoverflow.com/q/48643378
has comment: http://stackoverflow.com/comment/84283345
has body: I have a two sets of numpy array data of dimensions 36*3. Each row of both arrays corresponds to the same Y value. I need to feed in each row for numpy array 1 into a regression NN to generate a value, and then sum all of these. This needs to be repeated for numpy array 2. The final prediction for the single Y value, is the difference between the two sums of predictions. I am unsure how to feed these rows of x data (3 input nodes) values into a X placeholder, for each y value into a Y placeholder to then be run in a TF session. As the entire code below only corresponds to one datapoint in effect; the function get_dataset(1) gives this.This is how one datapoint is loaded currently. I am wondering how others would approach this fitting problem. Essentially I do not know how to format the x data. There is more than one input per Y value. data = get_dataset(1) # 36*6 np array corresponding to one Y value ideal_data = data[:,[0,1,4]] # ideal and displaced data are in these columns (0,1) and (2,3) ideal_data = ideal_data.tolist() #flatten displaced_data = data[:,[2,3,4]] displaced_data = displaced_data.tolist() y = data[0][5] y_data = tf.convert_to_tensor(y) for i in range(36): # get each row i.e. X(i) datapoints ideal_data_tf = tf.convert_to_tensor(ideal_data[i]) displaced_data_tf = tf.convert_to_tensor(displaced_data[i]) My regression NN is currently defined as the following function, with an X placeholder: with tf.name_scope("Training_Neural_Network"): #Training Computation def training_multilayer_perceptron(X, weights, biases): #dropout should only be used during training, not during evaluation with tf.name_scope("Layer1"): layer_1 = tf.add(tf.matmul(X, weights['W1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) layer_1 = tf.nn.dropout(layer_1,keep_prob) with tf.name_scope("Layer2"): layer_2 = tf.add(tf.matmul(layer_1, weights['W2']), biases['b2']) layer_2 = tf.nn.relu(layer_2) layer_2 = tf.nn.dropout(layer_2,keep_prob) with tf.name_scope("Layer3"): out_layer = tf.add…
has answer: http://stackoverflow.com/a/48644340
upvote count: 1
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has title: How to feed multiple values of X data for each Y to a TensorFlow NN
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84283513
has comment: http://stackoverflow.com/comment/84317151

http://stackoverflow.com/q/48569024
accepted answer: http://stackoverflow.com/a/48569730
has answer: http://stackoverflow.com/a/65008965
answer count: 4
favorite count: 0
type: Question
upvote count: 2
downvote count: 2
has body: I got the following question in an exam and it failed some test cases which I don't have access to. The question is about sorting royal names with roman numerals. Given was a list of strings that we had to sort. The input obeyed the following constraints: 1) length of the list 1 &lt;=n&lt;= 50 2)Each name started with a capital letter followed by a space followed by a roman numeral between 1 and 50 inclusive. 3) Each number is a Roman numeral with capital letters I, V, X, L. The code is as follows: #! /usr/bin/env python def decode(s): if s == "I": return 1 elif s == "V": return 5 elif s == "X": return 10 elif s == "L": return 50 def romanToInt(num): res = 0 for i in range(0, len(num)-1): if decode(num[i]) &lt; decode(num[i+1]): res -= decode(num[i]) else: res + decode(num[i]) res = res + decode(num[len(num) - 1]) return res def getSortedList(names): if len(names) == 0: return [] copy_names = [[a,a] for a in names] copy_names = sorted(copy_names, key=lambda x:x[0]) for i in range(0, len(copy_names)): n2 = copy_names[i][0].split(" ") num = str(romanToInt(n2[1])) copy_names[i][0] = n2[0]+ " " + num copy_names = sorted(copy_names, key=lambda x:x[0]) res = [a[1] for a in copy_names] return res arr = ["Richard V","Henry VI","Edward II","Richard XXV","Henry IX","Edward L"] print getSortedList(arr) I have debugged this code with multiple inputs and can't figure out what the problem is. Can anyone please point out any mistake that I am overlooking?
has title: Debug Code: Sorting Royal names
has answer: http://stackoverflow.com/a/48569291
possible better answer: http://stackoverflow.com/a/48569291
tagged with: python
tagged with: string
tagged with: sorting
has answer: http://stackoverflow.com/a/68104771
has comment: http://stackoverflow.com/comment/84134664
has comment: http://stackoverflow.com/comment/84135362
type: AnsweredQuestion
score: 0
tagged with: algorithm
has answer: http://stackoverflow.com/a/48569730

http://stackoverflow.com/q/48559509
tagged with: uwsgi
type: Question
has comment: http://stackoverflow.com/comment/84149253
answer count: 0
type: UnansweredQuestion
has title: How to set python version for running flask application in uwsgi?
has comment: http://stackoverflow.com/comment/84119182
has comment: http://stackoverflow.com/comment/84118314
has body: I deployed a flask SocketIO application using uwsgi server in Ubuntu 16.04.I will be getting my original app instance from a script wsgi.py from server import app if __name__ == "__main__": app.run() And in a separate virtual environment I installed all the dependencies required for my project and intended to run my application through a configuration file myproject.ini which will be activated by a service in /etc/systemd/system Here's the configuaration file myproject.ini [uwsgi] module = wsgi:app master = true processes = 5 socket = myproject.sock chmod-socket = 660 vacuum = true die-on-term = true And here's the myproject.service file [Unit] Description=uWSGI instance to serve myproject After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/myproject Environment="PATH=/home/user/myproject/virtual_frame/bin" ExecStart=/home/user/myproject/virtual_frame/bin/uwsgi --ini myproject.ini [Install] WantedBy=multi-user.target When I run the application with the default wsgi server of flask then it's working fine But, when I am trying to run the application with uwsgi server which I configured then I am getting the following error As gevent doesn't work in python3, so I am assuming that the uwsgi server is running the application in python3 enviroment Therefore, I am interested to know the configuration to force uwsgi to work in python instead of python3 And here's the status of the project:-
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/84119156
has comment: http://stackoverflow.com/comment/84116361
tagged with: flask-socketio
tagged with: python

http://stackoverflow.com/q/48628163
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48629078
accepted answer: http://stackoverflow.com/a/48629078
upvote count: 3
tagged with: pagination
answer count: 1
tagged with: django-models
has comment: http://stackoverflow.com/comment/84253944
has title: django error using pagination and raw queryset
favorite count: 0
type: Question
has body: when I try to add pagination to my page it gives me error object of type 'RawQuerySet' has no len() views: class StudentmessageListView(ListView, LoginRequiredMixin): login_url = '/login/' redirect_field_name = 'redirect_to' template_name = 'student_messagesall.html' context_object_name = 'messages_all' model = Message paginate_by = 3 def get_queryset(self): return Message.objects.raw('SELECT * FROM ertaapp_message where to_prof_id=%s ORDER BY create_date DESC',[self.request.user.id]) def get_context_data(self, **kwargs): context = super(StudentmessageListView, self).get_context_data(**kwargs) context['reps'] = ReplyMessage.objects.raw('SELECT * FROM ertaapp_replymessage') return context how can I solve this?
has comment: http://stackoverflow.com/comment/84253559
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84254417

http://stackoverflow.com/comment/84047548
has text: @kostix makes a couple very important points about the same `free` and `malloc` used by Go and the extension. A few more details on that, python's own allocators are called `Py_Malloc` and `Py_Free` respectively so as not to be confused with the `libc` versions. In Cython code, use `from libc.stdlib cimport free, malloc` for the same functions Go is using via libc.
comment on: http://stackoverflow.com/a/48499056
score: 1
type: Comment
type: AnswerComment

pywinauto
tags question: http://stackoverflow.com/q/48559538
tag name: pywinauto
type: Tag

http://stackoverflow.com/q/48571304
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43859978
tagged with: wtforms
tagged with: python
has comment: http://stackoverflow.com/comment/84139726
tagged with: flask
score: 0
answer count: 0
has body: Hi so suppose I have a list of forms: class Create(Form): cols = [] for col in ['colA', 'colB', 'colC']: cols.append(TextAreaField(col)) When this gets initialized here: @app.route('/some/path') def create(): form = Create() return render_template('index.html', form=form) I want to make sure all these TextAreaField get converted into &lt;textarea id="col#", name="col#"&gt;&lt;textarea&gt;. As right now they stay as &lt;UnboundedField(TextAreaField, ('col#,),{})&gt; objects. Right now they are not getting converted If this is possible any recommendation would be great. Thanks! &lt;div class="row"&gt; {% for col in form.cols %} &lt;div class="col-md-2"&gt; &lt;div class="form-group"&gt; {{ col(rows="20") }} {% for error in col.errors %} &lt;span style="color: red;"&gt;[{{ error }}]&lt;/span&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; AttributeError: 'UnboundField' object has no attribute '__call__' It obviously works when I have them all separately: class Create(Form): cols = [] colA = TextAreaField('colA') colB = TextAreaField('colB') colC = TextAreaField('colC') Otherwise I wouldnt be asking the question
has comment: http://stackoverflow.com/comment/84139635
has comment: http://stackoverflow.com/comment/84140532
has comment: http://stackoverflow.com/comment/84139881
type: Question
has title: Initialize a list of field in a form using Wtforms

http://stackoverflow.com/comment/83970781
type: Comment
comment on: http://stackoverflow.com/a/48488791
type: AnswerComment
has text: @JWestwood I implemented the use of `dict.get` and provided a default value, should the first parameter, the desired key, not be found in the dictionary.
score: 0

http://stackoverflow.com/comment/84001126
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48503703
has text: It isn't the duplicate, i said I have done both, both doesn't work.
type: Comment

http://stackoverflow.com/comment/84171521
score: 0
comment on: http://stackoverflow.com/a/48586943
has text: @gonczor ah, you are correct.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83990770
score: 0
comment on: http://stackoverflow.com/q/48498195
has text: Possible duplicate of [Examples for string find in Python](https://stackoverflow.com/questions/674764/examples-for-string-find-in-python)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84232577
type: Comment
type: QuestionComment
has text: Why do you want to reinvent the wheel? [Django CMS](https://www.django-cms.org/) offers something similar and it is the right application for your use case.
comment on: http://stackoverflow.com/q/48616339
score: 1

http://stackoverflow.com/comment/84051052
type: Comment
type: QuestionComment
has text: @TarunLalwani what do you mean what command did i run? it's a python code "userid = pwd.getpwuid(os.stat('.').st_uid).pw_name" and okay ill take a look at that question
comment on: http://stackoverflow.com/q/48527958
score: 0

http://stackoverflow.com/q/48602394
type: Question
has answer: http://stackoverflow.com/a/48602429
has body: I wrote a tkinter code, with a label. There was a variable in the label text. lab = Label(root, text = 'randomstrings', x, 'randomstrings') lab.pack() When I ran the code, it gave an error message here: , x, It said: positional argument follows keyword argument
score: -2
tagged with: python
tagged with: label
type: AnsweredQuestion
has title: How to put variable into a label text?
has answer: http://stackoverflow.com/a/48602408
accepted answer: http://stackoverflow.com/a/48602428
tagged with: tkinter
downvote count: 4
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/84201332
has answer: http://stackoverflow.com/a/48602428
possible better answer: http://stackoverflow.com/a/48602429
favorite count: 0

http://stackoverflow.com/comment/84124117
type: QuestionComment
comment on: http://stackoverflow.com/q/48564122
type: Comment
has text: Why split `LOAD R1,18` into `["L", "O", "A", "D", " ", "R", "1", ",", "1", "8"]` instead of `["LOAD", "R1", "18"]`?
score: 1

http://stackoverflow.com/comment/84039307
comment on: http://stackoverflow.com/q/48522081
has text: You're opening this up for multipe things to go wrong, if somebody bookmarks a page and that page gets deleted, they'll end up on a different page, this is a security nightmare, specially if the pages are supposed to be access protected, the whole point of that kind of url scheme is that , the urls would be permanent and unique for each resource, if a page or resource is deleted, the person should get a 404
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84192977
has text: Format code as code please.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48598275

http://stackoverflow.com/a/48658282
type: Answer
accepted answer of: http://stackoverflow.com/q/48534128
score: 0
answers question: http://stackoverflow.com/q/48534128
type: AcceptedAnswer
has body: I resolved the problem i just had to interchange the time and pressure position

http://stackoverflow.com/a/56090535
score: 39
has comment: http://stackoverflow.com/comment/110720793
has comment: http://stackoverflow.com/comment/103991865
type: Answer
has comment: http://stackoverflow.com/comment/103902427
has comment: http://stackoverflow.com/comment/116849083
has comment: http://stackoverflow.com/comment/137742073
has comment: http://stackoverflow.com/comment/104031972
has comment: http://stackoverflow.com/comment/128916607
downvote count: 1
upvote count: 40
answers question: http://stackoverflow.com/q/48608570
has body: Since 2010 you can use a virtual-hosted style S3 url, i.e. no need to mess with region specific urls: url = f'https://{bucket}.s3.amazonaws.com/{key}' With quoted key : url = f'''https://{bucket}.s3.amazonaws.com/{urllib.parse.quote(key, safe=&quot;~()*!.'&quot;)}''' Moreover, support for the path-style model (region specific urls) continues for buckets created on or before September 30, 2020. Buckets created after that date must be referenced using the virtual-hosted model. See also this blog post.

http://stackoverflow.com/comment/84271303
type: Comment
score: 0
type: AnswerComment
has text: @skrx: [link](https://www.libsdl.org/release/SDL-1.2.15/docs/html/sdldelay.html) On pygame doc. Its says that tick uses dsl_delay function. This is the description of SDL_function. Wait a specified number of milliseconds before returning. SDL_Delay will wait at least the specified time, but possible longer due to OS scheduling.(This may be the reason for not accurate on every platform.) Note: Count on a delay granularity of at least 10 ms. Some platforms have shorter clock ticks but this is the most common. (This too)
comment on: http://stackoverflow.com/a/48635383

http://stackoverflow.com/comment/84185174
comment on: http://stackoverflow.com/q/48590449
type: Comment
has text: Unfortunately not any and all python interpreters will be listed. Only the most popular locations will be searched and listed. We search the registry (as per pep 514), conda installs, and local virtual environments). We can make some changes to include Winpython as well, please create an issue on GitHub.
score: 0
type: QuestionComment

geography
type: Tag
tag name: geography
tags question: http://stackoverflow.com/q/48607339

http://stackoverflow.com/a/48622736
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84325009
has comment: http://stackoverflow.com/comment/115443289
has comment: http://stackoverflow.com/comment/84282537
has comment: http://stackoverflow.com/comment/115451286
has comment: http://stackoverflow.com/comment/84266890
has comment: http://stackoverflow.com/comment/84315736
answers question: http://stackoverflow.com/q/48619835
score: 3
upvote count: 3
has body: It's not GPU (instead it tries to exploit threading and the CPU's vector units), but pyvips is quite a bit quicker than scipy, you could test that. I made a benchmark: import sys import time import scipy.ndimage import pyvips scale = 10 n_loops = 10 start = time.time() test_image = scipy.ndimage.imread(sys.argv[1]) for i in range(0, n_loops): result = scipy.ndimage.interpolation.zoom(test_image, scale) end = time.time() print 'scipy took', end - start start = time.time() test_image = pyvips.Image.new_from_file(sys.argv[1]) for i in range(0, n_loops): result = test_image.resize(scale).write_to_memory() end = time.time() print 'pyvips took', end - start # transform with both libraries to compare results ndi = scipy.ndimage.imread(sys.argv[1]) result = scipy.ndimage.interpolation.zoom(ndi, scale) scipy.misc.imsave('ndi.tif', result) im = pyvips.Image.new_from_file(sys.argv[1], access='sequential') result = im.resize(scale) result.write_to_file('pyvips.tif') Both default to bicubic. pyvips is a lazy library, so you need the extra write_to_memory() at the end to generate a memory array. On this four core / eight thread desktop running Ubuntu 17.10 with the packaged versions of all libraries and a 512x512 mono version of the 'lena' test image, I see: $ python zoom.py ~/pics/lena.png scipy took 15.6309859753 pyvips took 1.36838102341 A GPU upsizer would obviously be faster again, but maybe pyvips would be fast enough? If you compare the two output images, you'll see the scipy one is shifted up by a small amount. You can see what's happening more clearly with a very small input image, for example, this 3x3 pixel image: When zoomed 20x by scipy and pyvips becomes: Which puzzles me. Additionally, they are clearly using different kernels, which is also odd.

http://stackoverflow.com/comment/84195550
comment on: http://stackoverflow.com/q/48598829
score: 0
has text: From my understanding of the question you're looking to plot a heightmap. This question suggests that Mayavi has a solution for this https://stackoverflow.com/questions/30706919/how-to-create-a-3d-height-map-in-python
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84095092
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48526754
has text: Happy to be of help!
type: AnswerComment

http://stackoverflow.com/comment/84109856
has text: You can work with docker. Create a docker image for your virtual environment and use the docker image in a pipeline in your current job. Just spin up the container, do your tests inside the container and bring it down again, instead of needing to install everything every time you can persist that configuration in your docker image/container.
comment on: http://stackoverflow.com/q/48552479
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48491143
linked to: http://stackoverflow.com/q/5365580
downvote count: 0
linked to: http://stackoverflow.com/q/45449764
answer count: 1
linked to: http://stackoverflow.com/q/15667189
has title: Python multiprocessing--global variables in separate processes sharing id?
favorite count: 0
tagged with: multiprocessing
type: Question
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/11055303
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/48493221
tagged with: parallel-processing
tagged with: python-multiprocessing
has body: From this question I learned that: When you use multiprocessing to open a second process, an entirely new instance of Python, with its own global state, is created. That global state is not shared, so changes made by child processes to global variables will be invisible to the parent process. To verify this behavior, I made a test script: import time import multiprocessing as mp from multiprocessing import Pool x = [0] # global def worker(c): if c == 1: # wait for proc 2 to finish; is global x overwritten by now? time.sleep(2) print('enter: x =', x, 'with id', id(x), 'in proc', mp.current_process()) x[0] = c print('exit: x =', x, 'with id', id(x), 'in proc', mp.current_process()) return x[0] pool = Pool(processes=2) x_vals = pool.map(worker, [1, 2]) print('parent: x =', x, 'with id', id(x), 'in proc', mp.current_process()) print('final output', x_vals) The output (on CPython) is something like enter: x = [0] with id 140138406834504 in proc &lt;ForkProcess(ForkPoolWorker-2, started daemon)&gt; exit: x = [2] with id 140138406834504 in proc &lt;ForkProcess(ForkPoolWorker-2, started daemon)&gt; enter: x = [0] with id 140138406834504 in proc &lt;ForkProcess(ForkPoolWorker-1, started daemon)&gt; exit: x = [1] with id 140138406834504 in proc &lt;ForkProcess(ForkPoolWorker-1, started daemon)&gt; parent: x = [0] with id 140138406834504 in proc &lt;_MainProcess(MainProcess, started)&gt; final output [1, 2] How should I explain the fact that the id of x is shared in all the processes, yet x takes different values? Isn't id conceptually the memory address of a Python object? I guess this is possible if the memory space gets cloned in the child processes. Then is there something I can use to get the actual physical memory address of a Python object?

http://stackoverflow.com/q/48521578
has comment: http://stackoverflow.com/comment/84037647
has title: Writing to a text file from python list
has comment: http://stackoverflow.com/comment/84037653
possible better answer: http://stackoverflow.com/a/48521693
has comment: http://stackoverflow.com/comment/84037741
type: Question
accepted answer: http://stackoverflow.com/a/48521669
has answer: http://stackoverflow.com/a/48521693
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48521669
has body: I am trying to create a text file and write to it from a python list. Code: file1 = open("test.txt","w") test_list = ['hi', 'hello', 'welcome'] for each_ele in test_list: file1.write(each_ele+'\n') file1.close() Still the file is empty, any suggestions please?
has comment: http://stackoverflow.com/comment/84037660
has comment: http://stackoverflow.com/comment/84037811
tagged with: python
has comment: http://stackoverflow.com/comment/84037770
has answer: http://stackoverflow.com/a/48521751
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84037773
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/16208206

http://stackoverflow.com/comment/91491126
has text: It's technically correct both ways
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48549861
type: AnswerComment

http://stackoverflow.com/comment/84256064
score: 0
comment on: http://stackoverflow.com/q/48610777
type: Comment
type: QuestionComment
has text: @DavisKing, thanks for the pointer. Pickle seems to work after I use version 2, but I am running into a separate error with not a lot of documentation to go on. Thanks nonetheless.

http://stackoverflow.com/comment/84193187
score: 0
has text: Actually, just figured it. I didn't need to ignore unique names (as there are all unique in this instance) but more importantly, my list wasn't appending because I didn't cast the number_inc correctly as an int then str. Works now. Still be interested if anyone has better approaches to the idea in general.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48598222

http://stackoverflow.com/q/48644937
type: Question
accepted answer: http://stackoverflow.com/a/48645346
score: 5
tagged with: subprocess
has comment: http://stackoverflow.com/comment/84286933
has answer: http://stackoverflow.com/a/48645346
has answer: http://stackoverflow.com/a/48645520
downvote count: 0
has title: Calling scp from Python's subprocess not working with filelist \{a,b,c\}
tagged with: string
has answer: http://stackoverflow.com/a/48645002
favorite count: 0
has answer: http://stackoverflow.com/a/48645115
type: AnsweredQuestion
tagged with: bash
upvote count: 5
tagged with: python
possible better answer: http://stackoverflow.com/a/48645115
has comment: http://stackoverflow.com/comment/84286916
has body: I want to call a command like scp username@hostname:/dir/to/files/\{a,b,c\} /target/dir from Python to copy many files in one command. The command works perfectly if entered directly into the shell. But if I use import subprocess p = subprocess.Popen(['scp', 'username@hostname:/dir/to/files/\{a,b,c\}', '/target/dir']) sts = os.waitpid(p.pid, 0) I get the error scp: /dir/to/files/{a,b,c}: No such file or directory Obviously, the backslashes are missing. And if I use double backslashes in the Popen arguments like \\{a,b,c,d\\} I get the error scp: /dir/to/target/\a: No such file or directory scp: /dir/to/target/\b: No such file or directory scp: /dir/to/target/\c\: No such file or directory Nothing changes if I use raw strings like r'\{' + r'\}' How can I call the scp command from Python with the correctly escaped curly braces '\\{a,b,c\\}'?
answer count: 4

http://stackoverflow.com/q/48587726
has body: I'm trying to create a mock response and want to set the response.text to some unicode chars. Here's the code: class TestClass(TestCase): @mock.patch(self, mocked_get) def test_func(self): mocked_get.side_effect = self.mocked_get expected_result = [u'ssemsth'] result = self.api.query(query_params) self.assertEqual(result, expected_result) def mocked_get(self, *args, **kwargs): class MockResponse(): def test_result(): res = Response() res.message = u'semsmth' return res # some testcondition mock_response = MockResponse() if self.api.counter == 1: return mock_response.test_result() In the result for the response, I'm getting [u''], a list with empty unicode string. I want to get [u'semsmth'] Any thoughts? I'm thinking I can't set the res.message = u'semsth' and just return that. How do I set this attribute for the Response() object i'm sending to the calling test_function
tagged with: unicode
tagged with: unit-testing
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84175361
tagged with: python
has comment: http://stackoverflow.com/comment/84173084
has title: Mocking Response Python Unit testing
score: 0
tagged with: mocking
answer count: 0

http://stackoverflow.com/q/48528894
has title: NameError: name functionName is not defined
answer count: 2
has comment: http://stackoverflow.com/comment/84052954
has answer: http://stackoverflow.com/a/48528985
has comment: http://stackoverflow.com/comment/84053113
downvote count: 0
has comment: http://stackoverflow.com/comment/84053068
has answer: http://stackoverflow.com/a/48528939
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84052940
favorite count: 0
type: AnsweredQuestion
has body: My startup file from UserInfo import UserInfo user = UserInfo() print(user.username) UserInfo.py file from fileinput import filename class UserInfo(object): """description of class""" username = ""; password = ""; def readConfig(fileName): config_file = open(filename,"r") username = config_file.readline() password = config_file.readline() def __init__(self): readConfig("config.txt") Exception: NameError: name 'readConfig' is not defined Why readConfig function is not accessible in the same class?
possible better answer: http://stackoverflow.com/a/48528939
score: 1
has comment: http://stackoverflow.com/comment/84053103
accepted answer: http://stackoverflow.com/a/48528985
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/48597967
upvote count: 4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48597496
score: 4
accepted answer of: http://stackoverflow.com/q/48597496
has body: I found out what the problem was. @UweMannl was right all along. After @mhawke pointed out that cron's environment is different than the one of my terminal, I thought that perhaps also the python binary could be different and indeed it was: I want /home/ziofil/anaconda3/bin/python and cron was using /usr/bin/python. I modified the last line of the script to /home/ziofil/anaconda3/bin/python script_30_mins.py and everything works!
type: AcceptedAnswer

http://stackoverflow.com/comment/84261795
type: Comment
type: QuestionComment
has text: @user2357112 because I don't want to take the dates into account, I just want the times.
comment on: http://stackoverflow.com/q/48632242
score: 0

http://stackoverflow.com/q/48491810
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48491881
upvote count: 2
has answer: http://stackoverflow.com/a/48491881
tagged with: missing-data
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has body: I have a dataframe like this with some NaNs: df: 0 1 1 11.0 111.0 2 12.0 112.0 3 13.0 113.0 4 NaN 114.0 4 15.0 NaN 5 16.0 116.0 6 17.0 117.0 7 18.0 118.0 So what should I do to it to get the following: 0 1 1 11.0 111.0 2 12.0 112.0 3 13.0 113.0 4 15.0 114.0 4 15.0 114.0 5 16.0 116.0 6 17.0 117.0 7 18.0 118.0 So that the NaN values in the index 4 are filled with index 4 values from other rows which are not NaN?
tagged with: pandas
has title: Python Pandas DataFrame Fill Missing Value
answer count: 1
score: 1

http://stackoverflow.com/q/48616362
has comment: http://stackoverflow.com/comment/84229631
has answer: http://stackoverflow.com/a/48618254
has body: With this code, I only get to test if the number the user entered is prime or not. How do I add another loop to my original code in order to find all the prime numbers less than or equal to the number the user has entered? num = int(input("Enter a number: ")) if num &gt; 1: prime = True for n in range(2, num): if (num % n) == 0: print ("Number", num, "is not prime") break else: print("Number", num, "is prime")
answer count: 3
has comment: http://stackoverflow.com/comment/84230346
linked to: http://stackoverflow.com/q/4114167
downvote count: 3
has comment: http://stackoverflow.com/comment/84230023
has comment: http://stackoverflow.com/comment/84230058
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48618369
has answer: http://stackoverflow.com/a/48616467
has comment: http://stackoverflow.com/comment/84229985
type: UnansweredQuestion
upvote count: 0
score: -3
linked to: http://stackoverflow.com/q/26561654
has comment: http://stackoverflow.com/comment/84229656
tagged with: python
has comment: http://stackoverflow.com/comment/84230005
has title: Find prime numbers less than or equal to the number the user has entered with loops. How do I do that?

http://stackoverflow.com/comment/84141748
type: AnswerComment
has text: I can edit my answer. You can edit your question. Be specific on what you want to know.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48551489

http://stackoverflow.com/q/48550999
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48551446
upvote count: 3
has answer: http://stackoverflow.com/a/48551818
has answer: http://stackoverflow.com/a/48551507
possible better answer: http://stackoverflow.com/a/48551446
favorite count: 0
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/48551212
tagged with: python
has body: I am trying to modify the values of an array based on a subset of a subset, but I can't find a way to do this. I think this exposes my lack of understanding about exactly how array indexing and subsetting works and what views are, but I can't find a solution anywhere so I am hoping that someone can help me. Example problem: import numpy as np #generate some simple data MyArray=np.arange(20).reshape(4,5) &gt;&gt;&gt;MyArray array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) #subset 1 i=np.where(MyArray &gt; 5) #subset of that subset j=np.where(MyArray[i] &lt; 15) &gt;&gt;&gt;MyArray[i][j] array([ 6, 7, 8, 9, 10, 11, 12, 13, 14]) Great, that's what I expected to see! But if I now want to change those values to something else, I can't: &gt;&gt;&gt;MyArray[i][j]=999 &gt;&gt;&gt;MyArray[i][j] array([ 6, 7, 8, 9, 10, 11, 12, 13, 14]) #hmmmm :( An ugly solution that works I CAN get the values to change by looping over the elements of j individually, but this seems extraordinarily clumsy &amp; hard to read: #get number of elements in j nj=np.size(j) #loop over each element of j and modify the corresponding ith element of MyArray for j_it in range(0,nj): MyArray[i[0][j[0][j_it]]][i[1][j[0][j_it]]]=999 &gt;&gt;&gt;MyArray array([[ 0, 1, 2, 3, 4], [ 5, 999, 999, 999, 999], [999, 999, 999, 999, 999], [ 15, 16, 17, 18, 19]]) Similarly, I can modify MyArray using just one level of subsetting: ii=np.where((MyArray &gt; 5) &amp; (MyArray &lt; 15)) MyArray[ii]=999 &gt;&gt;&gt;MyArray array([[ 0, 1, 2, 3, 4], [ 5, 999, 999, 999, 999], [999, 999, 999, 999, 999], [ 15, 16, 17, 18, 19]]) So, where am I going wrong with the first example? NOTE:- I know that my last solution works fine for this problem, but my actual problem necessarily involves far more data and the second level of subsetting (and possibly a third...) Thanks in advance, and apologies if this is something simple that I really should be able to work out fo myself from the documentation:…
has title: Python: changing the value of array elements based on multiple subsets
has answer: http://stackoverflow.com/a/48551212
answer count: 4

http://stackoverflow.com/q/48580765
score: 0
has comment: http://stackoverflow.com/comment/84157962
answer count: 1
tagged with: file
accepted answer: http://stackoverflow.com/a/48580830
type: Question
has title: selection using strings from files
has answer: http://stackoverflow.com/a/48580830
linked to: http://stackoverflow.com/q/12330522
has body: I am trying to make a sort of quiz revision code for my exams. I am however struggling to get the selection for whether the answer is right or not to work. no matter what answer I put it outputs "nope". Each file I use has 6 lines. import random file = open("questions.txt", "r") questions = file.readlines() file2 = open("answers.txt", "r") answers = file2.readlines() question_answering = True while question_answering: question = random.randrange(5) print(questions[question]) answer = input("enter your answer: ") print(answers[question]) if answer == answers[question]: print("well done!") else: print("nope") I have included a test which is print(answers[question]) which does output the correct answer that I am looking for but when I input that answer it does not work.
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84093818
type: Comment
has text: @Evan, I certainly could write some relatively simple code, but I open dataframes quite often and I want to see the most recent dates very quickly. I often open several related dataframes in separate windows, to compare them.
type: QuestionComment
comment on: http://stackoverflow.com/q/48547818
score: 0

http://stackoverflow.com/q/48627036
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84250947
has title: Why do *args and **kwargs seem to disappear in class decorator?
type: AnsweredQuestion
upvote count: 0
has body: Practicing with decorators, found this behavior strange: def test_decorator(cls, *args, **kwargs): print (args, kwargs) def build(*args, **kwargs): print (args, kwargs) return cls(*args, **kwargs) return build @test_decorator class Test: def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs t = Test(1, 2, 3, val = 4) print (t.args, t.kwargs) # output # () { } # (1, 2, 3) {'val' = 4} # (1, 2, 3) {'val' = 4} Why does the first print in the decorator show empty containers? Further, if I defined build() as: def build(): return cls(*args, **kwargs) I know it will fail because of nested function scoping. I'm just not sure why they somehow don't exists before the call to build and suddenly return to scope.
answer count: 1
tagged with: decorator
has answer: http://stackoverflow.com/a/48627085
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48627085

http://stackoverflow.com/q/48637960
has answer: http://stackoverflow.com/a/48643528
type: Question
has title: Improper input: N=3 must not exceed M=1 (error trying to fit a gaussian function)
type: UnansweredQuestion
answer count: 1
has body: I'm pretty new to python and curve fitting and currently I'm trying to fit the graph below with a Gaussian I'm following this tutorial and my code looks like this import numpy as np import matplotlib.pyplot as plt from pylab import genfromtxt from matplotlib import pyplot from numpy import sqrt, pi, exp, linspace,loadtxt from lmfit import Model def gaussian(x,amp,cen,wid): "1-d gaussian: gaussian(x,amp,cen,wid)" return (amp/(sqrt(2*pi)*wid))*exp(-(x-cen)**2/(2*wid**2)) filelist=[] time=[0.00,-1.33,-2.67,-4.00,-5.33,-6.67,1.13,2.67,4.00,5.33,6.67] index=0 offset=0 filelist.append('0.asc') for i in range(1,6): filelist.append("-%s00.asc" %(i)) for i in range(1,6): filelist.append("+%s00.asc" %(i)) sfgpeaks=[] for fname in filelist: data=np.genfromtxt(fname,delimiter=',',unpack=True,skip_footer=20) SFGX=data[0,500:530] SFGY=data[1,500:530] SFGpeakY=np.max(SFGY) sfgpeaks.append(SFGpeakY) gmodel = Model(gaussian) result = gmodel.fit(SFGpeakY, x=time[index], amp=5,cen=5,wid=3) plt.plot(time[index],sfgpeaks[index],'ro') plt.plot(time[index],result.init_fit, 'k--',label="Gaussian Fit") plt.xticks(time) index=index+1 print(pump2SHGX) pyplot.title("Time Delay-SFG peak") plt.xlabel("Timedelay[ps]") plt.ylabel("Counts[arb.unit]") plt.savefig("796and804nmtimesfg") plt.legend(bbox_to_anchor=(1.0,0.5)) plt.show() However, I'm getting an error when I try to add the data that I have(time delay and the Y value of the graph above) into the gaussian parameters. The error I'm getting is this TypeError: Improper input: N=3 must not exceed M=1 Does this error because I'm trying to insert a value from an array into the parameter?? Any help is much appreciated.
tagged with: curve-fitting
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84272232
has comment: http://stackoverflow.com/comment/84284874
has comment: http://stackoverflow.com/comment/84275153
has comment: http://stackoverflow.com/comment/84274864

http://stackoverflow.com/q/48549557
tagged with: python
has title: How to convert all warnings.warn to logging
has comment: http://stackoverflow.com/comment/84095153
has body: I have whole configuration to log and process all messages through logging. Ideally, I would like to convert all warnings to logging warnings so that I can see them in the collected logs. Currently they are juts displayed on stderr.
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48553224
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/48625937
has comment: http://stackoverflow.com/comment/84248812
has body: I'm having what will definitely be a very simple issue but I can't get my head around it. I'm trying to get the user to input a desired website name, then use that to decide on the full name use that in another function. Here's the basics of the function. def website(): x = input("Enter url:") global url if 'Google' in x: url = ("www.google.com") else: "Try again!" website() This only works if I have global url there. Otherwise, it breaks. In the main function it tries to use the output url from website() straight away, but returns: NameError: name 'url' is not defined If global url isn't there. The next function literally prints the result of the previous function. It will do more but as I can't even get it to print yet I haven't got to that stage.
has comment: http://stackoverflow.com/comment/84249450
upvote count: 0
linked to: http://stackoverflow.com/q/19158339
answer count: 2
has comment: http://stackoverflow.com/comment/84248782
tagged with: function
has comment: http://stackoverflow.com/comment/84248734
has title: Can't use the variables of a function in another function for Python
has answer: http://stackoverflow.com/a/48626079
score: -3
has comment: http://stackoverflow.com/comment/84248811
has comment: http://stackoverflow.com/comment/84248857
favorite count: 0
has answer: http://stackoverflow.com/a/48626013
type: Question
has comment: http://stackoverflow.com/comment/84249156
tagged with: scope
downvote count: 3
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84249292

http://stackoverflow.com/comment/84214094
score: 3
comment on: http://stackoverflow.com/q/48608814
type: Comment
type: QuestionComment
has text: The `sleep` commands *are* working; they are all just started simultaneously, because each `if` statement is run in the background.

http://stackoverflow.com/q/48638760
has body: I've been working on a CNN to localize a coin in an image. The CNN outputs a bounding box for the coin (x_min, y_min, x_max, y_max) and a few probabilities image_contains_coin, image_doesnt_contain_coin, coin_too_close (if the coin is too close to the camera), and dirty_coin if the coin is dirty (not clean/shiny). So so I'm using the results of the last nn layer's mat mul for the bounding box outputs directly and the probabilities go through an extra sigmoid function. If there is no coin in the image, then the error of the bounding box and the 2 remaining probabilities should be ignored. The error is calculated as RMS error of the bounding box plus the cross entropy error of the sigmoid/probability outputs. I was wondering if this (the following code) is the correct way to do this kind of thing in tensorflow? and if there are any problems with my ideas or code? Just to see where the outputs are in the array: output_x1 = 0 output_y1 = 1 output_x2 = 2 output_y2 = 3 output_is_coin = 4 output_is_not_coin = 5 output_is_too_close = 6 output_is_dirty = 7 num_outputs = 8 And the output layer and cost model: with tf.variable_scope('output'): # Output, class prediction out = cnn.output_layer(fc1, 256, num_outputs, 'out') out_for_error = out # Slice up the outputs and add a sigmoid to the probabilities aabb_out = tf.slice(out, [0,0], [-1,4]) prob_out = tf.slice(out, [0,4], [-1,4]) prob_out = tf.nn.sigmoid(prob_out) self.out = tf.concat([aabb_out, prob_out], 1, 'O') with tf.variable_scope('error'): # if the image is not of a plate, then the error for all other outputs needs # to be ignored. This is done by replacing those components of the output # array with the desired values (from training data) rather than the output # of the nn image_is_plate = tf.slice(image_infos, [0,4], [-1,1]) is_plate_mask = tf.constant([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0]) not_plate_mask = tf.constant([0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0]) error_mask = tf.add(tf.multiply(is_plate_mask, image_i…
tagged with: python
downvote count: 1
tagged with: conv-neural-network
tagged with: deep-learning
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/48639236
tagged with: tensorflow
favorite count: 0
type: Question
has title: Compicated error model in Tensorflow
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/133824862
type: Comment
type: AnswerComment
has text: @Superior: https://imgs.xkcd.com/comics/account_problems.png
comment on: http://stackoverflow.com/a/48521817
score: 2

http://stackoverflow.com/q/48493226
has answer: http://stackoverflow.com/a/48493246
type: Question
has body: ↑ Yes, it does. Python 2.7.13 I want to input 0 for the first prompt, then .37 for then next, so it comes out to .481 For some reason, and I know I've messed up, I cannot add the 'second' variable defined above, and the 'overallheight' value is not working: u1 = 12.5 first = .481 u2 = 2 length = u1 * 12 second = u2 / 64 overallheight = first - second #this line is not subtracting height_multiply = overallheight / .3075 width_multiply = length / 108 def calc(): x = float(raw_input("first prompt")) y = float(raw_input("second prompt")) y1 = (y - .0625) * height_multiply x1 = x * width_multiply y2 = y1 + second #this is the 'second' that needs to be added print("(%s,%s)") % (x1, y2) while 1&gt;0: calc()`
linked to: http://stackoverflow.com/q/2958684
tagged with: python
tagged with: variables
has comment: http://stackoverflow.com/comment/83979714
score: -1
has title: Cannot add variable to number Python
tagged with: python-2.7
duplicate of: http://stackoverflow.com/q/2958684
has comment: http://stackoverflow.com/comment/83979651
type: AnsweredQuestion
downvote count: 2
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83979679
favorite count: 0
accepted answer: http://stackoverflow.com/a/48493246

http://stackoverflow.com/comment/84021300
type: QuestionComment
comment on: http://stackoverflow.com/q/48513205
has text: @davedwards That's not what the argument to [`readlines`](https://docs.python.org/3/library/io.html#io.IOBase.readlines) does either.
score: 1
type: Comment

http://stackoverflow.com/comment/84144221
has text: @CL, thanks for the link!
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48528300

http://stackoverflow.com/q/48516379
tagged with: python
has comment: http://stackoverflow.com/comment/84027650
has body: I have a bunch of users and want to get a list of all the products they have bought. I currently do this with list_of_products = [user.products.all() for user in all_users] Where the User table and the Product table are connected by a many-to-many relationship. I noticed that this does not scale very well. If the number of users increases, it can take quite a while. I am trying to understand whether this is due to a overhead when performing a call or whether this is just the scaling because more products are needed? Basically, what is the fastest way to retrieve all products for a list of users. Just in case, here are the tables class User(db.Model): id = db.Column(db.Integer, primary_key=True) ... products = db.relationship('product', secondary=sales, lazy='dynamic') class Product(db.Model): id = db.Column(db.Integer, primary_key=True) ... sales = db.Table( 'sales', db.Column('product_id', db.Integer, db.ForeignKey('product.id')), db.Column('user_id', db.Integer, db.ForeignKey('user.id')) )
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/97197
linked to: http://stackoverflow.com/q/6542967
has comment: http://stackoverflow.com/comment/84027351
has title: optimize multiple sqlalchemy queries
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/84028044
tagged with: postgresql
type: UnansweredQuestion

http://stackoverflow.com/a/48532973
has comment: http://stackoverflow.com/comment/84062743
type: Answer
has body: The problem lies in both your objective function and the constraints. Since you are using scipy's minimize function, you must minimize the negative of the objective function to find the maximum of the function (It is slightly tricky). #objective function to maximize def objective(x): return -1.0*(x[0]*Reg + x[1]*Lat + x[2]*Moc) You have also incorrectly typed the inequality functions. If you look at the scipy documentation, all inequalities are in the form g(x)>=0. So, for example, if you want x2 &lt;= 125, you must multiply by negative 1 (to switch the inequality), then add 125 which gets: g(x) = 125-x2 >= 0. So for the rest of your constraints: #constraints def cons_total_production(x): return (-1.0*sum(x))+500 def cons_choc(x): return (-1.0*x[2])+125 def cons_milk(x): return (-1.0*sum(x[1:]))+350 Which will give you the outputs: fun: -918.7499999999989 jac: array([-1.25, -2. , -2.25]) message: 'Optimization terminated successfully.' nfev: 35 nit: 7 njev: 7 status: 0 success: True x: array([ 150., 225., 125.]) fun: -890.62499998809 jac: array([-1.25, -2. , -2.25]) message: 'Optimization terminated successfully.' nfev: 10 nit: 2 njev: 2 status: 0 success: True x: array([ 187.5, 187.5, 125. ]) Linear programming is so cool! Hope it helps :)
accepted answer of: http://stackoverflow.com/q/48532652
score: 3
answers question: http://stackoverflow.com/q/48532652
has comment: http://stackoverflow.com/comment/84061667
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48567564
has body: You can use ModelCheckpoint https://keras.io/callbacks/#modelcheckpoint to save the best model while training if instead, you want to save only after 1k epoch I would simply train the model for 1k epochs and then call model.save('model.h5')
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48559103

http://stackoverflow.com/a/49858788
type: Answer
has body: This is now possible in XlsxWriter version 1.0.4. See the databar Conditional Formatting Options. For you case you could do something like this: worksheet.conditional_format('G2:I80', {'type': 'data_bar', 'min_color': 'red', 'max_color':'green', 'data_bar_2010': True, })
upvote count: 2
has comment: http://stackoverflow.com/comment/129584441
downvote count: 0
answers question: http://stackoverflow.com/q/48527270
score: 2

http://stackoverflow.com/a/48623387
upvote count: 1
answers question: http://stackoverflow.com/q/48621712
has body: that would be very simple: (require '[net.cgrand.enlive-html :as enlive]) (let [data (enlive/html-resource (java.net.URL. "https://www.stackoverflow.com")) all-refs (enlive/select data [:a])] (first all-refs)) ;;=&gt; {:tag :a, :attrs {:href "https://stackoverflow.com", :class "-logo js-gps-track", :data-gps-track "top_nav.click({is_current:true, location:1, destination:8})"}, :content ("\n " {:tag :span, :attrs {:class "-img"}, :content ("Stack Overflow")} "\n ")} the all-refs collection would contain all the links from page in enlive representation form. (let [data (enlive/html-resource (java.net.URL. "https://www.stackoverflow.com")) all-refs (enlive/select data [:a])] (map #(-&gt; % :attrs :href) all-refs)) would for example collect all the href values from links
type: Answer
accepted answer of: http://stackoverflow.com/q/48621712
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48638541
type: AcceptedAnswer
downvote count: 0
has body: Ok, lets go through it line by line. Personally I don't think map is very idiomatic in Python so I would write this: maxLen = max(map(len, myList)) As a generator expresion: max_len = max(len(item) for item in my_list) The second version is almost plain English: let max_len be the maximum value among the length of each item in my_list. The best way to understand something in Python is just fire up the REPL and try it. So if you have my_list as a list of lists: my_list = [[1], [1, 2], [1, 2, 3]] The above will get you the length of the largest item: 3 Now you want to make every item the same size. How can you do that? One way is to append None items to it. For each item in the list, you test if the length of the item is smaller then the largest item in the list and it is almost plain English: for item in list: # for each item in the list while len(item) &lt; max_len: # while the item length is smaller than 3 item.append(None) # append None to the item You may want to do a bit of premature optimization and call extend once instead of calling append several times because you think performance will be better this way (but you can't really tell it unless you have profiled both solutions): for item in list: if len(item) &lt; max_len: item.extend([None] * (max_len - len(item))) Now what is going on here? In Python, list + list concatenates two copies of list, and list * 3 is the same as list + list + list. So in the first iteration of the for loop, item is [1], len(item) is 1 and max_len - len(item) is 3 - 1. Finally, [None] * 2 is [None, None] so after the call to extend the first item will be [1, None, None]. Same thing for the second item, its length is 2, 3 minus 2 is one and it will end up as [1, 2, None]. The 3rd item has the same length as max_len (3) so the if condition is false. The result will be: [[1, None, None], [1, 2, None], [1, 2, 3]] All lists in the list of lists now have the same size, 3. For the sake of completion, for such a small list the extend versio…
accepted answer of: http://stackoverflow.com/q/48638004
has comment: http://stackoverflow.com/comment/84273818
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48638004
score: 5

http://stackoverflow.com/comment/84208443
has text: Generate a random float between 0, 1. See documentation https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.rand.html
type: Comment
comment on: http://stackoverflow.com/a/48606040
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84209561
score: 2
has text: I'm not sure I'm following you on this - if you have access to the original document and its contents, why are you trying to rebuild it?
type: Comment
comment on: http://stackoverflow.com/q/48606567
type: QuestionComment

http://stackoverflow.com/q/48624306
answer count: 1
downvote count: 1
tagged with: unit-testing
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48625057
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I have a python file which defines some endpoints using flask each doing some computation and return a JSON (POST method). I want to do unit testing on this in order to do this I want to be able to access the app I created in one python file in another file so I can test my endpoints. I see a lot of this on the internet : from source.api import app from unittest import TestCase class TestIntegrations(TestCase): def setUp(self): self.app = app.test_client() def test_thing(self): response = self.app.get('/') assert &lt;make your assertion here&gt; It doesn't explain how I can define and access my app in another file. This might be a stupid question but I really don't see how. My app is defined as follows: from flasgger import Swagger from flask import Flask, jsonify, request from flask_cors import CORS import os def init_deserializer_restful_api(): # Initiate the Flask app app = Flask(__name__) Swagger(app) CORS(app) # Handler for deserializer @app.route("/deserialize", methods=['POST']) def handle_deserialization_request(): pass I have many other end points in this fashion. Should i just do: import my_file_name Thanks!!
tagged with: flask
linked to: http://stackoverflow.com/q/419163
has title: Access flask app endpoints in another python file?
score: 1
has comment: http://stackoverflow.com/comment/84247605

http://stackoverflow.com/comment/84248400
score: 0
type: AnswerComment
has text: You're going to have to upload it somewhere you can access. S3 Perhaps?
comment on: http://stackoverflow.com/a/48541473
type: Comment

http://stackoverflow.com/q/48589457
has comment: http://stackoverflow.com/comment/84176122
tagged with: hash
score: 1
has comment: http://stackoverflow.com/comment/84176191
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84177265
has answer: http://stackoverflow.com/a/48590081
accepted answer: http://stackoverflow.com/a/48590081
linked to: http://stackoverflow.com/q/1663807
type: AnsweredQuestion
tagged with: python-3.x
has body: I have 3 tuples: o = (0, 1) n = ((1, 2), (1,)) c = ((30, 70), (20,)) that I want to put in a nested dictionary. The desired output is: {'0':{'1':30, '2':70}, '1':{'1':20}} I tried the following: for x in enumerate(o): graph[str(o[x])] = {} for y in enumerate(n): for z in enumerate(y): graph[str(o[x])][n[x][z]] = c[x][z] Which does not work, I am not sure how to proceed.
has title: Python: Looping and nested dictionaries
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/22171558
answer count: 1
tagged with: loops
favorite count: 0
type: Question

http://stackoverflow.com/comment/84196076
type: AnswerComment
comment on: http://stackoverflow.com/a/48599702
has text: What's the point of having a function here? Just to access value based on index? How is `access(a,(0,0,0))` better than `a[0][0][0]`?
score: 2
type: Comment

http://stackoverflow.com/comment/84239073
type: AnswerComment
has text: to keep more than 10 tags `df=df['count' > 10]` . for later I would suggest you to post new question.
comment on: http://stackoverflow.com/a/48619610
score: 0
type: Comment

http://stackoverflow.com/comment/84085065
has text: Please post the full traceback in your question. People tend not to read comments and you can't format properly in comments.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48544489
type: Comment

http://stackoverflow.com/a/51088908
answers question: http://stackoverflow.com/q/48526360
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48526360
has body: I digged myself a lot, and what @Charles Duffy commented above seems most proper way. You should have two separate dependency lists: One with the dependencies a human has decided you need (which shouldn't contain transitive dependencies); one with the frozen list that reflects what you tested against (which should contain transitive dependencies) However, Recently with the release of pipenv, I think this is the better way to keep track of dependencies. It's like npm, much easier to maintain requirements and creating venv. It automatically creates and manages a virtualenv for your projects, as well as adds/removes packages from your Pipfile as you install/uninstall packages. It also generates the ever–important Pipfile.lock, which is used to produce deterministic builds.
type: AcceptedAnswer
downvote count: 0
score: 5

http://stackoverflow.com/q/48552043
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/48552604
has body: (Bear with me, I think in C and not Python, so you're probably about to see some real dumb stuff...) I have many (100+) different C structs, pulled into Python (version 3.5.1) as bytes, that I want to be able to access using the original C struct's variable names. Here's a simple example. In Python I have received these bytes: # In Python: example1_bytes = b'\x08\x09\x0a\x0b' Assume these bytes were provided by something running C, using a struct of the following format: // In C: struct example1 { uint8_t val1; uint8_t val2; uint8_t val3; uint8_t val4; }; How can I process example1_bytes so that I can access them like this: # In Python: result = process_example1_bytes(example1_bytes) print(result.val1) # Prints "8" print(result.val2) # Prints "9" # Et cetera Taking it a step further, what if the C struct is more complex and contains arrays and/or sub-structs? For example, something like this: // In C: struct substruct { uint8_t ss_val1; uint8_t ss_val2; }; struct example2 { uint8_t val1; uint8_t val2; struct substruct ss[8]; }; How can I process example2_bytes so that I can access them like this: # In Python: result = process_example2_bytes(example2_bytes) print(result.val1) print(result.ss[3].ss_val2) I've experimented a bit using Python's struct unpack, which returns tuples and I think is a step in the right direction, but it hasn't quite gotten me to the usable solution I want. I'm not sure if I need to go down the namedtuple path or take some other direction.
answer count: 1
favorite count: 0
has title: Given bytes that map to a C struct, how to access the bytes via the C struct's variable names
has comment: http://stackoverflow.com/comment/84100434
type: Question
upvote count: 5
tagged with: python
linked to: http://stackoverflow.com/q/1825715
has answer: http://stackoverflow.com/a/48552604
tagged with: python-3.x
type: AnsweredQuestion

http://stackoverflow.com/a/78238957
score: 3
has body: A little late to the party, but if anybody is interested, I published namedpipe package on PyPI to enable named pipes in both Posix and Windows. Here is a link to the GitHub repo. Its API is modeled after built-in open() and IO classes. A quick usage sample: import subproces as sp from namedpipe import NPopen with NPopen('r+') as pipe: # bidirectional (duplex) binary pipe # - for an inbound pipe, specify the read access mode 'rb' or 'rt' # - for an outbound pipe, specify the write access mode 'wb or 'wt' sp.run(['my_client', pipe.path]) stream = pipe.wait() # Wait for the client to connect and create a stream b = stream.read(64) # read 64 bytes from the client in_bytes = bytearray(128) nread = stream.readinto(in_bytes) # read 128 bytes of data from client b_rest = stream.readall() # read all bytes sent by the client, block stream.write(out_bytes) # send bytes in out_bytes to the client Note: I wrote it a few years ago to work with the ffmpegio but I haven't yet encountered a use-case myself ironically. So, I hope someone can make a good use of it (although it is very much in a beta stage).
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/48542644
downvote count: 0

http://stackoverflow.com/q/48617050
type: Question
has title: AttributeError: 'NoneType' object has no attribute 'shape' What is wrong in my code?
has answer: http://stackoverflow.com/a/48617139
answer count: 1
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48617139
has body: I got an error,AttributeError: 'NoneType' object has no attribute 'shape'.I wrote codes in views.py import os import cv2 from pathlib import Path import random path = Path(__file__).parent path /= "../../image1" path1 = Path(__file__).parent path1 /= "../../image2" index_list =[] for i in path.iterdir(): i = str(i) print(i) if i.split(".")[-1].lower() in {"jpeg", "jpg", "png"}: list_img = cv2.imread(i) index_list.append(list_img) num = 0 for j in path.iterdir(): j = str(j) if j.split(".")[-1].lower() in {"jpeg", "jpg", "png"}: img = cv2.imread(j) num += 1 random_int = random.randint(0, 9) index = index_list[random_int] height1 = index.shape[0] width1 = index.shape[1] print(height1) print(width1) When I run this code,I got an error, height1 = index.shape[0] AttributeError: 'NoneType' object has no attribute 'shape' . In image1's folder,5 images are in there like photo1,photo2,photo3,photo4,photo5.I debuted this program,so I found photo3 causes this error,and I deleted photo3 from image1's folder.And I run this program again,photo2 causes this error.I really cannot understand why this error happens.I think maybe wrong path of the folder causes this error,but it is wrong.How should I fix this?What is wrong in my code?
tagged with: python

http://stackoverflow.com/q/48569659
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48571498
upvote count: 2
possible better answer: http://stackoverflow.com/a/48573292
downvote count: 0
tagged with: django
tagged with: sorting
tagged with: django-rest-framework
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48573292
accepted answer: http://stackoverflow.com/a/48571498
has body: Specifically, I am looking to get a query of users. My User model has a first_name and last_name field. What I need to do is order the request.user at the top of the results, and the remaining users in alphabetical order by last_name, first_name. The last part is easy: q = User.objects.all().order_by('last_name', 'first_name') However I am not sure how to ensure that the request.user is the first result in the query. This is all being done for a django rest framework view, and thus (I believe) I need to have it done through a query which is passed on to the serializer.
has title: django- how would I create a sort for a query to put one specific element first, then remaining by some field?
score: 2

http://stackoverflow.com/q/48591021
has comment: http://stackoverflow.com/comment/84179478
type: Question
has answer: http://stackoverflow.com/a/48591160
type: AnsweredQuestion
has title: Remove substring in a column pandas
has answer: http://stackoverflow.com/a/48591226
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84179334
possible better answer: http://stackoverflow.com/a/48591226
answer count: 2
tagged with: pandas
upvote count: 3
has comment: http://stackoverflow.com/comment/84179503
has body: I have a dataframe where one column has strings that sometimes contain a word and parentheses around the value I want to keep. How do I do remove them? Here's what I have: import pandas as pd df = pd.read_csv("Espacios_@cronista.csv") del df['Espacio'] df[df['Tamano'].str.contains("Variable")] Output I have: Tamano Subastas Imp Fill_rate 0 Variable (300x600) 43 13 5.99 1 Variable (266x600) 43 5 4.44 2 266x600 43 5 4.44 Output I need: Tamano Subastas Imp Fill_rate 0 300x600 43 13 5.99 1 266x600 43 5 4.44 2 266x600 43 5 4.44
downvote count: 0
has comment: http://stackoverflow.com/comment/84179569
accepted answer: http://stackoverflow.com/a/48591160
favorite count: 0

http://stackoverflow.com/comment/84172557
comment on: http://stackoverflow.com/a/48587689
score: 0
has text: what i mean by fragments is for the suffix # at the end of the URL.. btw ur answer is right! thanks a lot :)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83993801
comment on: http://stackoverflow.com/q/48499681
has text: check this package https://github.com/ottoyiu/django-cors-headers
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48501318
has comment: http://stackoverflow.com/comment/83996349
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83998483
has comment: http://stackoverflow.com/comment/84000162
answers question: http://stackoverflow.com/q/48500717
has body: Of course this is possible: Eclipse - Windows - Preferences - PyDev - Interpreters - Python Interpreter - New... Then you can seelct the interpreter per project: Right-click project - Properties - PyDev-Interpreter/Grammar - Interpreter - Pick from list
has comment: http://stackoverflow.com/comment/83999772
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84000052
has comment: http://stackoverflow.com/comment/83999956
has comment: http://stackoverflow.com/comment/83999315
accepted answer of: http://stackoverflow.com/q/48500717

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/48620804
tags question: http://stackoverflow.com/q/48625299

http://stackoverflow.com/comment/84255087
type: Comment
has text: For starters, there must be quotation marks around `"student == 'current' and grade == 'fail'"`.
type: QuestionComment
comment on: http://stackoverflow.com/q/48628883
score: 0

http://stackoverflow.com/q/48518891
has answer: http://stackoverflow.com/a/48524302
has comment: http://stackoverflow.com/comment/84033587
answer count: 1
has comment: http://stackoverflow.com/comment/84032590
upvote count: 1
tagged with: macos
tagged with: ghostscript
favorite count: 0
type: Question
has title: TypeError: TypeError("object of type 'NoneType' has no len()",) while convert pdf to image
has comment: http://stackoverflow.com/comment/84045076
has comment: http://stackoverflow.com/comment/84041793
has body: I am building API which converts uploaded pdf to image based on Django REST framework, on MacOS env. Of course, installed imagemagick and ghostscript well on the system. Here is my code snippet. from wand.image import Image try: with Image(filename=pdffile, resolution=300) as img: for i, page in enumerate(img.sequence): filename = '{}-{}.jpg'.format(imagefilename, i + 1) file ='{}/{}'.format(tmp_dir, filename) Image(page).save(filename=file) filelist.append(filename) except WandException as e: print e except TypeError as e: print e But I am getting this error: Exception TypeError: TypeError("object of type 'NoneType' has no len()",) in bound method Image.del of wand.image.Image: (empty) ignored At the line: with Image(filename=pdffile, resolution=300) as img: Here is trackback: Internal Server Error: /api/v1/admin/upload/pdf Traceback (most recent call last): File "/Volumes/WORK/Projects/BazeanAnalytics/web-app-baz-analytics/API/data-api/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Volumes/WORK/Projects/BazeanAnalytics/web-app-baz-analytics/API/data-api/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Volumes/WORK/Projects/BazeanAnalytics/web-app-baz-analytics/API/data-api/venv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Volumes/WORK/Projects/BazeanAnalytics/web-app-baz-analytics/API/data-api/venv/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Volumes/WORK/Projects/BazeanAnalytics/web-app-baz-analytics/API/data-api/venv/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "/Volumes/WORK/Projects/BazeanAnalytic…
has comment: http://stackoverflow.com/comment/84041892
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84034266
downvote count: 0
has comment: http://stackoverflow.com/comment/84032945
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84032427
has comment: http://stackoverflow.com/comment/84036998
has comment: http://stackoverflow.com/comment/84032466
has comment: http://stackoverflow.com/comment/84045182
tagged with: imagemagick
score: 1
has comment: http://stackoverflow.com/comment/84032798

http://stackoverflow.com/a/48590700
score: 1
answers question: http://stackoverflow.com/q/48582506
type: Answer
has comment: http://stackoverflow.com/comment/84268066
has comment: http://stackoverflow.com/comment/84275845
has body: Affinity propagation needs two asymmetric n by n matrixes. Your input matrix is another copy. Do the math: what amount of memory do you need for n=1 million and double precision times three matrixes (maybe there will even be yet another copy)? Do you have enough memory for TBs of distance data? Otherwise, you should probably use an algorithm that does not use a distance matrix.
has comment: http://stackoverflow.com/comment/84237161
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84270498
has comment: http://stackoverflow.com/comment/84337866
has comment: http://stackoverflow.com/comment/84256436

http://stackoverflow.com/comment/84019355
comment on: http://stackoverflow.com/q/48511429
type: Comment
score: 0
type: QuestionComment
has text: @juanpa.arrivillaga - in this case, though, we're dealing with two threads running in the same process. They both have the same instance of `one`.

http://stackoverflow.com/comment/84187351
comment on: http://stackoverflow.com/a/48595128
type: Comment
has text: @MadPhysicist In python2 it wont create a list in memory while `.items()` will
type: AnswerComment
score: 0

loops
tags question: http://stackoverflow.com/q/48579982
tags question: http://stackoverflow.com/q/48632229
tags question: http://stackoverflow.com/q/48541843
tags question: http://stackoverflow.com/q/48552512
tags question: http://stackoverflow.com/q/48554495
tags question: http://stackoverflow.com/q/48585532
tags question: http://stackoverflow.com/q/48519553
tags question: http://stackoverflow.com/q/48492265
tags question: http://stackoverflow.com/q/48494296
tags question: http://stackoverflow.com/q/48632452
tags question: http://stackoverflow.com/q/48521710
tags question: http://stackoverflow.com/q/48613728
tags question: http://stackoverflow.com/q/48517177
tag name: loops
tags question: http://stackoverflow.com/q/48645336
tags question: http://stackoverflow.com/q/48518993
tags question: http://stackoverflow.com/q/48615285
tags question: http://stackoverflow.com/q/48560727
tags question: http://stackoverflow.com/q/48590311
tags question: http://stackoverflow.com/q/48603998
tags question: http://stackoverflow.com/q/48585241
tags question: http://stackoverflow.com/q/48599009
tags question: http://stackoverflow.com/q/48568797
tags question: http://stackoverflow.com/q/48600784
tags question: http://stackoverflow.com/q/48637042
tags question: http://stackoverflow.com/q/48506985
tags question: http://stackoverflow.com/q/48609583
tags question: http://stackoverflow.com/q/48603827
tags question: http://stackoverflow.com/q/48522852
tags question: http://stackoverflow.com/q/48513205
tags question: http://stackoverflow.com/q/48579947
tags question: http://stackoverflow.com/q/48536802
tags question: http://stackoverflow.com/q/48548187
tags question: http://stackoverflow.com/q/48589457
type: Tag
tags question: http://stackoverflow.com/q/48585820
tags question: http://stackoverflow.com/q/48522316
tags question: http://stackoverflow.com/q/48513956
tags question: http://stackoverflow.com/q/48645464
tags question: http://stackoverflow.com/q/48511102
tags question: http://stackoverflow.com/q/48603340
tags question: http://stackoverflow.com/q/48530872
tags question: http://stackoverflow.com/q/48549798
tags question: http://stackoverflow.com/q/48640937
tags question: http://stackoverflow.com/q/48583030
tags question: http://stackoverflow.com/q/48595039
tags question: http://stackoverflow.com/q/48521306
tags question: http://stackoverflow.com/q/48641425
tags question: http://stackoverflow.com/q/48520394

http://stackoverflow.com/a/48826668
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48518413
has body: Resolved by setting: LOGGER1.propagate = False
answers question: http://stackoverflow.com/q/48518413
type: Answer
score: 0

http://stackoverflow.com/comment/83992503
has text: @GerhardBarnard Development is not exclusively about code and neither is StackOverflow. ["...the best Stack Overflow questions have a bit of source code in them"](https://stackoverflow.com/help/on-topic). It's not the best question by these standards, but I don't see that it's bad. This was a "a practical, answerable problem that is unique to software development".
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48498560
score: 0

http://stackoverflow.com/a/48563762
answers question: http://stackoverflow.com/q/48563526
type: Answer
has body: Which z to take it's a bit up to you. From the plot itself it's hard to say but my guess is that it's linear (the simplest option). Taking your code and adding the z axis you can do something like this import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt from math import exp,sin,cos from pylab import * mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') a=0.05 b=0.10 # took the liberty of reducing the max value for th # as it was giving you values of the order of e42 th=np.linspace(0, 50, 10000) x=a*exp(b*th)*cos(th) y=a*exp(b*th)*sin(th) z=np.linspace(0,2, 10000) # creating the z array with the same length as th ax.plot(x, y, z) # adding z as an argument for the plot ax.legend() plt.show() You can play with your a and b parameters to get the elliptical shape you want. You can also play with the definition of z to make it exponential, or logarithmic in growth.. or something else entirely. BTW, your imports are a bit redundant and probably some funtions from one package are being shadowed by another package.
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/a/48935483
has comment: http://stackoverflow.com/comment/86330630
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/113468786
has body: There seems to be a bug in chromedriver. I narrowed it down, and two files seem to be the culprit: {user-data-dir}/Local State and {user-data-dir}/{profile-directory}/Preferences. If you do not specify profile-directory, it will be 'Default'. Chrome/Chromium doesn't seem to be able to read these files, even if you properly close chromedriver, using browser.quit(). You'll need to delete the files in order to be able to start chromedriver again, using the same profile. I used the following code in my finally block, in order to delete the files: if browser is not None: browser.quit() time.sleep(1) delete_paths = ['../selenium/chrome_profile/Local State', '../selenium/chrome_profile/Default/Preferences'] for delete_path in delete_paths: if os.path.exists(delete_path): os.remove(delete_path)
score: 9
answers question: http://stackoverflow.com/q/48571886
downvote count: 0
has comment: http://stackoverflow.com/comment/85803789

http://stackoverflow.com/comment/84150446
type: QuestionComment
has text: No, time it's the current time which it's dynamic because I'm queering the db every 2 minutes and Time_Start it's the time when an event was activated(so it's static). So it's time(curent_time) - Time_Start(when event activated) = duration
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48566333

http://stackoverflow.com/comment/84189624
type: AnswerComment
comment on: http://stackoverflow.com/a/48596350
type: Comment
score: 0
has text: Can you add timings for 1000 rows?

http://stackoverflow.com/comment/84222541
score: 0
has text: @alexis I can run it on its own, I put a shebang comment at the top: `#!/usr/bin/env python3`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48612859

http://stackoverflow.com/q/48531039
has answer: http://stackoverflow.com/a/48531594
has title: Create variable of weights from array
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: deep-learning
tagged with: tensor
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/48531594
type: Question
has body: I have an array : [1, 4, -10, 3, 5]. I'm trying to create a Variable of weights using that array. After doing training, I print the weight as: result = sess.run(w) print(result) the result is just the array in the format [1, 4, -10, 3, 5]. How I tried to create a Variable from the array: c = [1, 4, -10, 3, 5] for i in range(len(c)): w = tf.Variable(c[i], name='weights') Obviously, this weight result is wrong, and I've spent hours looking at documentation and SO posts. How do I create a Variable using that array?

http://stackoverflow.com/q/48522471
has title: Offline installation of Django
duplicate of: http://stackoverflow.com/q/11091623
score: 1
answer count: 1
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/11091623
type: Question
has answer: http://stackoverflow.com/a/48522543
tagged with: pip
tagged with: django
accepted answer: http://stackoverflow.com/a/48522543
tagged with: python
upvote count: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35144184
has body: As in: Can I install Django as offline in Windows 7? ... I am trying to install Django from a file. My RHEL 7 is in a closed network. From another computer I have fetched version 2.0.1 from https://github.com/django/django/releases. running install-command results in: pip3.6 install django-2.0.1.tar.gz Processing ./django-2.0.1.tar.gz Collecting pytz (from Django==2.0.1) Could not fetch URL https://pypi.python.org/simple/pytz/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skipping Could not find a version that satisfies the requirement pytz (from Django==2.0.1) (from versions: ) No matching distribution found for pytz (from Django==2.0.1) The error corresponds to the fact, that my system does not have access through the proxy. How can I do the install without the need of access to outside world? The possible duplicate: Python Packages Offline Installation didn't mention pytz-package

http://stackoverflow.com/comment/84069990
type: Comment
type: QuestionComment
has text: @zaidfazil I tried this just now and it does not change anything. DB is still not populated
comment on: http://stackoverflow.com/q/48536993
score: 0

http://stackoverflow.com/q/48584712
has answer: http://stackoverflow.com/a/48615070
tagged with: asynchronous
type: AnsweredQuestion
has body: I have seen a few variants of my question but not quite exactly what I am looking for, hence opening a new question. I have a Flask/Gunicorn app that for each request inserts some data in a store and, consequently, kicks off an indexing job. The indexing is 2-4 times longer than the main data write and I would like to do that asynchronously to reduce the response latency. The overall request lifespan is 100-150ms for a large request body. I have thought about a few ways to do this, that is as resource-efficient as possible: Use Celery. This seems the most obvious way to do it, but I don't want to introduce a large library and most of all, a dependency on Redis or other system packages. Use subprocess.Popen. This may be a good route but my bottleneck is I/O, so threads could be more efficient. Using threads? I am not sure how and if that can be done. All I know is how to launch multiple processes concurrently with ThreadPoolExecutor, but I only need to spawn one additional task, and return immediately without waiting for the results. asyncio? This too I am not sure how to apply to my situation. asyncio has always a blocking call. Launching data write and indexing concurrently: not doable. I have to wait for a response from the data write to launch indexing. Any suggestions are welcome! Thanks.
has title: Flask: spawning a single async sub-task within a request
possible better answer: http://stackoverflow.com/a/48588092
answer count: 2
accepted answer: http://stackoverflow.com/a/48615070
has answer: http://stackoverflow.com/a/48588092
tagged with: multithreading
type: Question
score: 0
tagged with: python

http://stackoverflow.com/q/48592266
linked to: http://stackoverflow.com/q/24615895
tagged with: python
has body: I am using the Drive API to download an image. Following their file downloading documentation in Python, I end up with a variable fh that is a populated io.BytesIO instance. I try to save it as an image: file_id = "0BwyLGoHzn5uIOHVycFZpSEwycnViUjFYQXR5Nnp6QjBrLXJR" request = 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 {} {}%.'.format(file['name'], int(status.progress() * 100))) fh.seek(0) image = Image.open(fh) # error The error is: cannot identify image file &lt;_io.BytesIO object at 0x106cba890&gt;. Actually, the error does not occur with another image but is thrown with most images, including the one I linked at the beginning of this post. After reading this answer I change that last line to: byteImg = fh.read() dataBytesIO = io.BytesIO(byteImg) image = Image.open(dataBytesIO) # still the same error I've also tried this answer, where I change the last line of my first code block to byteImg = fh.read() image = Image.open(StringIO(byteImg)) But I still get a cannot identify image file &lt;StringIO.StringIO instance at 0x106471e60&gt; error. I've tried using alternates (requests, urllib) with no fruition. I can Image.open the the image if I download it manually. This error was not present a month ago, and has recently popped up into the application this code is in. I've spent days debugging this error with no success and have finally brought the issue to Stack Overflow. I am using from PIL import Image.
has answer: http://stackoverflow.com/a/48597455
tagged with: google-drive-api
tagged with: stringio
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48597455
has title: PIL cannot identify image file for a Google Drive image streamd into io.BytesIO
tagged with: bytesio
linked to: http://stackoverflow.com/q/31077366
type: Question
type: AnsweredQuestion
tagged with: python-imaging-library

http://stackoverflow.com/comment/84240765
comment on: http://stackoverflow.com/a/48621186
score: 0
type: AnswerComment
type: Comment
has text: I don't have linux. Is there a way to install it on windows with pip?

http://stackoverflow.com/a/48614697
has body: You can retrieve a list of document topics from a gensim LDA with Ldamodel.show_topics() and then classify a new document with Ldamodel.get_document_topics(doc) where doc is a document bag-of-words vector. https://radimrehurek.com/gensim/models/ldamodel.html
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48606331
answers question: http://stackoverflow.com/q/48606331
type: Answer
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/a/48504747
has comment: http://stackoverflow.com/comment/84003960
downvote count: 1
has comment: http://stackoverflow.com/comment/84003581
has comment: http://stackoverflow.com/comment/84003627
has body: You can try something like this: from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^contacts/', include('appname.contacts.urls')), url(r'^comments/', include('appname.urls')), url(r'^subscriptions/', include('appname.partner.urls')), url(r'^', RedirectView.as_view(url="/admin/")) ] This is what I've done in my project so whenever the user go to 127.0.0.1:8000 it redirects to /admin
type: Answer
score: -1
answers question: http://stackoverflow.com/q/48504649
has comment: http://stackoverflow.com/comment/84026971
upvote count: 0

http://stackoverflow.com/comment/84281833
has text: It doesn't give the expected outcome. The result is only correct for the first row. This should be the expected outcome: [ [0, 1, 1], [1, 1, 1], [0, 0, 1], [1, 0, 0] ]
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48641829
type: AnswerComment

http://stackoverflow.com/a/48611224
upvote count: 77
score: 76
has comment: http://stackoverflow.com/comment/87772058
has body: After searching hours together i found answer from Stackoverflow itself, where the answer is provided for different issue. And that solution worked here as well. Here is the solution for TF 1.x: tf.logging.set_verbosity(tf.logging.ERROR) For TF 2.x: tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) Source: Is there a way to suppress the messages TensorFlow prints?
downvote count: 1
has comment: http://stackoverflow.com/comment/92282970
answers question: http://stackoverflow.com/q/48608776
type: Answer
has comment: http://stackoverflow.com/comment/105445671
has comment: http://stackoverflow.com/comment/102289257

http://stackoverflow.com/q/48613469
has body: I'm attempting to create dicts of currency information from the coinmarketcap API and name each dict after the currency symbol. End goal: # see coinmarketcap data entered into the dict print(BTC['price'] + "\t$" + BTC['marketCap']) # add arbitrary data to the BTC dict that other dicts might not have BTC['founder'] = "Satoshi Nakamoto" # see data from multiple sources in any given dict print(BTC['symbol'] + " was founded by " + BTC['founder']) print(LTC['symbol'] + " " + LTC['isMineable'] + " mineable") BTC was founded by Satoshi Nakamoto LTC is mineable However, when I get coinMarketCapTicker['symbol'], and it's a string "BTC", I'm having a hard time creating a dict called BTC from that value. import requests import json tickerURL = "https://api.coinmarketcap.com/v1/ticker/?limit=100" request = requests.get(tickerURL) coinMarketCapTicker = request.json() while True: for x in coinMarketCapTicker tickerSymbol = x['symbol'] # load current symbol's dict with the rest of the data from the API tickerSymbol = {"symbol" : x['symbol'], "price" : x['price_usd'], "marketCap" : x['market_cap_usd']} break This makes a dict called 'tickerSymbol' that gets overwritten for every symbol, instead of dicts named BTC, ETH, LTC, etc I've tried this instead, but they don't work: x['symbol'] = {"symbol" : x['symbol'], "price" : x['price_usd'], "marketCap" : x['market_cap_usd']} and str(x['symbol']) = {"symbol" : x['symbol'], "price" : x['price_usd'], "marketCap" : x['market_cap_usd']} I'm a little stuck, any ideas?
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84223900
has comment: http://stackoverflow.com/comment/84224219
has comment: http://stackoverflow.com/comment/84223873
has comment: http://stackoverflow.com/comment/84223922
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84223916
downvote count: 0
has comment: http://stackoverflow.com/comment/84223849
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/84223958
has title: How do I name a Python dictionary after a variable?
has comment: http://stackoverflow.com/comment/84223806
has comment: http://stackoverflow.com/comment/84224135
has comment: http://stackoverflow.com/comment/84223724
favorite count: 0
has comment: http://stackoverflow.com/comment/84223994
type: Question
score: 1
has answer: http://stackoverflow.com/a/48614898

http://stackoverflow.com/comment/131812459
has text: @Dr.Snoopy I am not referring to gradient averaging (like A3C). Every family I mentioned above uses weight averages. For the last two cases, I mentioned specifically that weight averages "resemble" those operations. In fact, through arguments like the ones presented in the Bayesian MC Dropout paper, it is easy to show that "activation averaging" and weight averaging are very closely related. Regardless of that though, weight averaging is still a reasonable operation to investigate, as it was in 2018, when a number of the above domains were already discovered.
comment on: http://stackoverflow.com/q/48560227
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84263767
has text: what do you think about the seq2seq implementation though? seems like there's something wrong there too
comment on: http://stackoverflow.com/q/48614675
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84178349
type: AnswerComment
comment on: http://stackoverflow.com/a/48590088
type: Comment
has text: Thanks for the quick response Ill have to try option 2 i guess. I already do option 1 in an earlier portion of the code but that doesn't really work too well. If I unplug one of the 7 connections on the linux machine it still will pass the ping response through one of the other lines even if i specify a diff IP address.
score: 0

http://stackoverflow.com/comment/84116193
comment on: http://stackoverflow.com/q/48560319
has text: Is the date string always going to be in the format d/m/y ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84212734
has text: Those will be in separate line
score: 0
comment on: http://stackoverflow.com/a/48606518
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84017325
has text: no problem, I've commented the code, I hope it is clear now
type: Comment
comment on: http://stackoverflow.com/a/48507644
score: 0
type: AnswerComment

http://stackoverflow.com/a/48595074
has comment: http://stackoverflow.com/comment/84189002
answers question: http://stackoverflow.com/q/48594989
has comment: http://stackoverflow.com/comment/84187197
has comment: http://stackoverflow.com/comment/84188847
has comment: http://stackoverflow.com/comment/84187480
has comment: http://stackoverflow.com/comment/84187182
has comment: http://stackoverflow.com/comment/84188819
has comment: http://stackoverflow.com/comment/84188042
has comment: http://stackoverflow.com/comment/84187256
type: Answer
has comment: http://stackoverflow.com/comment/84187290
has comment: http://stackoverflow.com/comment/84187457
has comment: http://stackoverflow.com/comment/84189034
has comment: http://stackoverflow.com/comment/84188789
has comment: http://stackoverflow.com/comment/84188970
score: 0
has body: You have Spark dataframe which you need to first convert into pandas. import pandas as pd lines = sqlContext.read.parquet("hdfs:////data/lab_01/") lines.registerTempTable("test_data") resultsDF = sqlContext.sql("select * from results").toDF() resDF=pd.DataFrame(resultDF) header = ["lab_key", "tray_id", "time", "gene_id", "source"] # removed pandas from below line resDF.to_csv("/data/results.csv", sep=",", columns = header)

http://stackoverflow.com/q/48605643
tagged with: youtube
downvote count: 1
has comment: http://stackoverflow.com/comment/84207657
has comment: http://stackoverflow.com/comment/112075296
has comment: http://stackoverflow.com/comment/112040663
has comment: http://stackoverflow.com/comment/84207585
score: 1
duplicate of: http://stackoverflow.com/q/55928904
tagged with: youtube-api
has comment: http://stackoverflow.com/comment/132192458
has title: Get the official music video from YouTube API
has comment: http://stackoverflow.com/comment/95630233
has body: Similar question: How to detect official artist channel using youtube api? The problem at hand is to find the official music video using the YouTube API. To be more specific: Not only put a filter to get only Music video as shown here: Youtube API - search only music videos The actual link in YouTube is this I can always go through some 5 results and choose based on views, but my search space is already large and I want to minimize it one query per song. A major problem with point 1 and 3 combined is that there is a chance of a fan-made cover to have more views. A working alternative I tried was like this: youtube_search(song_name + " VEVO"), This works of course only for big artists as you may have guessed. To actually do it, I figured if YouTube API only searched in the link in point 2 then the work is done. Is that possible or is there a better way?
favorite count: 0
linked to: http://stackoverflow.com/q/15121635
linked to: http://stackoverflow.com/q/55928904
has comment: http://stackoverflow.com/comment/84207698
has comment: http://stackoverflow.com/comment/84207640
has comment: http://stackoverflow.com/comment/95658701
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84207627
has comment: http://stackoverflow.com/comment/84207637
has comment: http://stackoverflow.com/comment/132170519
answer count: 0
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/31981358

http://stackoverflow.com/a/48489784
downvote count: 0
answers question: http://stackoverflow.com/q/48489694
has body: I think you need strftime for string format with astype for convert to float: df["Date"] = pd.to_datetime(df["Date"], '%d/%m/%Y').dt.strftime('%Y%m%d').astype(float) Solution with your real data is simplify, because is not necessary convert to datetimes: df = pd.read_excel('Linx Revenues.xls') df.columns = ['Date', 'Gross'] #print (df) df["Date"] = df["Date"].dt.strftime('%Y%m%d').astype(float) print (df) Date Gross 0 20171201.0 168.40 1 20171201.0 188.60 2 20171201.0 177.40 3 20171201.0 958.90 4 20171201.0 931.90 5 20171201.0 71.80 6 20171201.0 35.00 7 20171201.0 556.13 8 20171201.0 413.00 9 20171201.0 0.90 10 20171201.0 699.00 11 20171201.0 111.70 12 20171201.0 153.30 13 20171201.0 669.10 14 20171201.0 713.70 15 20171201.0 423.70 16 20171201.0 -2.00 17 20171202.0 80.50 18 20171202.0 213.40 19 20171202.0 1170.10 20 20171202.0 605.00 21 20171202.0 1275.30 22 20171202.0 202.30 23 20171202.0 120.00
has comment: http://stackoverflow.com/comment/83979115
type: Answer
accepted answer of: http://stackoverflow.com/q/48489694
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84095215
type: AcceptedAnswer

http://stackoverflow.com/a/51200423
upvote count: 6
has body: You setup the random seed only in numpy and not in tensorflow (in case it's the backend of keras in your case). Try to add this in your code: from numpy.random import seed seed(1337) from tensorflow import set_random_seed set_random_seed(1337) the detailed article about this topic here
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48562099
type: Answer

http://stackoverflow.com/a/48501867
upvote count: 1
answers question: http://stackoverflow.com/q/48501023
type: Answer
has body: You can use itertools.groupby to create a dict where key will be the food expiration date and value will be the number of times it occurs in the list &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; fridge = [Food("beer",4), Food("steak",1), Food("hamburger",1), Food("donut",3),] &gt;&gt;&gt; d = dict((k,len(list(v))) for k,v in groupby(sorted(l,key=lambda x: x.expiration), key=lambda x: x.expiration)) Here we specify groupby to group all elements of list that have same expiration(Note the key argument in groupby). The output of groupby operation is roughly equivalent to (k,[v]), where k is the group key and [v] is the list of values belong to that particular group. This will produce output like this: &gt;&gt;&gt; d &gt;&gt;&gt; {1: 2, 3: 1, 4: 1} At this point we have expiration and number of times a particular expiration occurs in a list, stored in a dict d. Next we need to create a list such that If an element is present in the dict d output it, else output 0. We need to iterate from 0 till max number in dict d keys. To do this we can do: &gt;&gt;&gt; [0 if not d.get(x) else d.get(x) for x in range(0, max(d.keys())+1)] This will yield your required output &gt;&gt;&gt; [0,2,0,1,1]
score: 1
downvote count: 0

http://stackoverflow.com/a/48580022
type: Answer
score: 0
has body: I think you will be able to do your statistics if modify your code like this num_rounds = 1e3 result_list = [] for i in range(num_rounds): try: result = run_experiment() result_list.append(result) except Exception as ex: # do statistics That way you have the exception as ex, you can check and store the type. If you also want to store the random input parameters than you should put the same try-except in your run_experiment function
answers question: http://stackoverflow.com/q/48579892

http://stackoverflow.com/comment/83975501
score: 0
has text: Really appreciate this, you wouldn't know of any documentation/guides I could take a look at to brush up on this type of thing?
type: Comment
comment on: http://stackoverflow.com/a/48491179
type: AnswerComment

http://stackoverflow.com/comment/84064141
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48534303
has text: you need to install it ? .. go to command promt and type pip install Orange
score: 0

http://stackoverflow.com/comment/84153039
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48578343
has text: Welcome to Stack Overflow! Here we expect error messages described the problem to be **in the question post itself as text**, not linked as images. Please, edit your question post and correct this. (After copy-pasting error message to the question post, you may format it with `{}` button.)

http://stackoverflow.com/comment/84246108
has text: your recursion pattern is off. for example, in a, if 1/n=1/4 i.e. n=4 then 1-1/4 is not zero
comment on: http://stackoverflow.com/q/48624364
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48551633
has comment: http://stackoverflow.com/comment/84101492
tagged with: python
linked to: http://stackoverflow.com/q/17139487
tagged with: pyodbc
has body: I am not sure if I am approaching this in the best way. I need to use the results of an array to generate dynamic sql. I am trying to run a sql statement with a variable that comes from an array while count &lt;=len(ArrayList) -1: ID = ArrayList[count,0] AnotherValue = ArrayList[count,1] sql = """ select Column1, Column2 from Atable where ID = """ + ID + """ and AnotherValue = """ + AnotherValue sqlResults= pd.read_sql(sql, conn) count +=1 How can I use a variable to run the statement in a loop? Or other suggestions? Thank you! I am getting this error: TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('&lt;U254') dtype('&lt;U254') dtype('&lt;U254') I also tried this: while count &lt;=len(ArrayList) -1: ID = ArrayList[count,0] AnotherValue = ArrayList[count,1] sql = """ select Column1, Column2 from Atable where ID = $ID and AnotherValue = $AnotherValue """ sqlResults= pd.read_sql(sql, conn) count +=1 and it got this error ('42000', '[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid pseudocolumn "$ID". (126) (SQLExecDirectW)')
has comment: http://stackoverflow.com/comment/84099911
score: 0
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84101843
has title: Python pyodbc Sql
has comment: http://stackoverflow.com/comment/84099655
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/48588945
answers question: http://stackoverflow.com/q/48588828
has comment: http://stackoverflow.com/comment/84175559
score: 0
has comment: http://stackoverflow.com/comment/84176527
type: Answer
has body: As right now selenium doesn't support multiple class name.If your class name includes a space, WebDriver will see it as a "compound selector". You can use cssSelector or id for selecting the webelement. Try below code You can try this xpath: //button[@class="_qv64e _gexxb _4tgw8 _njrw0" and text()="Approve"] Or CSS selector: ._qv64e._gexxb._4tgw8._njrw0 As : driver.find_elements_by_xpath(//span/button [text()="Approve"]) and driver.find_elements_by_css_selector(._qv64e._gexxb._4tgw8._njrw0) Refer this link http://selenium-python.readthedocs.io/locating-elements.html
has comment: http://stackoverflow.com/comment/84175207
has comment: http://stackoverflow.com/comment/84176175
has comment: http://stackoverflow.com/comment/84175306

http://stackoverflow.com/a/49207323
score: 0
has comment: http://stackoverflow.com/comment/85419741
answers question: http://stackoverflow.com/q/48539511
has body: The way @karloskar mentioned was fixed my case. However, after I modified sandbox.py to allow _ssl and _socket to be WHITE_LIST, I got another library import issue - ImportError: No module named google.auth. For who also got above google.auth import error, you could consider to update your appengine_config.py like below. That's the way fixed my import issue. # appengine_config.py import os import google from google.appengine.ext import vendor lib_directory = os.path.dirname(__file__) + '/lib' # Change where to find the google package (point to the lib/ directory) google.__path__ = [os.path.join(lib_directory, 'google')] + google.__path__ # Add any libraries install in the "lib" folder. vendor.add(lib_directory) Reference1: App Engine not finding google.auth file in dev_appserver.py Reference2: https://github.com/GoogleCloudPlatform/google-auth-library-python/issues/169#issuecomment-315417916
type: Answer

http://stackoverflow.com/q/48491894
type: Question
has body: MODELS: class Post(Base): id = Column(Integer, primary_key=True) ... topics = relationship('PostTopic', back_populates='post') class PostTopic(Base): post_id = Column(Integer, ForeignKey("post.id"), primary_key=True) topic_id = Column(Integer, ForeignKey("topic.id"), primary_key=True) topic = relationship('Topic', foreign_keys=topic_id, back_populates="posts_per_topic") post = relationship('Post', foreign_keys=post_id, back_populates="topics") class Topic(Base): id = Column(Integer, primary_key=True) topic_name = Column(Text) posts_per_topic = relationship('PostTopic', back_populates='topic') I'm trying to query a list of entities from posts, and with each post, a list of the one to many topic_names all in one query. post_bundle = Bundle('post', Post.id, Post.title, Post.image, Post.date_created) creator_bundle = Bundle('user', User.first_name, User.last_name, User.photo_link, User.user_id) subject_bundle = Bundle('subject', Subject.icon) topic_bundle = Bundle('topic', Topic.topic_name) return request.dbsession.query(post_bundle, creator_bundle, subject_bundle, topic_bundle)\ .join(Post.creator, Post.subject)\ .join("topics", "topic")\ .filter(Post.is_archived == False, Post.is_draft == False)\ .filter(User.is_banned == False) But I'm receiving repeats for the same post for each topic. eg. ('post_title_1', 'topic_title_1'), ('post_title_1', 'topic_title_2'), ('post_title_1', 'topic_title_3'), ('post_title_1', 'topic_title_4'), What I want: ('post_title_1', ('topic_title_1', 'topic_title_2', 'topic_title_3', )), ('post_title_2', ('topic_title_4', 'topic_title_5', 'topic_title_6', )),
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48492019
has answer: http://stackoverflow.com/a/48492019
tagged with: postgresql
type: AnsweredQuestion
score: 1
answer count: 1
has title: SQLAlchemy relationship list for each row in query
downvote count: 0
has comment: http://stackoverflow.com/comment/83977605
tagged with: sqlalchemy
favorite count: 0

http://stackoverflow.com/q/48608442
answer count: 1
tagged with: mysql
has body: I get the error not all arguments converted during string formatting, when I execute the below-given code: pro_title = "FSBT" print "pro_title: " + pro_title pro_id_query = "SELECT ID FROM projs WHERE pro_title=%s" cursor.execute(pro_id_query, pro_title) db.commit() row = cursor.fetchone() pro_id = None if row is not None: pro_id = str(row[0]) print "pro_id: " + pro_id I also tried format: pro_id_query = "SELECT ID FROM projs WHERE title={}" cursor.execute(pro_id_query.format(pro_title)) It only works when I use ' around {}: pro_id_query = "SELECT ID FROM projs WHERE title='{}'" cursor.execute(pro_id_query.format(pro_title)) I do not understand why INSERT queries work well with %s, while SELECT queries do not: insert_query = "INSERT INTO projs (title, description) VALUES (%s, %s) ON DUPLICATE KEY UPDATE `title`=%s" cursor.execute(insert_query, (pro_title, pro_description, pro_title))
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84213617
has comment: http://stackoverflow.com/comment/84215681
tagged with: python
type: Question
score: 0
has title: MySQL db call: not all arguments converted during string formatting
accepted answer: http://stackoverflow.com/a/48608950
has answer: http://stackoverflow.com/a/48608950

http://stackoverflow.com/q/48629227
favorite count: 0
type: Question
tagged with: dll
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52180574
tagged with: python
tagged with: qt
tagged with: c++
score: 2
has body: There is a software Siemens NX. In this software I can use Python for developing some plugins and applications for this software via NXOpen API. It also has an embedded Python interpreter. I've also found some Qt libraries in the installed NX directory. There are some files like Qt5GuiNX.dll, Qt5CoreNX.dll etc. So I suppose NX uses this files for its internal plugins. I wanna use these libraries to developing some user intafaces in my plugins. The reason is simple: Each plugin hav to be installed on the users' machines. I would like to avoid installing additional frameworks and libraries on them. I want to use these libraries for developing user interface in my plugins. So I tried to use SIP, but it uses .sip files for C++ functions/classes wrappers. Each .sip file contains .h file of certain Qt library which I don't have. So I can't use SIP for binding .dll as I understood. I suppose I can use ctypes module. But when I try to call some functions I see following: And this library has got a lot of C++ functions and few C ones: Do you have any ideas how to use it?
downvote count: 0
answer count: 1
has title: Calling .dll functions of embedded Qt

http://stackoverflow.com/comment/84136444
comment on: http://stackoverflow.com/q/48558873
score: 0
type: Comment
type: QuestionComment
has text: What you need to do is use `blockSignals` on the widgets that are actually emitting the signals (i.e. `self._plots[(r, c)]`). There's no point calling it on `self`, because by then it's too late.

http://stackoverflow.com/q/48634622
has comment: http://stackoverflow.com/comment/84266173
type: UnansweredQuestion
score: -8
has comment: http://stackoverflow.com/comment/84266221
tagged with: python
has comment: http://stackoverflow.com/comment/84266168
has answer: http://stackoverflow.com/a/48634653
has comment: http://stackoverflow.com/comment/84266171
has title: Why is python not recognizing my input
has answer: http://stackoverflow.com/a/48635227
has body: So I'm writing a program for that is supposed to take input of either 1 or 2 from a user, and add the inputs to the total until the total has reached 21. I have a while statement that makes sure the input is either a 1 or 2 but when I test it no matter what input I enter it shows that 1 and 2 are answers that don't qualify. So I don't know if I wrote the parameters for my while statement incorrectly or if my input is not being recognized correctly. If someone could tell me how I can make my code continue running if 1 or 2 is inputed that'd be much appreciated. Thank You.
favorite count: 0
type: Question
upvote count: 0
downvote count: 8
answer count: 2

http://stackoverflow.com/comment/84253106
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48628097
type: AnswerComment
has text: Is not better chain third condition?

http://stackoverflow.com/a/48645428
accepted answer of: http://stackoverflow.com/q/48644605
has comment: http://stackoverflow.com/comment/84288664
answers question: http://stackoverflow.com/q/48644605
type: Answer
has comment: http://stackoverflow.com/comment/84288399
score: 0
type: AcceptedAnswer
has body: If I understand the correct output format word-O, you can try something like this: words = open('filename').read().split() labeled_words = [word+"-O" for word in words] # And now user your output format, each word a line, separate by tabs, whatever. # For example new lines with open('outputfile','w') as output: output.write("\n".join(labeled_words))
has comment: http://stackoverflow.com/comment/84288347

export-to-csv
tags question: http://stackoverflow.com/q/48620151
tags question: http://stackoverflow.com/q/48610829
tags question: http://stackoverflow.com/q/48645262
tag name: export-to-csv
tags question: http://stackoverflow.com/q/48568649
tags question: http://stackoverflow.com/q/48558338
type: Tag

http://stackoverflow.com/a/62028422
type: Answer
answers question: http://stackoverflow.com/q/48577781
score: 0
has body: Well, try this: from django.urls import reverse, resolve from django.test import SimpleTestCase from .views import HomePageView,AboutPageView class SimpleTests(SimpleTestCase): def test_home_page_status_code(self): path = reverse("home") self.assertEquals(resolve(path).func.view_class, HomePageView) response = self.client.get(path) self.assertEquals(response.status_code, 200) def test_abaout_page_status_code(self): path = reverse("about") self.assertEquals(resolve(path).func.view_class, AboutPageView) response = self.client.get(path) self.assertEquals(response.status_code, 200)

http://stackoverflow.com/comment/84269724
type: AnswerComment
has text: @MisterMystery : Yes that should work. I just did `elif` because I wanted to make sure what was happening there.
type: Comment
comment on: http://stackoverflow.com/a/48635383
score: 0

http://stackoverflow.com/comment/84262372
has text: er, is this using `pandas`?
comment on: http://stackoverflow.com/q/48632580
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84237637
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48620587
type: QuestionComment
has text: Please avoid pasting code as pictures, as it doesn't allow to run it. If you'll edit your post it'll be much easier to help

http://stackoverflow.com/comment/84133544
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48568649
has text: Your code is not properly indented; please fix it so we can run it.

http://stackoverflow.com/q/48547439
duplicate of: http://stackoverflow.com/q/21122540
has body: This is my robot code in Python 2.7: #!/usr/bin/env python # -*- coding: utf-8 -*- from chatterbot.trainers import ListTrainer from chatterbot import ChatBot bot = ChatBot('Test') Conversa =['Oi','Olá','Tudo bem?','Eu estou bem'] bot.set_trainer(ListTrainer) bot.train(Conversa) while True: quest = input('Voce: ') resposta = bot.get_response(quest) print ('Bot: ', resposta) When I run it gives the following error: Traceback (most recent call last): File "file/bot.py", line 15, in &lt;module&gt; quest = input('Voce: ') File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'oi' is not defined If I change the input to raw_input it gives this error too: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 18: ordinal not in range(128)
answer count: 1
duplicate of: http://stackoverflow.com/q/9942594
accepted answer: http://stackoverflow.com/a/48587617
type: Question
has title: UnicodeEncodeError: 'ascii' codec can't encode characte
tagged with: python
has answer: http://stackoverflow.com/a/48587617
linked to: http://stackoverflow.com/q/21122540
linked to: http://stackoverflow.com/q/16457441
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/477061
tagged with: bots

http://stackoverflow.com/comment/84019255
type: AnswerComment
has text: at the end is where the totals go. I have the rest I just need the last line to put this at this end. Total 38 28
comment on: http://stackoverflow.com/a/48512059
type: Comment
score: 0

http://stackoverflow.com/comment/84042253
type: Comment
comment on: http://stackoverflow.com/q/48523726
type: QuestionComment
score: 0
has text: No, there is not

http://stackoverflow.com/a/48609724
score: 0
upvote count: 1
has body: Your problem is that you end up in an infinite loop due to the following bit of code: if players[i][1] &lt; 200: continue # here you skip to the top of the loop without changing i When you change to i += 2 this problem still exists but you happen to avoid getting stuck in it. This is because you only process the even-indexed elements. Each of these has a value over 200 so your code never gets to the continue statement. [['James', 202], ['Durant', 205], ['David', 211]] Try: i = 0 while i &lt; len(players): if players[i][1] &lt; 200: print(players[i]) i += 1
downvote count: 1
answers question: http://stackoverflow.com/q/48609632
type: Answer

http://stackoverflow.com/q/48534819
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has body: So I have an array of ranks (obtained from scipy.stats.rankdata): 1 2 5 3 4 The no.s are the ranks assigned to the corresponding indices. Now I want to shift the ranks downward by 2 positions. That is, I want the indices with the top 2 ranks to be assigned the last 2 ranks. The other elements must therefore increase in rank. 3 4 2 5 1 So the indices with the top 2 ranks i.e index 2 and 4 having ranks 5 and 4 are given the bottom 2 ranks 2 and 1 . The other elements are increased in rank subsequently. How do I implement this shift for any top n ranks?
type: UnansweredQuestion
tagged with: arrays
tagged with: python
score: -1
upvote count: 0
has answer: http://stackoverflow.com/a/48534895
has title: How to do shift in ranked numpy array?

http://stackoverflow.com/a/48588036
upvote count: 6
answers question: http://stackoverflow.com/q/48587799
downvote count: 0
has body: String concatenation is performed in python via the + operator. So changing to col+'_change' will fix this issue for you. You might find it helpful to read the relevant python documentation.
score: 6
type: Answer

http://stackoverflow.com/comment/84046120
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48525582
has text: Basically you're appending the `s*_loc` to `loc` if `s*` is not `''`. Why not create a boolean list and take all the `True`? Simply put why not do `['' == item for item in [s0,s1,s2 .... ]]` and then process all the values which are `False`
score: 0

http://stackoverflow.com/comment/84147380
type: AnswerComment
has text: Oh ok that makes sense thanks for the information and help with the code! I didn't realize there were other errors too.
comment on: http://stackoverflow.com/a/48575243
score: 0
type: Comment

http://stackoverflow.com/comment/84155758
has text: Then do you think i need to try another method to approach this problem? How can i implement it?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48574670

http://stackoverflow.com/a/48584359
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48575757
score: 1
downvote count: 0
has body: One solution is to implement your own QValidator as I show below: class LettersValidator(QValidator): def __init__(self, options, *args, **kwargs): QValidator.__init__(self, *args, **kwargs) self._options = options def validate(self, value, pos): if len(value) &gt; 0: if value[-1] in self._options: return QValidator.Acceptable, value, pos else: if value == "": return QValidator.Intermediate, value, pos return QValidator.Invalid, value, pos if __name__ == '__main__': app = QApplication(sys.argv) w = QLineEdit() w.setValidator(LettersValidator("tam")) w.show() sys.exit(app.exec_())

http://stackoverflow.com/comment/84151523
has text: Opps, my bad, it should be an empty string.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48577499
type: Comment

http://stackoverflow.com/q/48645232
has comment: http://stackoverflow.com/comment/84288078
has comment: http://stackoverflow.com/comment/84294316
tagged with: web-scraping
has title: How can I parse the table from webpage using beautiful soup for HTML page?
tagged with: beautifulsoup
score: 0
has comment: http://stackoverflow.com/comment/84287829
tagged with: python
has comment: http://stackoverflow.com/comment/84287496
has body: I'm trying to parse this website table contents, I tried using below program import requests from bs4 import BeautifulSoup url = "http://www.espncricinfo.com/rankings/content/page/211270.html" page = requests.get(url) soup = BeautifulSoup(page.text,"html.parser") batsman_type = (soup.find_all('h3'))[0].text ret = [] row = {} for tr in soup.find_all("tr"): tds = tr.find_all("td") if len(tds) &gt; 0 : row = {'Rank':tds[0].text,'Name': tds[1].text, 'Country' : tds[2].text, 'Rating': tds[3].text} ret.append(row) row = {} ret.append(row) print(ret) when I print td it returns none value, how can I fix this in order to get all the contents of table?, If you need to any other question please feel free to ask
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/36225844
answer count: 0
has comment: http://stackoverflow.com/comment/84287633
type: UnansweredQuestion

http://stackoverflow.com/a/48543898
has body: There is closed parenthesis missing in the below line `a_val=(5-0.004364*(v_val**2)`
downvote count: 1
score: 0
answers question: http://stackoverflow.com/q/48543815
type: Answer
upvote count: 1

http://stackoverflow.com/a/49852214
downvote count: 0
has comment: http://stackoverflow.com/comment/90396245
answers question: http://stackoverflow.com/q/48491566
has body: from sklearn.base import BaseEstimator, TransformerMixin class DataFrameSelector(BaseEstimator, TransformerMixin): def __init__(self, attribute_names): self.attribute_names=attribute_names def fit(self, X, y=None): return self def transform(self, X): return X[self.attribute_names].values This should work.
upvote count: 12
type: Answer
score: 12

http://stackoverflow.com/comment/84204912
has text: also what exactly/how exactly does __name__ work here? I looked around for info on the topic but couldn't find much about how it was used here
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48593235

virtual-machine
tag name: virtual-machine
tags question: http://stackoverflow.com/q/48593596
type: Tag

random
tags question: http://stackoverflow.com/q/48527573
tags question: http://stackoverflow.com/q/48619344
tags question: http://stackoverflow.com/q/48503151
tags question: http://stackoverflow.com/q/48631962
tags question: http://stackoverflow.com/q/48550897
tags question: http://stackoverflow.com/q/48558077
tag name: random
tags question: http://stackoverflow.com/q/48572819
tags question: http://stackoverflow.com/q/48575110
type: Tag
tags question: http://stackoverflow.com/q/48613706
tags question: http://stackoverflow.com/q/48605961
tags question: http://stackoverflow.com/q/48630181
tags question: http://stackoverflow.com/q/48566704
tags question: http://stackoverflow.com/q/48629695

http://stackoverflow.com/q/48595018
has answer: http://stackoverflow.com/a/68387387
answer count: 2
downvote count: 2
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: sdk
has title: How to create a PDF generator on Python?
linked to: http://stackoverflow.com/q/2252726
has body: I'm a beginner programmer, tryna teach myself to code. One of the ways I do that is I give myself projects to work on. Right now I'm working on a PDF generator application and my question is where can I start in build this application? I've heard of SDKs and APIs, but I'm not really sure how to use them in my code, whether I have to import a file for it, or something of that sort. Any advice would be much appreciated.
has answer: http://stackoverflow.com/a/48595046
tagged with: pdf-generation
favorite count: 0
score: -1
type: Question

http://stackoverflow.com/a/48613532
has comment: http://stackoverflow.com/comment/84223868
has body: Your __new__ method isn't returning an instance of my_context_man, but an instance of str, and str doesn't have an __enter__ method. It's the return value of __enter__ that gets bound to the name after as in the with statement. You want class my_context_man: def __init__(self, my_str): self.msg = my_str print("beginning " + my_str) def __enter__(self): return self.msg def __exit__(self, exc_type, exc_val, exc_tb): print('end')
has comment: http://stackoverflow.com/comment/84224075
has comment: http://stackoverflow.com/comment/84224453
has comment: http://stackoverflow.com/comment/84224400
has comment: http://stackoverflow.com/comment/84224890
score: 0
answers question: http://stackoverflow.com/q/48613445
has comment: http://stackoverflow.com/comment/84224382
type: Answer

http://stackoverflow.com/q/48572082
type: Question
has body: I have a web application that runs locally only (does not run on a remote server). The web application is basically just a ui to adjust settings and see some information about the main application. Web UI was used as opposed to a native application due to portability and ease of development. Now, in order to start and stop the main application, I want to achieve this through a button in the web application. However, I couldn't find a suitable way to start a asynchronous and managed task locally. I saw there is a library called celery, however that seems to be suitable to a distributed environment, which mine is not. My main need to be able to start/stop the task, as well as the check if the task is running (so I can display that in the ui). Is there any way to achieve this?
type: UnansweredQuestion
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has title: Django asynchronous tasks locally
score: 1
has answer: http://stackoverflow.com/a/48572125
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48570373
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48570102
has body: The callback is being invoked with the correct values on every button click, as can be verified with some print statements. The error is in your logic. Since you are operating on the current signal, rather than some original signal, you presumably always want to flip every time, unconditionally. Currently, you are only flipping every other button push, because this flip_signal(..., False) just returns the signal passed in, as-is. Changing the update_flip callback to always flip yields the behavior you want: def update_flip(attrname, old, new): # flip the *current* data on *every* button toggle source.data = dict(x=source.data['x'], y=flip_signal(source.data['y'], True)) For your logic to work you would need a different function than your current flip_signal. You would need a function that always returns the original unflipped signal on False, and always returns the flipped signal on True. Contrast this with the current flip_signal, if you call it with False it gives you back whatever you passed in, regardless of whether it is the flipped or unflipped signal.
accepted answer of: http://stackoverflow.com/q/48570102
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48606229
tagged with: encoding
type: UnansweredQuestion
has body: I have csv files having encoding-'utf-8'. I need to convert the csv to excel workbook with same encoding but unable to do so. Tried many things but not able to fix. Here is the code snippet. NOte: Using xlsxwriter package def csv_to_excel(input_file_path, output_file_path): file_path = input_file_path excel_file_path = output_file_path wb = Workbook(excel_file_path.encode('utf-8', 'ignore'), {'encoding': 'utf-8'}) sheet1 = wb.add_worksheet(("anyname1").encode('utf-8','ignore')) sheet2 = wb.add_worksheet(("anyname2").encode('utf-8','ignore')) for filename in glob.glob(file_path): (f_path, f_name) = os.path.split(filename) w_tab = str(f_name.split('_')[2]).split('.')[0] if (w_tab=="anyname1"): w_sheet = sheet1 elif (w_tab=="anyname2"): w_sheet = sheet2 spamReader = csv.reader(open(filename, "rb"), delimiter=',',quotechar='"') row_count = 0 for row in spamReader: for col in range(len(row)): w_sheet.write(row_count,col,row[col]) row_count +=1 try: os.remove(excel_file_path) except: pass wb.close() print "Converted CSVs to Excel File" Errors: Case1: When I am trying to open the utf-8 encoded csv file as follows: spamReader = csv.reader(io.open(filename, "r", encoding = 'utf-8'), delimiter=',',quotechar='"') Then getting error while iterating over the spamReader object as UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 92: ordinal not in range(128) Case2: When I am trying to open the same csv file as binary as mentioned in above code snippet, then I am not able to save it as utf-8 encoded excel, so while calling wb.close(), getting error as UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 12: ordinal not in range(128) I have just started learning python so maybe this is not that big issue but Please help me on this.
linked to: http://stackoverflow.com/q/10406135
downvote count: 0
has comment: http://stackoverflow.com/comment/84244504
tagged with: python
has comment: http://stackoverflow.com/comment/84210301
has comment: http://stackoverflow.com/comment/84244486
answer count: 0
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: ASCII Encode/Decode Error

http://stackoverflow.com/comment/84311817
comment on: http://stackoverflow.com/a/48639813
score: 0
type: Comment
has text: @AntonyHatchkins: You're setting yourself up for problems with code like that; you looked at a fluke of rounding error that happened to match your intuition once, and you're counting on it to keep matching your intuition with further inputs. It won't.
type: AnswerComment

http://stackoverflow.com/a/48547844
accepted answer of: http://stackoverflow.com/q/48547420
has comment: http://stackoverflow.com/comment/84094268
answers question: http://stackoverflow.com/q/48547420
has comment: http://stackoverflow.com/comment/84097827
score: 1
has comment: http://stackoverflow.com/comment/84091704
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84095777
downvote count: 0
upvote count: 1
has body: Generally, re(z) is how you take the real part of a complex number in SymPy. But there are other issues here. roots returns a dictionary in which the values encode multiplicities. Your code ignores multiplicities, simply adding 1. Better to either use those values, or maybe use multiple=True flag of roots which makes it return a list instead, with multiple roots repeated. roots will only return the roots that are expressible in radicals. For polynomials of degrees up to 4 these are all of them, but for higher degrees you will likely be missing some or all of roots. The rootof function is suitable for these cases: it takes the index of a root as a second argument. Accordingly, I give two examples. First, using roots with multiple flag, so it returns a list instead of a dict: z = symbols('z') p = Poly([3, 4, 5, 2], z) rts = roots(p, multiple=True) print([re(val) for val in rts]) These values can be compared to 0. Second, a higher degree polynomial: we don't expect roots in radicals anymore. z = symbols('z') p = Poly([3, 4, 5, 2, 7, 5, 9], z) for k in range(degree(p)): print(re(rootof(p, k).n())) Output: -1.05474041145861 -1.05474041145861 -0.364466197630592 -0.364466197630592 0.752539942422535 0.752539942422535 which makes sense because the complex roots of a polynomial with real coefficients come in conjugate pairs.
type: Answer

string-to-datetime
tag name: string-to-datetime
type: Tag
tags question: http://stackoverflow.com/q/48628867

http://stackoverflow.com/q/48587863
has body: The following code leads to an exception by pandas merge function. first = pd.read_csv('https://raw.githubusercontent.com/AntoineGautier/Data/master/first.txt', header=None) secnd = pd.read_csv('https://raw.githubusercontent.com/AntoineGautier/Data/master/secnd.txt', header=None) common_cols = [c for c in first.columns if c in secnd.columns] first.merge(secnd, on=common_cols, how='left', indicator=True) The following does not. first.columns = first.columns.astype('str') secnd.columns = secnd.columns.astype('str') common_cols = [c for c in first.columns if c in secnd.columns] first.merge(secnd, on=common_cols, how='left', indicator=True) So is it considered a bad practice to work with column names of type numpy.int64?
score: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84173079
has comment: http://stackoverflow.com/comment/84173057
type: UnansweredQuestion
downvote count: 0
tagged with: python
answer count: 0
has title: Python pandas - Is it a bad practice to work with integers as column names?
tagged with: pandas

http://stackoverflow.com/q/48541968
tagged with: sqlite
favorite count: 0
has answer: http://stackoverflow.com/a/48542153
type: Question
has comment: http://stackoverflow.com/comment/84079258
has title: sqlite3.OperationalError: no such column: - Python
has comment: http://stackoverflow.com/comment/84079685
has answer: http://stackoverflow.com/a/48542196
answer count: 2
type: UnansweredQuestion
tagged with: python
has body: I am trying to Inserat something from Input into my Database. But getting the Error: sqlite3.OperationalError: no such column: kundename import sqlite3 conn = sqlite3.connect('datenbank.db') print ("Opened database successfully") kundenname= input("Kundename: ") auftragstyp= input("Auftragstyp: ") auftragsurl= input("Auftragsurl: ") anzahl= input("Anzahl der Bewertungen: ") conn.execute("INSERT INTO kundenname VALUES (kundename,auftragstyp,auftragsurl,anzahl)", (kundenname, auftragstyp, auftragsurl, anzahl)) conn.commit() print ("Records created successfully") conn.close() But if I make like: import sqlite3 conn = sqlite3.connect('datenbank.db') print ("Opened database successfully") conn = conn.execute("SELECT ID, kundename from kundenname") for row in conn: print ("ID = ", row[0]) print ("kundename = ", row[1]) print ("Operation done successfully") conn.close() then it works and Shows me the Datas in the Base. But why insert saying the colum dosent excist? Thank you very much!
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/48567719
has body: If you are representing ranges as tuple dictionary keys, this would work: segments = {(0, 13): 'Bike segment', (22, 217): 'Car segment'} [v for k, v in segments.items() if 122 in range(*k)] # ['Car segment'] If your ranges are not mutually exclusive, you may get more than one element. If your input does not exist in one of the ranges, you will have an empty list.
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48567308

http://stackoverflow.com/q/48593142
tagged with: python
tagged with: regex
upvote count: 1
has comment: http://stackoverflow.com/comment/84184798
has title: How to extract substrings for a normal string python
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48593367
has answer: http://stackoverflow.com/a/48593367
has answer: http://stackoverflow.com/a/48593962
downvote count: 1
tagged with: substring
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am looking for a way to extract a part of a string (I think they are called substrings). I have looked for a solution, but haven't found one. Here is an example: ` text = input('Insert Math Problem: ') '''Insert substring recognition script here''' if text contains('3') and text contains('4'): print('Contains three and four!') else: print('Does not contain three and four.')` For example if I typed in What is 3 * 4, how would I get just the 3 * 4 part? The type of substring I would like to have extracted is the operation and the two numbers surrounding it. I would also like it to be flexible in a way that it could find 3*4 or 3 times 4. My Python version is 3.6.4 and I am using a Mac.
accepted answer: http://stackoverflow.com/a/48593962

http://stackoverflow.com/comment/84074638
score: 0
comment on: http://stackoverflow.com/q/48502667
type: Comment
has text: What does mean 'most similar tables'? What is a criterion of similarity?
type: QuestionComment

http://stackoverflow.com/comment/84256913
type: AnswerComment
has text: @WaterGuy define a `namedtuple` with a field that will contain this count ahead of time. Fill it with `None` until you do. In general,y ou should try to organize your program's data-structures as much as possible ahead of time
comment on: http://stackoverflow.com/a/48629163
score: 1
type: Comment

http://stackoverflow.com/comment/84108864
score: 0
has text: @Brystephor Do you intend to use VBA to solve this problem or do you want to use xlWings?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48556211

http://stackoverflow.com/q/48536523
has comment: http://stackoverflow.com/comment/84068069
tagged with: python
score: -1
has body: I have a string like this: out = """Tue Nov 7 07:20:56.948 UTC total 1224 11 -rw------- 1 243 Nov 7 06:50 .bash_history 12 -rw-r--r-- 1 364236 Nov 5 12:24 bh_cardmgr_1899.by.11.20171105-122102.sysadmin-vm.ec937.core.gz 15 -rw-r--r-- 1 42082 Nov 5 13:03 bh_cardmgr_1900.by.11.20171105-130244.sysadmin-vm.ec937.core.txt 14 -rw-r--r-- 1 365799 Nov 5 13:03 bh_cardmgr_1900.by.11.20171105-130244.sysadmin-vm.ec937.core.gz 16 -rw-r--r-- 1 366337 Nov 7 04:58 bh_cardmgr_1887.by.11.20171107-045835.sysadmin-vm.ec937.core.gz 131074 drwxr-xr-x 4 4096 Nov 7 05:27 cisco_support 131073 drwxr-xr-x 2 4096 Nov 5 09:22 tftpboot 13 -rw-r--r-- 1 42082 Nov 5 12:24 bh_cardmgr_1899.by.11.20171105-122102.sysadmin-vm.ec937.core.txt 131077 drwxr-xr-x 2 4096 Nov 5 09:31 dumper 17 -rw-r--r-- 1 42082 Nov 7 04:58 bh_cardmgr_1887.by.11.20171107-045835.sysadmin-vm.ec937.core.txt """ I just want to get the file names from this string and create a list of those filenames. How do I get an output like this? list = [bh_cardmgr_1899.by.11.20171105-122102.sysadmin-vm.ec937.core.gz, bh_cardmgr_1900.by.11.20171105-130244.sysadmin-vm.ec937.core.txt, bh_cardmgr_1900.by.11.20171105-130244.sysadmin-vm.ec937.core.gz]
downvote count: 1
has title: how to get the file name from the string in python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48536795
answer count: 3
possible better answer: http://stackoverflow.com/a/48536843
has answer: http://stackoverflow.com/a/48536795
has answer: http://stackoverflow.com/a/48536843
has answer: http://stackoverflow.com/a/48567938
favorite count: 0
type: Question
upvote count: 0

http://stackoverflow.com/comment/84192742
comment on: http://stackoverflow.com/q/48598086
type: Comment
type: QuestionComment
has text: Import date first: `from datetime import date`, and if you want 6 for Saturday use `date.isoweekday()`. `date.weekday()` will give 5 for Saturday.
score: 0

http://stackoverflow.com/comment/84193816
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48598643
type: AnswerComment
has text: Thank you! This really pin-pointed my mistake. Ran both these codes and found out where the problem was.

http://stackoverflow.com/q/48513721
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84022163
has comment: http://stackoverflow.com/comment/84022845
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84022661
has comment: http://stackoverflow.com/comment/84023149
has comment: http://stackoverflow.com/comment/84023202
accepted answer: http://stackoverflow.com/a/48514255
has comment: http://stackoverflow.com/comment/84023753
has comment: http://stackoverflow.com/comment/84023008
has comment: http://stackoverflow.com/comment/84023297
tagged with: python
has comment: http://stackoverflow.com/comment/84023153
has body: Consider the following dataframe: df = pd.DataFrame(data=np.array([['a',1, 2, 3,'T'], ['a',4, 5, 6,'F'], ['b',7, 8, 9,'T'], ['b',10, 11 , 12,'T'], ['b',13, 14 , 15,'F']]) , columns=['id','A', 'B', 'C','T/F']) id A B C T/F 0 a 1 2 3 T 1 a 4 5 6 F 2 b 7 8 9 T 3 b 10 11 12 T 4 b 13 14 15 F I want to apply a condition to T/F column that will copy the rows of each id with T label to further columns of the same id. For example,I need the following result: id A B C T/F 0 a 1 2 3 T 1 2 3 T 1 a 4 5 6 F 1 2 3 T 2 b 7 8 9 T 7 8 9 T 3 b 10 11 12 T 7 8 9 T 4 b 13 14 15 F 7 8 9 T 5 b 7 8 9 T 10 11 12 T 6 b 10 11 12 T 10 11 12 T 7 b 13 14 15 F 10 11 12 T here is my script: n = np.array(df.groupby('id').size()) m = len(df.groupby('id')) Cnt = 0 df4 = pd.DataFrame() for prsnNo in range(m): for i in range(n[prsnNo]): v = df.iloc[Cnt: Cnt + n[prsnNo], :].groupby('id').cumcount() == i df1 = df.iloc[Cnt: Cnt + n[prsnNo], :].where(v) temp = df4 df4 = df.iloc[Cnt: Cnt + n[prsnNo], :].merge(df1, on="id", how="left") df4 = pd.concat([temp, df4]) Cnt += n[prsnNo] I do not know how to add a condition to check the value of T/F column in my loop.If I add the if condition in my loop it gives me an error. for prsnNo in range(m): for i in range(n[prsnNo]): if df[df['T/F'] =='T'] : v = df.iloc[Cnt: Cnt + n[prsnNo], :].groupby('id').cumcount() == i df1 = df.iloc[Cnt: Cnt + n[prsnNo], :].where(v) temp = df4 df4 = df.iloc[Cnt: Cnt + n[prsnNo], :].merge(df1, on="id", how="left") df4 = pd.concat([temp, df4]) Cnt += n[prsnNo] Thanks,
has title: checking condition in a loop (Pandas)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84023285
has comment: http://stackoverflow.com/comment/84023162
tagged with: pandas
has answer: http://stackoverflow.com/a/48514255
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84088390
has text: Please format your code correctly.
score: 0
comment on: http://stackoverflow.com/q/48546308
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88696703
has text: We get a ton of these errors and the app still works.... I think it's not these errors that's the problem.
comment on: http://stackoverflow.com/q/48535020
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48601563
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/48601604
duplicate of: http://stackoverflow.com/q/23309698
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48601604
tagged with: propertydescriptor
has body: I am trying to understand descriptors in python, and one thing I noticed is the following: In [1]: class descriptor: ...: def __init__(self): ...: pass ...: def __get__(self, instance, owner): ...: print ("__get__ called") ...: return 0 ...: def __set__(self, obj, value): ...: print ("__set__ called") In [2]: class Foo: ...: y = descriptor() ...: def __init__(self): ...: self.x = descriptor() In [3]: Foo.y __get__ called Out[3]: 0 In [4]: f = Foo() In [5]: f.x Out[5]: &lt;__main__.descriptor at 0x1099dd588&gt; As you can see, on the class attribute, descriptor's __get__ is being correctly called, but on instance attribute it is not calling the required method. I tried reading this, but it is not immediately obvious what part of that page applies over here.
duplicate of: http://stackoverflow.com/q/36932396
tagged with: python
linked to: http://stackoverflow.com/q/36932396
tagged with: python-3.6
has title: descriptor behavior difference on class and instance
type: AnsweredQuestion
score: 1
answer count: 1

http://stackoverflow.com/q/48536295
has answer: http://stackoverflow.com/a/48539871
has answer: http://stackoverflow.com/a/48536495
has answer: http://stackoverflow.com/a/48536546
has comment: http://stackoverflow.com/comment/84067718
has comment: http://stackoverflow.com/comment/84068565
has title: Inverse of string format in python
has answer: http://stackoverflow.com/a/70672881
upvote count: 2
has answer: http://stackoverflow.com/a/48536486
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48558991
score: 0
downvote count: 2
has answer: http://stackoverflow.com/a/48558991
tagged with: string
favorite count: 0
tagged with: format
type: Question
has answer: http://stackoverflow.com/a/48536592
answer count: 8
has body: In python, we can use str.format to construct string like this: string_format + value_of_keys = formatted_string Eg: FMT = '{name:} {age:} {gender}' # string_format VoK = {'name':'Alice', 'age':10, 'gender':'F'} # value_of_keys FoS = FMT.format(**VoK) # formatted_string In this case, formatted_string = 'Alice 10 F' I just wondering if there is a way to get the value_of_keys from formatted_string and string_format? It should be function Fun with VoK = Fun('{name:} {age:} {gender}', 'Alice 10 F') # the value of Vok is expected as {'name':'Alice', 'age':10, 'gender':'F'} Is there any way to get this function Fun? ADDED : I would like to say, the '{name:} {age:} {gender}' and 'Alice 10 F' is just a simplest example. The realistic situation could be more difficult, the space delimiter may not exists. And mathematically speaking, most of the cases are not reversible, such as: FMT = '{key1:}{key2:}' FoS = 'HelloWorld' The VoK could be any one in below: {'key1':'Hello','key2':'World'} {'key1':'Hell','key2':'oWorld'} .... So to make this question well defined, I would like to add two conditions: 1. There are always delimiters between two keys 2. All delimiters are not included in any value_of_keys. In this case, this question is solvable (Mathematically speaking) :) Another example shown with input and expected output: In '{k1:}+{k2:}={k:3}', '1+1=2' Out {'k1':1,'k2':2, 'k3':3} In 'Hi, {k1:}, this is {k2:}', 'Hi, Alice, this is Bob' Out {'k1':'Alice', 'k2':'Bob'}
tagged with: python
possible better answer: http://stackoverflow.com/a/48536546
tagged with: regex
has answer: http://stackoverflow.com/a/48536481

http://stackoverflow.com/q/48515837
tagged with: django
tagged with: python
has body: I have an issue with Validate Sign Up User data in serializers - Django Rest Framework. Hope your guys help me! My request: I want to create sign up form with user enter Duplicate email, it'll raise serializer object which duplicate. My serializers: class UserDuplicateSerializer(ModelSerializer): class Meta: model = User fields = [ 'username', 'full_name', 'first_name', 'last_name', ] class UserSignUpSerializer(ModelSerializer): username = CharField(required=True, allow_blank=False) class Meta: model = User fields = [ 'username', 'email', 'password' ] extra_kwargs = {"password": {"write_only": True}} # Validate duplicate username def validate_username(self, value): data = self.get_initial() username = data.get("username") username_qs = User.objects.filter(username=username) if username_qs.exists(): duplicate_obj = User.objects.get(username=username) serializer = UserDuplicateSerializer(duplicate_obj) raise ValidationError(format(serializer.data)) else: pass return value def create(self, validated_data): username = validated_data['username'] ... user_obj.save() return validated_data It renders: {'username': u'duongnuhabang', 'first_name': u'Dương Nữ', 'profile_pic_url': OrderedDict([('id', 71), ('image', '/media/users/2/13_71.jpg'), ('config_translateY', 0)]), 'last_name': u'Hạ Băng', 'full_name': u'Dương Nữ Hạ Băng'} But I want to JSON Type: {'username': 'duongnuhabang', 'first_name': 'Feed Git', ...}
has answer: http://stackoverflow.com/a/48515880
score: 0
answer count: 1
tagged with: django-rest-framework
type: Question
has title: Validate Sign Up User data in serializers - Django Rest Framework
tagged with: serialization
type: UnansweredQuestion

http://stackoverflow.com/a/51855895
upvote count: 2
downvote count: 0
has body: The code is as follows: def mean_squared_error(y_true, y_pred): return K.mean(K.square(y_pred - y_true), axis=-1) One application for choosing the axis to be -1 is for example, for colored picture, it has 3 layers RGB. Each layer has size 512 times 512 pixels and they are stored in an object of size 512 times 512 times 3. Suppose your task involves reconstructing the picture and you store in another object of size 512 times 512 times 3. Calling the MSE would enable you to analyze how good is your reconstruction task at each pixel. The output would be of size 512 times 512, summarizing your performance at each pixel.
answers question: http://stackoverflow.com/q/48618525
score: 2
type: Answer

http://stackoverflow.com/a/48562810
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84121273
answers question: http://stackoverflow.com/q/48562627
score: 1
has comment: http://stackoverflow.com/comment/84121908
accepted answer of: http://stackoverflow.com/q/48562627
downvote count: 0
has body: You cannot do it that way because the variable item is the one being updated and rebound within the loop body, and again after iteration. The values within the list itself aren't updated. You could do this with a class so you have some object to refer back to after the loop class Var(): def __init__(self, x): self.x = x def incr(self): self.x += 1 def __str__(self): return str(self.x) a = Var(1) b = Var(3) c = Var(7) for item in [a, b, c]: item.incr() print("a: {}; b: {}; c: {}".format(a,b,c)) Alternatively, you're looking for something like this a, b, c = map(lambda x: x+1, [a, b, c])
has comment: http://stackoverflow.com/comment/84121940
has comment: http://stackoverflow.com/comment/84121409
has comment: http://stackoverflow.com/comment/84122346
has comment: http://stackoverflow.com/comment/84121696
type: AcceptedAnswer

http://stackoverflow.com/a/48549546
answers question: http://stackoverflow.com/q/48549204
accepted answer of: http://stackoverflow.com/q/48549204
type: Answer
score: 2
upvote count: 2
has body: use a regular expression replacement function with a dictionary. Match everything between brackets (non-greedy, avoiding the brackets themselves) and replace by the value of the dict, put original value if not found: import re d = {"BANANA":"12", "PINEAPPLE":"20","CHERRY":"100","BANANA":"400"} s = "A[BANANA] + B[PINEAPPLE] - C[CHERRY] BANANA" print(re.sub("\[([^\[\]]*)\]",lambda m : "[{}]".format(d.get(m.group(1),m.group(1))),s)) prints: A[400] + B[20] - C[100] 400
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48609288
has comment: http://stackoverflow.com/comment/84237047
has comment: http://stackoverflow.com/comment/84237562
has comment: http://stackoverflow.com/comment/84228979
type: Answer
has comment: http://stackoverflow.com/comment/84236121
score: 0
has body: Try this: mail_sent = self.pool.get('email.template').send_mail( cr, self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'user_root')[1], template_id, # purchase order model should be selected in email template form purchase_order_record.id, # record id force_send=True, context=ctx )
answers question: http://stackoverflow.com/q/48606005

http://stackoverflow.com/q/48498668
type: UnansweredQuestion
has body: So I have 3 files, api.py, build.py and data.json My problem is that when I update the json file via api.py and try to load a page it won't be adjusted to the new and updated data. Example: Json contains a field which is 0 or 1, if I change one to the other nothing happens, however if I go in and manually update the build.py file and reload the page it works(etc change a string in the 'build_header()' function below). Here is a short example of my code: api.py: @app.route('/') def api_root(): build.build_page('index') return render_template('index.html') build.py: def build_page(page): with open('data.json') as json_data: data = json.load(json_data) if page == 'index': header = build_header() body = build_body(data) content = [header, body] f = open('index.html') f.seek(0) f.truncate() f.write('\n'.join(content)) f.close() The json file is updated in a separate thread, which isn't relevant here afaik. When I make a HTTP GET request I get the right codes 200 if changed and 304 if not changed for data.json. Thanks in advance.
downvote count: 0
upvote count: 1
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/83990700
has comment: http://stackoverflow.com/comment/83990627
has comment: http://stackoverflow.com/comment/83991068
has comment: http://stackoverflow.com/comment/83990743
score: 1
has title: Python Flask updating file in background
tagged with: web
favorite count: 0
type: Question
answer count: 0

http://stackoverflow.com/comment/84161623
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48582496
has text: Try replacing \ with \\. You might also want to use the complete path to your `python`-executable

http://stackoverflow.com/comment/84281259
type: QuestionComment
score: 2
has text: Apart from the colormap (and some smoothing) the images look pretty similar to me. What *similar* are you talking about exactly? You can find the available colormaps in matplotlib [here](https://matplotlib.org/examples/color/colormaps_reference.html).
comment on: http://stackoverflow.com/q/48642216
type: Comment

http://stackoverflow.com/a/48567034
upvote count: 4
has comment: http://stackoverflow.com/comment/84130814
has body: I would do it this way: def getweekdays(frm, to): days = [0,1,2,3,4,5,6] if frm &lt;= to: return days[frm:to+1] else: return days[frm:] + days[:to+1] (I haven't checked the code, but you get the idea :) )
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/84130495
accepted answer of: http://stackoverflow.com/q/48566905
type: Answer
has comment: http://stackoverflow.com/comment/84130627
answers question: http://stackoverflow.com/q/48566905
has comment: http://stackoverflow.com/comment/84130427

http://stackoverflow.com/q/48612475
has comment: http://stackoverflow.com/comment/84221728
accepted answer: http://stackoverflow.com/a/48612544
has body: I am trying to understand how to call an instance of a random class but with code like this, it throws: app.classAFunction is not defined class ClassA(): def __init__(self): b = ClassB() def classAFunction(self): print("classAFunction was succesfully called") class ClassB(): def __init__(self): app.classAFunction() app = ClassA() Can you explain me what I'm doing wrong?
has comment: http://stackoverflow.com/comment/84221597
downvote count: 3
has answer: http://stackoverflow.com/a/48612544
has comment: http://stackoverflow.com/comment/84221635
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84221814
upvote count: 2
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84221773
has comment: http://stackoverflow.com/comment/84221564
type: AnsweredQuestion
has title: Calling an instance of a non-related class in python

http://stackoverflow.com/q/48516205
has comment: http://stackoverflow.com/comment/84037293
has body: I am trying to work with a Pandas DataFrame which has some NaN values. When I try to df.fillna(df.mean()) I get the following error and can not find a solution or reason for it: Error: TypeError: cannot label index with a null key All columns are int or float. I am even able to extract the single columns into an array, do fillna() on this array and re-integrate into the DataFrame. Any idea or hint? Thank you very much! My code: test=pd.read_csv("../input/test.csv") test.fillna(test.mean(),inplace=True) The file I am working on is from Kaggle the test or train.csv. I have same error for both data: https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data The Error code is like this: TypeError Traceback (most recent call last) &lt;ipython-input-29-ab3e419316e1&gt; in &lt;module&gt;() 14 15 #Also test has NaN's ---&gt; 16 test.fillna(test.mean(),inplace=True) /opt/conda/lib/python3.6/site-packages/pandas/core/frame.py in fillna(self, value, method, axis, inplace, limit, downcast, **kwargs) 2752 self).fillna(value=value, method=method, axis=axis, 2753 inplace=inplace, limit=limit, -&gt; 2754 downcast=downcast, **kwargs) 2755 2756 @Appender(_shared_docs['shift'] % _shared_doc_kwargs) /opt/conda/lib/python3.6/site-packages/pandas/core/generic.py in fillna(self, value, method, axis, inplace, limit, downcast) 3645 if k not in result: 3646 continue -&gt; 3647 obj = result[k] 3648 obj.fillna(v, limit=limit, inplace=True, downcast=downcast) 3649 return result /opt/conda/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key) 1962 return self._getitem_multilevel(key) 1963 else: -&gt; 1964 return self._getitem_column(key) 1965 1966 def _getitem_column(self, key): /opt/conda/lib/python3.6/site-packages/pandas/core/frame.py in _getitem_column(self, key) 1972 1973 # duplicate columns &amp; possible reduce dimensionality -&gt; 1974 result = self._constructor(self._data.get(key)) 1975 if result.columns.is_unique: 1976 result = result[key] /opt/conda…
linked to: http://stackoverflow.com/q/48478457
tagged with: fillna
score: 0
has answer: http://stackoverflow.com/a/48516755
linked to: http://stackoverflow.com/q/20109391
has answer: http://stackoverflow.com/a/48517122
tagged with: pandas
has comment: http://stackoverflow.com/comment/84027093
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/84026721
type: Question
has comment: http://stackoverflow.com/comment/84027725
has title: Panda - Fillna - TypeError: cannot label index with a null key
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84027025

http://stackoverflow.com/comment/84261750
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48632221
score: 0
has text: Will provide asap. For now, let me say every column/series dtype is object (text, in this case), and column A for grouping has approximately 10 distinct values.

http://stackoverflow.com/comment/126286931
score: 0
type: Comment
type: AnswerComment
has text: @GPhilo submitted an edit
comment on: http://stackoverflow.com/a/48640292

http://stackoverflow.com/comment/84163013
has text: Yes, thats better! ta
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48583113

http://stackoverflow.com/q/48637822
tagged with: python
possible better answer: http://stackoverflow.com/a/48637855
upvote count: 10
answer count: 4
has title: How do I obtain the second highest value in a row?
has answer: http://stackoverflow.com/a/48637855
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/76933250
downvote count: 0
has answer: http://stackoverflow.com/a/48637957
has body: I want to obtain the second highest value of a certain section for each row from a dataframe. How do I do this? I have tried the following code but it doesn't work: df.iloc[:, 5:-3].nlargest(2)(axis=1, level=2) Is there any other way to obtain this?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48638056
has answer: http://stackoverflow.com/a/48638056
score: 10

http://stackoverflow.com/a/48508080
score: 2
has comment: http://stackoverflow.com/comment/84038622
has comment: http://stackoverflow.com/comment/84030753
has comment: http://stackoverflow.com/comment/84038072
answers question: http://stackoverflow.com/q/48502300
type: Answer
has body: You cannot send raw bytes to a USB device. Intead you send URB (that is USB Request Blocks) to a USB endpoint. With usbmon you can discover that endpoint and what are the parameters and payload of the URB, and then replicate that from your program by using libusb. But libusb is a C library to access raw USB devices, but I am not aware of any way to use it directly from the command line. My advice is to write a simple C program that sends the data you want to the proper endpoint and just call it from your script.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48502300

http://stackoverflow.com/a/48619647
has comment: http://stackoverflow.com/comment/84244050
has comment: http://stackoverflow.com/comment/84241999
score: 5
upvote count: 5
has body: (Turns out this does not do exactly what OP wants. Still leaving this here as it might help others.) To include mutually exclusive elements, you could wrap those in lists within the list, get the combinations of those, and then the product of the combinations of sub-lists: &gt;&gt;&gt; from itertools import combinations, product &gt;&gt;&gt; l = [[1, 3], [2], [4], [5]] &gt;&gt;&gt; [c for c in combinations(l, 4)] [([1, 3], [2], [4], [5])] &gt;&gt;&gt; [p for c in combinations(l, 4) for p in product(*c)] [(1, 2, 4, 5), (3, 2, 4, 5)] A more complex example: &gt;&gt;&gt; l = [[1, 3], [2, 4, 5], [6], [7]] &gt;&gt;&gt; [c for c in combinations(l, 3)] [([1, 3], [2, 4, 5], [6]), ([1, 3], [2, 4, 5], [7]), ([1, 3], [6], [7]), ([2, 4, 5], [6], [7])] &gt;&gt;&gt; [p for c in combinations(l, 3) for p in product(*c)] [(1, 2, 6), (1, 4, 6), ... 13 more ... (4, 6, 7), (5, 6, 7)] This does not generate any "junk" combinations to be filtered out afterwards. However, it assumes that you want at most one element from each "exclusive" group, e.g. in the second example, it not only prevents combinations with 2,4,5, but also those with 2,4, 4,5, or 2,5. Also, it is not possible (or at least not easy) to have exclusively one of 1,3, and 1,5, but allow for 3,5. (It might be possible to extend it to those cases, but I'm not yet sure if and how.) You can wrap this in a function, deriving the slightly different input format from your (presumed) format and returning an accordant generator expression. Here, lst is the list of elements, r the number of items per combinations, and exclude_groups a list of groups of mutually-exclusive elements: from itertools import combinations, product def comb_with_excludes(lst, r, exclude_groups): ex_set = {e for es in exclude_groups for e in es} tmp = exclude_groups + [[x] for x in lst if x not in ex_set] return (p for c in combinations(tmp, r) for p in product(*c)) lst = [1, 2, 3, 4, 5, 6, 7] excludes = [[1, 3], [2, 4, 5]] for x in comb_with_excludes(lst, 3,…
type: Answer
has comment: http://stackoverflow.com/comment/84241511
has comment: http://stackoverflow.com/comment/84275182
has comment: http://stackoverflow.com/comment/84243939
has comment: http://stackoverflow.com/comment/84242495
answers question: http://stackoverflow.com/q/48616694
downvote count: 0
has comment: http://stackoverflow.com/comment/84246279
has comment: http://stackoverflow.com/comment/84242367
has comment: http://stackoverflow.com/comment/84246395

http://stackoverflow.com/comment/84163317
has text: You really shouldn't run things like DNNs in your server process. Instead you should use a job queue to decouple the two.
score: 0
comment on: http://stackoverflow.com/q/48516846
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48635083
favorite count: 0
type: Question
has title: Is there a function to find out how to get precise numbers represented in float format?
has comment: http://stackoverflow.com/comment/84271834
has comment: http://stackoverflow.com/comment/84266992
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4610999
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84267114
score: -7
has comment: http://stackoverflow.com/comment/84267003
has body: ok, 2^32, 2^32+1, 2^32+2 isn't precise when stored as a float. however, 2^64 is, is there function out that i can feed it a number, and it tell me if a float will store it precisely. the only reason i am interested in floats is because i want to store very long digit numbers in as few bytes as possible. 2^64 is 20 digits. i found this article, but i'm not sure if it applies since it talks about doubles and i know python does things differently? How to Calculate Double + Float Precision
has answer: http://stackoverflow.com/a/49110300
has comment: http://stackoverflow.com/comment/84267083
downvote count: 7

http://stackoverflow.com/comment/84273824
type: QuestionComment
type: Comment
has text: Why cannot I use Process in this way?
score: 0
comment on: http://stackoverflow.com/q/48634517

http://stackoverflow.com/comment/84192195
score: 2
type: Comment
type: AnswerComment
has text: Any of the above suggestions are good for debugging and they show that the function *does* indeed run. Note that performing a `print()` within the function is normally a bad idea and they should be removed once the problem is identified.
comment on: http://stackoverflow.com/a/48597736

http://stackoverflow.com/comment/84262947
type: QuestionComment
has text: If it works in command line then it should work in the IDE. The only issue here could be that the IDE is not set up correctly.
comment on: http://stackoverflow.com/q/48632439
score: 0
type: Comment

http://stackoverflow.com/comment/84027650
type: QuestionComment
comment on: http://stackoverflow.com/q/48516379
score: 0
type: Comment
has text: hi ilja, yes that is exactly my question, how would I combine this in one query? And can you also explain how you would rearrange my db to make it faster (by adding indexes) thanks

http://stackoverflow.com/a/48576634
has comment: http://stackoverflow.com/comment/84160301
downvote count: 0
has comment: http://stackoverflow.com/comment/84151129
has body: You can use slicers: idx = pd.IndexSlice df1.loc[idx[:, '00:00:00':'02:00:00'],:] = 1 Or if second levels are times: import datetime idx = pd.IndexSlice df1.loc[idx[:, datetime.time(0, 0, 0):datetime.time(2, 0, 0)],:] = 1 Sample: print (df1) aaa date time 2018-01-26 00:00:00 21.65 00:15:00 NaN 00:30:00 NaN 00:45:00 NaN 01:00:00 NaN 01:15:00 NaN 01:30:00 NaN 01:45:00 NaN 02:00:00 NaN 02:15:00 NaN 02:30:00 NaN 02:45:00 NaN 03:00:00 NaN 2018-01-27 00:00:00 2.00 00:15:00 NaN 00:30:00 NaN 00:45:00 NaN 01:00:00 NaN 01:15:00 NaN 01:30:00 NaN 01:45:00 NaN 02:00:00 NaN 02:15:00 NaN 02:30:00 NaN 02:45:00 NaN 03:00:00 NaN idx = pd.IndexSlice df1.loc[idx[:, '00:00:00':'02:00:00'],:] = 1 print (df1) aaa date time 2018-01-26 00:00:00 1.0 00:15:00 1.0 00:30:00 1.0 00:45:00 1.0 01:00:00 1.0 01:15:00 1.0 01:30:00 1.0 01:45:00 1.0 02:00:00 1.0 02:15:00 NaN 02:30:00 NaN 02:45:00 NaN 03:00:00 NaN 2018-01-27 00:00:00 1.0 00:15:00 1.0 00:30:00 1.0 00:45:00 1.0 01:00:00 1.0 01:15:00 1.0 01:30:00 1.0 01:45:00 1.0 02:00:00 1.0 02:15:00 NaN 02:30:00 NaN 02:45:00 NaN 03:00:00 NaN EDIT: For assign array is necessary use numpy.tile for repeat by length of first level unique values: df1.loc[idx[:, '00:00:00':'02:00:00'],:] = np.tile(np.arange(1, 10),len(df1.index.levels[0])) print (df1) aaa date time 2018-01-26 00:00:00 1.0 00:15:00 2.0 00:30:00 3.0 00:45:00 4.0 01:00:00 5.0 01:15:00 6.0 01:30:00 7.0 01:45:00 8.0 02:00:00 9.0 02:15:00 NaN 02:30:00 NaN 02:45:00 NaN 03:00:00 NaN 2018-01-27 00:00:00 1.0 00:15:00 2.0 00:30:00 3.0 00:45:00 4.0 01:00:00 5.0 01:15:00 6.0 01:30:00 7.0 01:45:00 8.0 02:00:00 9.0 02:15:00 NaN 02:30:00 NaN 02:45:00 NaN 03:00:00 NaN More general solution with generated array by length of slice: idx = pd.IndexSlice len0 = df1.loc[idx[df1.index.levels[0][0], '00:00:00':'02:00:00'],:].shape[0] len1 = len(df1.index.levels[0]) df1.loc[idx[:, '00:00:00':'02:00:00'],:] = np.tile(np.arange(1, len0 + 1), len1) Tested with times: import datetime idx = pd.IndexSlice arr =np.tile(np.ara…
upvote count: 1
has comment: http://stackoverflow.com/comment/84160152
has comment: http://stackoverflow.com/comment/84160724
has comment: http://stackoverflow.com/comment/84161210
has comment: http://stackoverflow.com/comment/84160828
has comment: http://stackoverflow.com/comment/84151167
has comment: http://stackoverflow.com/comment/84159818
type: Answer
has comment: http://stackoverflow.com/comment/84161459
accepted answer of: http://stackoverflow.com/q/48576286
has comment: http://stackoverflow.com/comment/84160445
has comment: http://stackoverflow.com/comment/84159945
has comment: http://stackoverflow.com/comment/84150458
has comment: http://stackoverflow.com/comment/84161586
has comment: http://stackoverflow.com/comment/84150486
answers question: http://stackoverflow.com/q/48576286
has comment: http://stackoverflow.com/comment/84160386
has comment: http://stackoverflow.com/comment/84150265
has comment: http://stackoverflow.com/comment/84150179
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48586174
has comment: http://stackoverflow.com/comment/84173184
answer count: 1
has body: I am trying to make a program using Python that allows the user to pick a function and graph it over specified values. I have this: import matplotlib.pyplot as plt import math import numpy as np from sympy import Symbol, Derivative, sin, sympify from sympy.core.sympify import SympifyError x = Symbol('x') fx = sympify(input("What is your function? ")) x_min = float(input("Enter x minimum: ")) x_max = float(input("Enter x maximum: ")) x_values = np.linspace(x_min, x_max, 3) y_values = fx.doit().subs({x:x_values}) plt.plot(x_values, y_values) plt.show() I input x**2 for the function, 0 for x_min, and 3 for x_max. The error I get is: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sympy/core/sympify.py", line 178, in sympify expr = parse_expr(a, locals or {}, rational, convert_xor) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sympy/parsing/sympy_parser.py", line 163, in parse_expr expr = eval(code, global_dict, local_dict) # take local objects in preference File "&lt;string&gt;", line 1 [Float ('0.' )Float ('1.5' )Float ('3.' )] ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/joe126/Dropbox/Python/Chapter02.py", line 16, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sympy/core/basic.py", line 831, in subs so, sn = sympify(o), sympify(n) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sympy/core/sympify.py", line 180, in sympify raise SympifyError('could not parse %r' % a) sympy.core.sympify.SympifyError: SympifyError: "could not parse '[0. 1.5 3. ]'" What is going wrong? Thanks.
has answer: http://stackoverflow.com/a/48588111
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84172314
has comment: http://stackoverflow.com/comment/84170607
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/48588111
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: sympy
has title: Error When Trying to Create Function Grapher

http://stackoverflow.com/a/48507675
accepted answer of: http://stackoverflow.com/q/48507460
type: Answer
answers question: http://stackoverflow.com/q/48507460
upvote count: 8
score: 8
downvote count: 0
type: AcceptedAnswer
has body: An effective way to document code and open it up to understanding by new devs in my experience is literate programming. https://en.wikipedia.org/wiki/Literate_programming The main thing is that there's a narrative that really explains what's going on, rather than a set of loose remarks. I prefer a somewhat non-standard form of literate programming, where I put my comments behind the code, rather than in between it. Experienced devs won't be hindered by it in this way. So like: class Node (object): # Node representing atomary partial state in a state machine def __init__ (self, value = Nothing): # Initial value is optional, not needed in case of dependent nodes ('Nothing' introduced y15m02d14) self.sinkNodes = [] # Nodes that depend on this node self.links = [] # Zero or more links to bareRead / bareWrite pairs self.exceptions = [] self.actions = [] self.validator = lambda value: True # Validators are deprecated, use exceptions instead self.persistent = False # Assume not worth persisting self.recursionCount = 0 if value == Nothing: # If node is uninitialized self.event = 0 # It should be updated else: # If node is supposed to be freely initialized self.currentValue = value # Free initialisation self.previousValue = self.currentValue # Make sure previousValue is available in case of free initialisation self.event = currentEvent () # Remember up to date if not value is None: # If it is a freely initialized ordinary node rather than an event-only node self.persistent = True # Remember it is part of a non-redundant basis for persistence (etc.) On the other hand blindly placing an obvious remark at each class and function and then generating doc with a tool hasn't helped me much in understanding anything. I need to have the actual code at hand, which is the case here. At truly difficult points in your code it doesn't hurt to have an explanation block over the full width. ''' As soon as we encounter a module in the chain that isn't already there, we'll have to create the …

http://stackoverflow.com/q/48555986
tagged with: python-hypothesis
has title: How to pass different DataType values in hypothesis and how to check return type and value is correct in Python
type: Question
score: 0
has answer: http://stackoverflow.com/a/49002734
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: hypothesis-test
tagged with: unit-testing
tagged with: assert
has body: Doing sample code for Unit Test in Python with Hypothesis module. Wrote simple getTimeDelta function to get time difference between two dates. Want to write Unit Test of the getTimeDelta function. Used hypothesis modules to get multiple datetime values. Question is that: 1. How to I pass different data type values i.e. time1 is str and time2 is datetime without writing multiple functions? checking only datatype of return value, not actual result is correct or not. How to do that? How to check data types of items, of result tuple? assertIsInstance Code: import unittest from hypothesis import given from hypothesis import strategies as st import datetime from dateutil.parser import parse as time_parse def getTimeDelta(time1, time2): try: if isinstance(time1, str): time1 = time_parse(time1) if isinstance(time2, str): time2 = time_parse(time2) return (time1 - time2, {"message": ""}) except Exception as err: return (False, {"message": "Exception {}".format(err)}) class TestTimeDeltaCalc(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestTimeDeltaCalc, self).__init__(*args, **kwargs) self.utils = Utils() @given(st.datetimes(), st.datetimes()) def test_time_delta(self, time1, time2): time_delta = getTimeDelta(time1, time2) if time_delta[0] is False: self.assertIsInstance(time_delta[0], bool) else: self.assertIsInstance(time_delta[0], datetime.timedelta) self.assertIsInstance(time_delta[1], dict) @given(st.text(), st.text()) def test_time_delta(self, time1, time2): time_delta = getTimeDelta(time1, time2) if time_delta[0] is False: self.assertIsInstance(time_delta[0], bool) else: self.assertIsInstance(time_delta[0], datetime.timedelta) self.assertIsInstance(time_delta[1], dict) if __name__ == '__main__': unittest.main() Edit 01: We can fix #Question1 by hypothesis.strategies.one_of(*args), link

http://stackoverflow.com/comment/84168522
type: Comment
type: AnswerComment
has text: Hi. Thanks. Another Nice compact solution. It seems there is no built-in function and no way around a custom function. +1
score: 0
comment on: http://stackoverflow.com/a/48585737

http://stackoverflow.com/comment/84252264
score: 1
comment on: http://stackoverflow.com/a/48625996
type: Comment
has text: By calling _simulateModel_ you get the simulation results as .mat file in the Dymola working directory. The post "Modelica - Dymola Python interface: Set output format to textual" explains how to get the simulation results as .txt file instead of .mat. You can add the code anywhere before calling _simulateModel_
type: AnswerComment

http://stackoverflow.com/comment/84227239
score: 1
has text: `window.onclick()` just registers a function to be called when a click occurs. It cannot possibly return the location of a click, because the click hasn't happened yet. Anything you want to happen in response to a click, you must put inside (or called by) the registered function.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48614047

http://stackoverflow.com/a/48614348
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48614005
has comment: http://stackoverflow.com/comment/84243757
type: Answer
has body: I found one way to get around this. Using server.start() does not start the tornado webserver, so nothing will happen in the initial approach. On the other hand, looking at the code for server.run_until_shutdown() generates a system signal before running the tornado IOLoop`, which would not work if the server is running on a thread. I found an example in bokeh repository, and linked from the docs, where the torando server can be started manually in a blocking call on the thread (no signals required). Here the code which should go in the run method of the thread: def run(self): server = Server({'/': self.make_document}) server.start() server.io_loop.add_callback(server.show, "/") server.io_loop.start()
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/48614005

http://stackoverflow.com/q/48528351
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48528506
score: 1
tagged with: python
has title: Django: change language from timesince
tagged with: django-settings
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has body: I want to change the language of timesince. Do I need to change directly in my django source or is there a way to modify TIMESINCE_CHUNKS variable in the settings file?
tagged with: django

http://stackoverflow.com/q/48543486
tagged with: tensorflow
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python
has body: We are using tensorflow library for face recognition. Our code works fine for single images. But when we run it as an API, the prediction time increases for every subsequent request. This happens because it searches for previously predicted images as well which should ideally not happen. Please find below the code I am using. def train: with tf.Session(config=tf.ConfigProto(log_device_placement=False)) as sess: test_set = _get_test_data(input_directory) images, labels = _load_images_and_labels(test_set, image_size=160, batch_size=batch_size, num_threads=4, num_epochs=1) _load_model(model_filepath=model_path) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) sess.run(init_op) images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0") embedding_layer = tf.get_default_graph().get_tensor_by_name("embeddings:0") phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0") coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess,coord=coord) emb_array, label_array = _create_embeddings(embedding_layer, images, labels, images_placeholder, phase_train_placeholder, sess) classifier_filename = classifier_output_path class_name, prob = _evaluate_classifier(emb_array, label_array, classifier_filename) coord.request_stop() coord.join(threads) def _create_embeddings(embedding_layer, images, labels, images_placeholder, phase_train_placeholder, sess): emb_array = None label_array = None try: i = 0 while True: print("batch images") batch_images, batch_labels = sess.run([images, labels]) print('Processing iteration {} batch of size: {}'.format(i, len(batch_labels))) emb = sess.run(embedding_layer, feed_dict={images_placeholder: batch_images, phase_train_placeholder: False}) emb_array = np.concatenate([emb_array, emb]) if emb_array is not None else emb label_array = np.concatenate([label_array, batch_labels]) if label_array is not None else batch_labels i += 1 except tf.errors.OutOfRange…
score: 2
upvote count: 2
tagged with: image-recognition
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48559751
has title: TensorFlow prediction runs for deleted images also
has answer: http://stackoverflow.com/a/48559751

http://stackoverflow.com/comment/84199807
has text: @displayname event_type can only be two ("a" or "b"), the IDs can be n. There's not a row like ´´´1 "c" 6´´´ in the dataframe.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48601441
score: 0

http://stackoverflow.com/q/48500373
has title: How to parse parameters from JSON file in python as a string?
score: 0
has answer: http://stackoverflow.com/a/48500529
has body: I am a newbie in python. I am trying to read some parameters from a JSON file and pass it as parameters in a command through the python os.system module. Following is my code: import json jdata = open('Az.json').read() params = json.loads(jdata) os.system('export rg=%s' %params['global']) the Az.Json file is basically a dictionary, and I am trying to set the environment variable 'rg' by reading the value associated with the 'global' key in the dictionary. But, my code is not working because it is reading it in Unicode format. I am not able to convert that Unicode data to string. Can someone please help me solve this problem?
has comment: http://stackoverflow.com/comment/83994273
has comment: http://stackoverflow.com/comment/83994160
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83994090
answer count: 1
has comment: http://stackoverflow.com/comment/83994053
tagged with: unicode
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83994096
tagged with: python
type: Question

http://stackoverflow.com/a/48574365
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48574075
has comment: http://stackoverflow.com/comment/84180920
has body: I really like Pir 's approach , and here is mine :-) df1.loc[df2.index,df2.columns]*=df2 df1 Out[293]: A B C All One 10.0 40.0 90.0 60 Two 250.0 360.0 490.0 180 Three 180.0 10.0 50.0 110 All 150.0 90.0 110.0 350
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84181868

http://stackoverflow.com/q/48615015
has answer: http://stackoverflow.com/a/48627260
has comment: http://stackoverflow.com/comment/84227390
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48615193
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84227302
has body: Total noob, seriously and angrily struggling with Python... What I'm trying to do SHOULD be simple: Make a button. Connect that button go a function. Click button --> run function. The problem comes when we have to use CLASS (which, no matter how much I read, study - or even pay to take classes continues to make zero sense to me)... I've tried every concieveable combination of putting this little convert() function IN the class, of adding self.convert or root.convert - and NONE of it works. And, I am clueless why - or what to try next. Here's the code: from tkinter import * from tkinter.ttk import Frame, Button, Style def convert(): print("clicked") kg = entry_kg.get() print(kg) class Example(Frame): def __init__(self): super().__init__() self.initUI() # initiate the GUI # ------------------------------- def initUI(self): self.master.title("Weight Converter") self.pack(fill=BOTH, expand=True) # ------------------------------------- frame_kg = Frame(self) # frame for Kilograms frame_kg.pack(fill=X) lbl_kg = Label(frame_kg, text="Kilograms", width=16) lbl_kg.pack(side=LEFT, padx=5, pady=5) entry_kg = Entry(frame_kg) entry_kg.pack(fill=X, padx=(5, 30), expand=True) # ------------------------------------------------ frame_btn = Frame(self) # frame for buttons frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5) btn_convert=Button(frame_btn, text="Convert", command=convert) btn_convert.pack(side=LEFT, padx=5, pady=5) # ------------------------------------------- def main(): root = Tk() root.geometry("300x200+300+200") app = Example() root.mainloop() if __name__ == '__main__': main() What am I doing wrong? How to do it right? The seemingly arbitrary and useless over-complication of a simple task is seriously maddening...
has comment: http://stackoverflow.com/comment/84227428
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48615106
has comment: http://stackoverflow.com/comment/84227372
has comment: http://stackoverflow.com/comment/84227146
has title: tkinter button in class can't call function
has comment: http://stackoverflow.com/comment/84227352
answer count: 3
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84227450
score: -1

http://stackoverflow.com/comment/83987472
score: 0
has text: @WarrenWeckesser. It does work for me.
type: QuestionComment
comment on: http://stackoverflow.com/q/48491649
type: Comment

http://stackoverflow.com/q/48554693
tagged with: python
linked to: http://stackoverflow.com/q/48427514
has answer: http://stackoverflow.com/a/54864084
score: 15
favorite count: 0
has comment: http://stackoverflow.com/comment/84105872
type: AnsweredQuestion
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48555361
accepted answer: http://stackoverflow.com/a/48555361
linked to: http://stackoverflow.com/q/48479910
upvote count: 15
type: Question
has title: Python - "No module named my_module" in terminal, but not in PyCharm
tagged with: pycharm
linked to: http://stackoverflow.com/q/48532134
has comment: http://stackoverflow.com/comment/84106625
has body: I have a python script that i'm trying to run. When i run it from within PyCharm it runs without a problem, but when i run it through the terminal using: python my_script.py i get: Traceback (most recent call last): File "folder/folder/my_script.py", line 4, in &lt;module&gt; from my_module import me1, me2, me3 ImportError: No module named my_module What could be the problem?
has comment: http://stackoverflow.com/comment/84105705
has answer: http://stackoverflow.com/a/62282440
possible better answer: http://stackoverflow.com/a/54864084
has comment: http://stackoverflow.com/comment/84105708

http://stackoverflow.com/a/48650638
has comment: http://stackoverflow.com/comment/84301418
has comment: http://stackoverflow.com/comment/84332371
has comment: http://stackoverflow.com/comment/84363681
has comment: http://stackoverflow.com/comment/84301580
has comment: http://stackoverflow.com/comment/84313536
type: Answer
accepted answer of: http://stackoverflow.com/q/48591455
has body: You could try to install glibc 2.14 in a specific path and force it with an env variable: export LD_LIBRARY_PATH=/home/user/.usr/lib Check this answer about how to do it: How to upgrade glibc from version 2.12 to 2.14 on CentOS? what is your distrib, and which version?
answers question: http://stackoverflow.com/q/48591455
score: 5
has comment: http://stackoverflow.com/comment/84313493
type: AcceptedAnswer
downvote count: 1
upvote count: 6

http://stackoverflow.com/comment/139685903
type: AnswerComment
comment on: http://stackoverflow.com/a/78851316
type: Comment
has text: @Katana24 The problem with your suggestion is which `python` are you running? It might be the "system" python, which could be `/usr/bin/python2`. It's hard to tell what that does. Better to explicitly call the `python3` interpreter that you want to use.
score: 0

http://stackoverflow.com/comment/84001008
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48503600
has text: what about stdin?
score: 0

http://stackoverflow.com/comment/83994900
comment on: http://stackoverflow.com/a/48498570
score: 0
type: AnswerComment
type: Comment
has text: http://strftime.org/ is a better resource than the official docs (sadly).

http://stackoverflow.com/q/48521128
has answer: http://stackoverflow.com/a/48527436
score: 0
answer count: 1
has title: Struggling to display a modelForm in admin panel
has comment: http://stackoverflow.com/comment/84037750
type: Question
has comment: http://stackoverflow.com/comment/84038310
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84039289
tagged with: django
tagged with: python
has body: Im trying add custom ModelForm to Django admin panel, however I am getting this error. django.core.exceptions.FieldError: Unknown field(s) (tron, rchain, etc..) I want to have a form in admin-panel when you click add to 'Currencies' there will be a choice of currencies and you can select one. I have been tweaking it for a while and can not come up with a solution. Basically, i believe I need to create a model instances 'on the go' whenever I select a currency in the admin panel.But how do I achieve it ? My code below #modelForm.py class Currencies_Form(ModelForm): #tuplez = [(i,) for i in Coins.arr] cryptoId = forms.ChoiceField(choices=Coins.arr, initial=' ', widget=forms.Select()) class Meta: model = Currencies fields = Coins.arr models.py class Currencies(models.Model): cryptoId = models.CharField(max_length=50) cryptoPrice = models.CharField(max_length=50) My file with an api call and data - CoinAPI.py class Coins: def __init__(self): self.arr = [] self.hashTable = {} params = 100 data = requests.get('https://api.coinmarketcap.com/v1/ticker/?limit={}'.format(params)).json() for objects in data: for k in objects.keys(): if k == 'id': self.arr += objects[k].split() self.hashTable.update({objects[k]:objects['price_usd']}) Coins = Coins() and my admin.py class whatever(admin.ModelAdmin): form = Currencies_Form admin.site.register(Currencies,whatever) Please don't mind the naming, clearly not PEP-8 standard, it's just for my local testing yet. To clarify what I want I'll post a screenshots on the add button I want a list of available currencies from the Coins.arr(array of currency names) almsot like this but as a list to select 1 from. I realise this post isn't great, but I really have no idea how else to explain this.

http://stackoverflow.com/q/48512449
answer count: 1
has title: Filter Pandas Dataframe that is an array
type: Question
has comment: http://stackoverflow.com/comment/84019882
has comment: http://stackoverflow.com/comment/84019909
has comment: http://stackoverflow.com/comment/84019827
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: filter
has body: I have a data frame that I'd like to filter by a column that is of type array. What is the most effective way to do this? df = pd.DataFrame({'a': [1,2,3,4,5], 'b': [['true','false'],['false'],['false','false','false'],['false','false','true'],[]]}) df a b 0 1 [true, false] 1 2 [false] 2 3 [false, false, false] 3 4 [false, false, true] 4 5 [] I'd ideally like to only return rows that contain a true value.
has answer: http://stackoverflow.com/a/48512602
accepted answer: http://stackoverflow.com/a/48512602
tagged with: pandas

http://stackoverflow.com/a/48501946
has comment: http://stackoverflow.com/comment/83998653
answers question: http://stackoverflow.com/q/48501822
has comment: http://stackoverflow.com/comment/83998691
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/83997774
upvote count: 3
has body: You can use pandas' Categorical data type for this: order = ["Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] data_file['day_of_week'] = pd.Categorical(data_file['day_of_week'], categories=order, ordered=True) data_file.sort_values(by='day_of_week', inplace=True) In your example, be aware that when you specify days = data_file['day_of_week'] you are creating a view to that column (Series) within your data_file frame. You may want to use days = data_file['day_of_week'].copy(). Or, just work within the DataFrame as is done above.
accepted answer of: http://stackoverflow.com/q/48501822
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84093353
type: QuestionComment
comment on: http://stackoverflow.com/q/48548437
score: 0
has text: There is no VS abbreviation in the scenario. I should not put it there. And there are overlapping brand names but for the sake of performance we can assume no overlapping
type: Comment

http://stackoverflow.com/comment/84258305
type: Comment
type: QuestionComment
has text: I am sorry, I had a little bit mistake and now I edited it.
comment on: http://stackoverflow.com/q/48630570
score: 0

http://stackoverflow.com/q/48499207
possible better answer: http://stackoverflow.com/a/48499315
has comment: http://stackoverflow.com/comment/83991958
has body: I am absolutely new to programming atm. I have searched the forums but none of the results were applicable to my case (unless I am mistaken, but trust me the first thing I did was to google). Please help me if you have time. Write a python program that prompts the user to enter a list of first names and stores them in a list. The program should display how many times the letter 'a' appears within the list. Now I thought I have got the PERFECT code. But everytime the program only counts the number of "a"s in the first word on the list!? terminate = False position = 0 name_list = [ ] while not terminate: name = str(input('Please enter name: ')) name_list.append(name) response = input('Add more names? y/n: ') if response == 'n': terminate = True print(name_list) for t in name_list: tally = name_list[position].count('a') position = position + 1 print("The numer of 'a' is: ", tally) If anyone has time to help I would appreciate it.
downvote count: 1
has answer: http://stackoverflow.com/a/48499416
favorite count: 0
type: Question
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83992342
has answer: http://stackoverflow.com/a/48499483
has comment: http://stackoverflow.com/comment/83992099
tagged with: python
has comment: http://stackoverflow.com/comment/83992407
has answer: http://stackoverflow.com/a/48499314
accepted answer: http://stackoverflow.com/a/48499314
has comment: http://stackoverflow.com/comment/83991899
answer count: 4
tagged with: list
has title: Python - searching for letters in a list of words
upvote count: 1
has answer: http://stackoverflow.com/a/48499315

http://stackoverflow.com/comment/84039746
type: QuestionComment
comment on: http://stackoverflow.com/q/48521184
has text: You did not read my comment with `BEFORE the while loop.` !?
score: 0
type: Comment

http://stackoverflow.com/q/48547141
score: 0
answer count: 1
tagged with: bokeh
has answer: http://stackoverflow.com/a/48547365
has body: Hoi, I am in the process of making a couple of bar-graphs with bokeh using vbar. Furthermore I added whiskers as error-bars and this all worked quite well, but my whiskers show up in the background of the bar graph and I cannot find the attribute, where I can specify this. I imagine this has to be specified in either add_layout or in Whisker. p.vbar(x=dodge('genes', 0.25, range=p.x_range), top='100uM', width=0.2, source=source, color="#e84d60", legend=value("100uM")) p.add_layout( Whisker(source=source, base=dodge('genes', 0.25, range=p.x_range), upper="top_100uM", lower="bottom_100uM") ) Am I blind, or does this option not exist? Cheers, Sebastian
type: Question
has title: Bokeh - How to get whiskers into foreground
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84097014
score: 0
type: AnswerComment
has text: Thanks, but how to put the element and the tuple as arguments? That part is not working.
type: Comment
comment on: http://stackoverflow.com/a/48550495

http://stackoverflow.com/comment/84244405
score: 0
has text: Yes. `PYTHONUNBUFFERED` has nothing to do with it though. You want to make sure that you have correctly configured the IDE environment. Without any mention on how it is configured we cannot help you.
comment on: http://stackoverflow.com/q/48622006
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84089670
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48533781
has text: Please do fix your indentation though and add a little prose to explain what you are doing in each case.

http://stackoverflow.com/q/48542140
tagged with: python
tagged with: httprequest
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48594545
has title: internal server error and forbidden access
has answer: http://stackoverflow.com/a/48594545
has comment: http://stackoverflow.com/comment/84079228
answer count: 1
downvote count: 0
score: 1
tagged with: web-scraping
upvote count: 1
tagged with: python-requests
has body: I am try to do web scraping of a website with the following code. import http.client from bs4 import BeautifulSoup import urllib.request from lxml.html import fromstring from http.client import HTTPConnection #as _HTTPConnection, HTTPException base_url = "https://apct.gov.in/apportal/Search/ViewAPVATDealers.aspx" page = urllib.request.urlopen(base_url) soup = BeautifulSoup(page, "html.parser") path = fromstring(soup.decode('utf-8')) header = { "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":"en-US,en;q=0.9", "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", } url = "https://apct.gov.in/apportal/Search/ViewAPVATDealers.aspx" form_data={} form_data["__EVENTTARGET"] = "" form_data["__EVENTARGUMENT"] = "" form_data["__LASTFOCUS"] = "" form_data["__VIEWSTATE"] = path.xpath('//*[@id="__VIEWSTATE"]/@value') form_data["__EVENTVALIDATION"] = path.xpath('//*[@id="__EVENTVALIDATION"]/@value') form_data["ctl00$ContentPlaceHolder1$dropact"] = "LT" form_data["ctl00$ContentPlaceHolder1$Ddl_Divisions"] = "GUNTUR" form_data["ctl00$ContentPlaceHolder1$Ddl_Circles"] = "All Circles" form_data["ctl00$ContentPlaceHolder1$ddlbusines"] = "Agent" conn = http.client.HTTPConnection('apct.gov.in') url_params = urllib.parse.urlencode(header) # 1 # # conn.request("POST", url, url_params, header) # response = conn.getresponse() # print(response.status, response.reason) # data = response.read() # print(data) # conn.close() # 2 # # r = requests.post(url,form_data,url_params) # #import pdb; pdb.set_trace() # print(r.status_code, r.reason) When i run the 1st comment part to retrieve response it shows 403 forbidden and when i run the 2nd commented part it shows internal server error. Can anyone find any mistake in any line due to which i am getting this error. I know with such limited information it is difficult to …
favorite count: 0
has comment: http://stackoverflow.com/comment/84079341
type: Question
tagged with: lxml
has comment: http://stackoverflow.com/comment/84079803

urllib
tags question: http://stackoverflow.com/q/48603339
type: Tag
tags question: http://stackoverflow.com/q/48614058
tags question: http://stackoverflow.com/q/48602625
tag name: urllib
tags question: http://stackoverflow.com/q/48631408
tags question: http://stackoverflow.com/q/48489443
tags question: http://stackoverflow.com/q/48594666
tags question: http://stackoverflow.com/q/48506352
tags question: http://stackoverflow.com/q/48529032

http://stackoverflow.com/comment/84175621
score: 0
comment on: http://stackoverflow.com/q/48589235
type: Comment
type: QuestionComment
has text: You could just find every `c` and count the `d`s after it.

http://stackoverflow.com/comment/84065597
type: Comment
type: QuestionComment
has text: Based on the [`DataFrame.to_latex` help](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_latex.html), you can supply `escape = False` (default is `True`). Try it.
comment on: http://stackoverflow.com/q/48516653
score: 0

http://stackoverflow.com/comment/84020799
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48512943
type: QuestionComment
has text: Edited to add the rest of the code with the link to the website.

http://stackoverflow.com/comment/84106970
has text: You can then have your forms post to each view you need. Im sure there are other ways to tackle this.
type: Comment
comment on: http://stackoverflow.com/a/48555440
score: 0
type: AnswerComment

secret-key
tags question: http://stackoverflow.com/q/48612895
tags question: http://stackoverflow.com/q/48606268
tag name: secret-key
type: Tag

http://stackoverflow.com/comment/84344501
type: Comment
score: 0
type: AnswerComment
has text: @PaulPanzer, I mean subdiagonal (`i==j+1` and `j-1`). I already did it by slicing the original matrix to a specific shape successfully. Thx so much for your help!
comment on: http://stackoverflow.com/a/48633379

http://stackoverflow.com/a/48605345
answers question: http://stackoverflow.com/q/48604742
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: If you just need the data in the template you could use the following (note that the following code is not actually tested, but will hopefully get you in the right direction): views.py ... # Pass whatever model is the foreign key for "doctor" in the ClinicDoctor model context = {"doctors": User.objects.all()} ... template.html Doctor Header Clinics Header {% for doctor in doctors %} {{ doctor }} {% for clinicdoctor in doctor.clinicdoctor_set.all %} clinicdoctor.clinic{% if not forloop.last %}, {% endif %} {% endfor %} {% endfor %} First pass in your doctors queryset to the template and then loop over them. The clinicdoctor_set.all will retrieve all ClinicDoctor entries for that doctor (the _set.all lets you retrieve all entries in a foreign key relationship in reverse). You can then reference the associated clinic foreign key normally. The {% if not forloop.last %}, {% endif %} will add a comma between each clinic entry, except for the last one of the loop. You can read more on this under the Related objects reference and the Template reference.

http://stackoverflow.com/a/65891043
type: Answer
has body: Python 3 For those that are looking for a step by step explanation that is easy to follow here's my 100% solution. It uses queues/stacks via append and pop as sort of suggested by the lesson. You can add various tests at the bottom. Don't forget to remove print outputs before submitting! def solution(A, B): N = len(A) print('START') print('Fish sizes: ' + str(A)) print('Fish directions: ' + str(B)) print() upstream = 0 downstream = [] for n in range(N): fs = A[n] fd = B[n] print('Fish pos: ' + str(n) + ', fish dir: ' + str(fd)+ ', fish size: ' + str(fs)) if fd == 0 and downstream == []: print('No fishes in the way') upstream += 1 print('Fishes gone upstream: ' + str(upstream)) elif fd == 1: downstream.append(fs) print('No fishes in the way') print('Fishes going downstream: ' + str(downstream)) elif fd == 0 and downstream != []: print('Challenge!') while downstream: # pick the downstream head pfs = downstream.pop() # if it's bigger kills upstream, puts back downstream, move on if pfs &gt; fs: downstream.append(pfs) print('Downward eats upward') print('Fishes going downstream: ' + str(downstream)) break # if it's smaller don't put it back and move on to next fish elif pfs &lt; fs: print('Upward eats downward') print('Fishes going downstream: ' + str(downstream)) if downstream == []: upstream += 1 print('Fishes gone upstream: ' + str(upstream)) break continue print() print('FINISH') print('Fishes gone upstream: ' + str(upstream)) print('Fishes going downstream: ' + str(len(downstream))) fishes = upstream + len(downstream) print('Fishes alive: ' + str(fishes)) return fishes if __name__ == '__main__': assert solution([4,3,2,1,5], [0,1,0,0,0]) == 2 print('Test 1 OK!') print() assert solution([1,2,3,4,5], [1,1,1,1,0]) == 1 print('Test 2 OK!') print() assert solution([5,4,3,2,1], [1,0,0,0,0]) == 1 print('Test 3 OK!') print() assert solution([1,2,3,4,5], [1,0,0,0,0]) == 4 print('Test 4 OK!') print() assert solution([1,2,3,4,5], [1,1,1,1,1]) == 5 print('Test 4 OK!') print() H…
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48627743
score: 1

spotipy
tags question: http://stackoverflow.com/q/48594282
tags question: http://stackoverflow.com/q/48608910
tag name: spotipy
type: Tag

http://stackoverflow.com/q/48610772
score: 0
answer count: 1
type: Question
has body: import pywaves as pw import sys, getopt amount = 0 receive = '' try: options, remainder = getopt.getopt( sys.argv[1:], 'r:a', ['receive', 'amount', ]) except getopt.GetoptError as err: print('ERROR:', err) sys.exit(1) for opt, arg in options: if opt in ('-a', '--amount'): amount = arg elif opt in ('-r', '--receive'): receive = arg print('OPTIONS :', options) myAddress = pw.Address(privateKey='MYPRIVATEKEY') otherAddress = pw.Address(receive) myToken = pw.Asset('MYADDRESS') myAmount = amount myAddress.sendAsset(otherAddress, myToken, myAmount) I tried run the code above and it seems my option "a" was not captured. What should I do to get it working? I run the following command line python this.py -r 3PFPovgPu3aBWA1krU544tPDTFiHgpvu7q1 -a 150 It returns ('OPTIONS :', [('-r', '3PFPovgPu3aBWA1krU544tPDTFiHgpvu7q1'), ('-a', '')]) I not sure why the "a" value was empty. How do I change my code to make it work properly?
has answer: http://stackoverflow.com/a/48611391
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84218033
tagged with: python
has title: Python getopts issue
has comment: http://stackoverflow.com/comment/84218646

http://stackoverflow.com/q/48612895
has comment: http://stackoverflow.com/comment/84223706
score: 0
answer count: 3
tagged with: django
has comment: http://stackoverflow.com/comment/84226991
has comment: http://stackoverflow.com/comment/85481567
has answer: http://stackoverflow.com/a/48616118
type: Question
has title: How does SECRET_KEY = os.environ['SECRET_KEY'] in Django work?
has answer: http://stackoverflow.com/a/61255911
tagged with: python
type: UnansweredQuestion
tagged with: secret-key
has comment: http://stackoverflow.com/comment/84223239
has comment: http://stackoverflow.com/comment/84222475
tagged with: digital-ocean
has comment: http://stackoverflow.com/comment/84223204
has body: I have my hardcoded SECRET_KEY in my settings.py file locally and want to put this file onto my live Digital Ocean server. If I just replace SECRET_KEY = 'xxx-xxx-xxx' with SECRET_KEY = os.environ['SECRET_KEY'] will it work? I'm assuming I have to do something else to actually get my local SECRET_KEY on there.
has answer: http://stackoverflow.com/a/48615057

http://stackoverflow.com/q/48625618
favorite count: 0
has body: I have a git repo for a single-header C/C++ library that has a certain .h file in the root. That's where the main code lives. Now I want to make some bindings for other programming languages like Python or Node.js. I would like to put each bindings in its own subfolder. Now the catch is that during publishing only this very subfolder is published. The .h file (located a few levels up and included by a relative path) is not published, and this breaks the installation of the bindings for almost every language. I can see the following options: Symlinks. This is very close to what I need, but they might be problematic on certain file systems, so I'd like to know if there are any reasonable alternatives. Hardlinks. AFAIK, not supported by Git at all. Git hook to ensure that files in the subfolders match the one at the top level, and update them if needed. But since Git hooks are not tracked by Git - some developers may omit the hooks and break it. A script to manually sync files. Pretty much like Git hooks, but more explicit. Might also allow to keep different versions of the .h file in different subfolders, and it would allow to update one bindings and not update the others for some time in the case of urgency. Maybe should come with a server-side hook or CI script to ensure the files match when tagged commit is pushed (e.g. when new version is released). What do you think would be the preferred solution, or are there any unnoticed pitfalls I have missed?
upvote count: 2
accepted answer: http://stackoverflow.com/a/48633743
has answer: http://stackoverflow.com/a/48633743
tagged with: python
answer count: 1
downvote count: 1
tagged with: git
tagged with: c++
tagged with: symlink
has comment: http://stackoverflow.com/comment/84260739
type: Question
type: AnsweredQuestion
has title: Git: keep two locations of the same file in sync
score: 1
tagged with: synchronization

http://stackoverflow.com/q/48542089
has comment: http://stackoverflow.com/comment/84079479
has comment: http://stackoverflow.com/comment/84079322
has comment: http://stackoverflow.com/comment/84079889
score: 9
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48628509
has answer: http://stackoverflow.com/a/48542550
accepted answer: http://stackoverflow.com/a/48542550
has title: PySpark - Convert to JSON row by row
has comment: http://stackoverflow.com/comment/84079612
has comment: http://stackoverflow.com/comment/84079774
has comment: http://stackoverflow.com/comment/84079609
favorite count: 0
type: Question
upvote count: 9
possible better answer: http://stackoverflow.com/a/48628509
tagged with: apache-spark-sql
has body: I have a very large pyspark data frame. I need to convert the dataframe into a JSON formatted string for each row then publish the string to a Kafka topic. I originally used the following code. for message in df.toJSON().collect(): kafkaClient.send(message) However the dataframe is very large so it fails when trying to collect(). I was thinking of using a UDF since it processes it row by row. from pyspark.sql.functions import udf, struct def get_row(row): json = row.toJSON() kafkaClient.send(message) return "Sent" send_row_udf = F.udf(get_row, StringType()) df_json = df.withColumn("Sent", get_row(struct([df[x] for x in df.columns]))) df_json.select("Sent").show() But I am getting an error because the column is inputed to the function and not the row. For illustrative purposes, we can use the df below where we can assume Col1 and Col2 must be send over. df= spark.createDataFrame([("A", 1), ("B", 2), ("D", 3)],["Col1", "Col2"]) The JSON string for each row: '{"Col1":"A","Col2":1}' '{"Col1":"B","Col2":2}' '{"Col1":"D","Col2":3}'
tagged with: pyspark
tagged with: http://stackoverflow.com/tag/json
tagged with: python

http://stackoverflow.com/comment/84216143
type: Comment
score: 0
type: QuestionComment
has text: In most cases, that approach would be appropriate. However, in my case it wouldn't. I would love to explain in detail why, however, It would be a rather long winded explanation. Again, I appreciate your input and feedback. Cheers!
comment on: http://stackoverflow.com/q/48602239

http://stackoverflow.com/comment/84170240
comment on: http://stackoverflow.com/a/48586400
type: Comment
type: AnswerComment
has text: if you can modify the csv, I'd recommend giving your columns meaningful names on the first row of the file. pandas knows how to handle csv files in this format and it will come in handy in a lot of other ways in the future.
score: 0

http://stackoverflow.com/comment/84274936
comment on: http://stackoverflow.com/q/48638398
type: Comment
type: QuestionComment
has text: @AntonyHatchkins you are just making a string with 20 precision from your first answer and you already know both returns diffrent So when you tries to make str that returned value how it will be same, and its not a float value it is str
score: 0

http://stackoverflow.com/a/48515372
score: 0
type: Answer
has body: the type of clean_soup is unicode not BeautifulSoup. clean_soup_2 = BeautifulSoup(clean_soup) clean_soup_2.find_all('div', attrs={'id': 'yw0'})
answers question: http://stackoverflow.com/q/48514985

http://stackoverflow.com/q/48495451
score: 0
has title: Python 3.5: To import a function from the same file, do you need to include the file name?
has body: This is my main function: import kercalc as kc kermat=kc.kernel(args) This is the content of kercalc.py: def kerfunc(args): &lt;code&gt; return value def kernel(args): &lt;code&gt; kermat=kerfunc(args) return kermat Should I include an import statement inside the "kernel" function as follows? def kernel(args): from kercalc import kerfunc kermat=kerfunc(args) &lt;code&gt; return kermat Or should I simply call my function?
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83983923
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48495506
has comment: http://stackoverflow.com/comment/83984217
has comment: http://stackoverflow.com/comment/83984208
tagged with: function
has comment: http://stackoverflow.com/comment/83983890
has answer: http://stackoverflow.com/a/48496421
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83984194
possible better answer: http://stackoverflow.com/a/48495721
has comment: http://stackoverflow.com/comment/83983999
has answer: http://stackoverflow.com/a/48495721
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/48495506

http://stackoverflow.com/a/48623040
type: Answer
has body: The post "find time shift between two similar waveforms" uses the mathematical "correlate" which is only meaningful for equally sized arrays. For your application, the following code will give the desired shift import numpy as np a=[0,0,1,2,3] b=[0,0,0,0,1,2,3,0] np.argmax(np.convolve(a[::-1],b,mode='valid')) ~~~~~~~~~~~~~~~~~~~~~ for the follow up comment question. Try from scipy.linalg import circulant b=[0,1,2,3,0] a=[0,0,1,2,3] [ i for i in range(len(b)) if not False in (a==circulant(b)[:,i])] the problem is convolve doesn't recognize circular matrices
score: 0
has comment: http://stackoverflow.com/comment/84509836
answers question: http://stackoverflow.com/q/48547580

http://stackoverflow.com/q/48544394
has comment: http://stackoverflow.com/comment/84084127
tagged with: forms
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: python
has title: Django 1.10 upload file. form is not valid
has comment: http://stackoverflow.com/comment/84084107
has body: I try upload file from Form in Django. I use Django 1.10. my form {% csrf_token %} Drag your file(s) here or click in this area. my views def upload_files(request): print(request.FILES, request.user.username) if request.POST: print('ok') form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print('YEEEES') return JsonResponse({'data':'ok', 'is_valid': True}) else: return JsonResponse({'data':'Bad', 'is_valid': False}) my forms.py from django import forms from .models import File class UploadFileForm(forms.ModelForm): class Meta: model = File fields = ('file_upload','user',) my model from django.db import models def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return ('user_%s/%s' %(instance.user.id, filename)) class File(models.Model): id = models.IntegerField(primary_key=True) id_user = models.IntegerField() user = models.TextField() uploaded_at = models.DateTimeField(auto_now_add=True) file_upload = models.FileField(upload_to='files/') file_size = models.IntegerField() file_name = models.TextField() I do not know what I'm doing wrong. My form is not valid. Please, help me! P.S. Still, I'm trying to save the file for each user separately, but examples from the Internet do not help
has answer: http://stackoverflow.com/a/48544515
score: 0

http://stackoverflow.com/q/48570602
has title: Maya Python Script works from console, doesnt work from file
has answer: http://stackoverflow.com/a/48579653
accepted answer: http://stackoverflow.com/a/48578575
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48578575
answer count: 2
score: 1
downvote count: 0
tagged with: maya
upvote count: 1
favorite count: 0
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/2808010
possible better answer: http://stackoverflow.com/a/48579653
has body: import maya.cmds as cmds #Function def printTxtField(fieldID): print cmds.textField(fieldID, query=True, text=True) #define ID string for Window winID = 'myWindow' if cmds.window(winID, exists=True): cmds.deleteUI(winID) cmds.window(winID) cmds.columnLayout() whatUSay = cmds.textField() cmds.button(label='Click me', command='printTxtField(whatUSay)') cmds.showWindow() this works fine when I execute it from the console in maya. But when I save it as a file and execute I get this error message: # Error: Object 'myWindow|columnLayout30|textField29' not found. # Traceback (most recent call last): # File "&lt;maya console&gt;", line 1, in &lt;module&gt; # File "&lt;maya console&gt;", line 5, in printTxtField # RuntimeError: Object 'myWindow|columnLayout30|textField29' not found. # I noticed that the numbers in columnLayout30|textField29 rise, each time I execute the script from the console, and then from the file again, which I find confusing, because the old window gets deleted each time. I have found this question: super function doesn&#39;t work inside a maya python module but I am not sure if it is the same issue. I am using IDLE 3.6.4 and Maya 2016 SP6 (I am a lonely artist, trying to get into scripting. (python/maya and C#/unity) What I want to say is, that learning the coding part really isnt that hard. It can be tedious at times, but you can google your way through almost anything. But its the "setting up" part that almost always throws me. Installing IDEs and libraries and "connecting" things. Here I am getting errors all the time. So any general help on what I am missing here, would be very much appreciated)

http://stackoverflow.com/a/67392493
type: Answer
has body: First of all, python doesn’t really have a concept of a table. Also the pipe character | has meaning in python, but it's not for building tables. The pipe character is a bitwise or of characters. For example, 00001111 | 10000000 = 10001111 in binary.
score: 0
answers question: http://stackoverflow.com/q/48613466

http://stackoverflow.com/comment/84257512
type: QuestionComment
score: 0
has text: Please give sample inputs and expected outputs
comment on: http://stackoverflow.com/q/48630146
type: Comment

http://stackoverflow.com/a/48638722
score: 0
answers question: http://stackoverflow.com/q/48638220
type: Answer
has comment: http://stackoverflow.com/comment/84274440
has body: You can do this: df=pd.DataFrame({"A":[1,2,3,4],"val":[[140,89.1,177.47],[90.49,90.9,178.90],[91.66,92.4,177.08],[135,85.65,173.8]]}) B=[] C=[] D=[] for i in range(len(df)): B.append(df["val"][i][0]) C.append(df["val"][i][1]) D.append(df["val"][i][2]) df["B"]=B df["C"]=C df["D"]=D print(df.query("(B &lt; 180-35 &amp; B &gt; 90+35) | (C &lt; 180-35 &amp; C &gt; 90+35) | (D &lt; 180-35 &amp; D &gt; 90+35)")) A val B C D 0 1 [140, 89.1, 177.47] 140.0 89.10 177.47 3 4 [135, 85.65, 173.8] 135.0 85.65 173.80 For convenience you can also drop the colmns B,C,D after selection

http://stackoverflow.com/comment/84058113
type: QuestionComment
score: 0
type: Comment
has text: try in the command-line console `pip <packagename> --version`
comment on: http://stackoverflow.com/q/48530749

http://stackoverflow.com/comment/84116350
comment on: http://stackoverflow.com/q/48560342
score: 1
type: QuestionComment
has text: Is there any particular reason for using Selenium? Twitter has an API that allows automated interactions (subject to API limits), for which there are a number of Python libraries.
type: Comment

http://stackoverflow.com/q/48565776
favorite count: 0
tagged with: pdb
type: Question
has body: Can I step out of a function after stepping into it with step while using pdb / ipdb debugger? And if there's no such option - what is the fastest way to get out of the stepped-in function?
has answer: http://stackoverflow.com/a/48565818
tagged with: ipdb
type: UnansweredQuestion
score: 76
has answer: http://stackoverflow.com/a/48566000
tagged with: python
upvote count: 76
has answer: http://stackoverflow.com/a/49911749
has title: PDB - stepping out of a function
tagged with: python-2.7
answer count: 3
downvote count: 0

http://stackoverflow.com/q/48615596
has body: The codes are as models.py class Firm(models.Model): name = models.CharField(unique=True, max_length=50, verbose_name="Firma Adı") slug = models.SlugField(unique=True, editable=False, max_length=50) class Worksite(models.Model): firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE) name = models.CharField(unique=True, max_length=50, verbose_name="Şantiye Adı") slug = models.SlugField(unique=True, editable=False, max_length=50) class Subcontractor(models.Model): worksite = models.ForeignKey('Worksite', on_delete=models.CASCADE) firm = models.ForeignKey('Firm', related_name="subcontractors", on_delete=models.CASCADE) Can the queryset code be written shorter? views.py class SubcontractorListView(ListView): template_name = 'firm/subcontractor_list.html' context_object_name = "firms" def get_queryset(self): ws = self.request.user.firm.worksites.values_list('id', flat=True) ss = Subcontractor.objects.values_list('firm_id', flat=True).filter(worksite_id__in=ws) return Firm.objects.filter(id__in=ss) Do you have different and short solutions? template {% for firm in firms %} &lt;div class="btn btn-outline-secondary text-left button"&gt;{{ firm }} &lt;/div&gt; {% endfor %}
has title: django ListView query_set code abbreviation
has comment: http://stackoverflow.com/comment/84397907
has comment: http://stackoverflow.com/comment/84285462
tagged with: inner-join
has comment: http://stackoverflow.com/comment/84246193
type: Question
answer count: 0
tagged with: django
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84228383
tagged with: listview
has comment: http://stackoverflow.com/comment/84228607
tagged with: django-queryset
score: 0
has comment: http://stackoverflow.com/comment/84397792

http://stackoverflow.com/q/48607309
tagged with: django-views
has answer: http://stackoverflow.com/a/48636914
answer count: 1
type: Question
has body: I'm trying to run a django application using runserver and am getting an error. python manage.py runserver 8009 Here is the output: Performing system checks... System check identified no issues (0 silenced). February 04, 2018 - 02:48:59 Django version 2.0.2, using settings 'hesab.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x03E9F348&gt; Traceback (most recent call last): File "C:\Users\sarvit\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) I have tried to runserver on port 8000 as well, and same error. Why am I getting this error?
tagged with: server
type: UnansweredQuestion
tagged with: django-models
tagged with: python
score: 0
has title: Runserver python django error

http://stackoverflow.com/q/48547739
type: Question
tagged with: xpath
has comment: http://stackoverflow.com/comment/84091401
has comment: http://stackoverflow.com/comment/84092283
has body: I'm trying to interact with a page that requires entry of a username and a passcode, then requires a click on a reCAPTCHA and then a click on a login button. Entry of the username and passcode and clicking on the reCAPTCHA work fine, but after interacting with the reCAPTCHA, the login button element seems to be unfindable by Selenium. The thing is, the login button element is easily found by Selenium before interacting reCAPTCHA. What's going on? from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait driver = webdriver.Firefox() driver.get("https://localbitcoins.com/accounts/login/") time.sleep(2) element = driver.find_element_by_name("username") element.send_keys("username") element = driver.find_element_by_name("password") element.send_keys("passcode") time.sleep(1) # reCAPTCHA wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_xpath('//iframe[contains(@src, "google.com/recaptcha")]'))) wait(driver, 10).until(EC.element_to_be_clickable((By.ID, "recaptcha-anchor"))).click() # login button elements = driver.find_elements_by_xpath("//button[contains(text(), 'Login')]") elements[0].click()
has answer: http://stackoverflow.com/a/48547888
accepted answer: http://stackoverflow.com/a/48547888
has title: Selenium in Python: button element seems to vanish after interacting with reCAPTCHA. wha?
tagged with: python
type: AnsweredQuestion
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: selenium
tagged with: recaptcha
favorite count: 0

http://stackoverflow.com/q/48614047
tagged with: turtle-graphics
type: UnansweredQuestion
has title: How can I make location not equal None
tagged with: python
has answer: http://stackoverflow.com/a/48615683
has answer: http://stackoverflow.com/a/48615061
has comment: http://stackoverflow.com/comment/84227239
has body: When I try to print or call location it says that it returns None. How can I make it so it returns the location of where I click? import turtle line = turtle.Turtle() def click_location(x,y): line.up() line.setpos(x,y) line.down() return line.pos() location = window.onclick(click_location)
score: 0
answer count: 2
type: Question

http://stackoverflow.com/comment/84209958
has text: Thank you @gissehel. This is what I am expecting "recreated_doc = ".".join(value for index, value in result)"
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48606839
score: 0

http://stackoverflow.com/comment/84060251
type: AnswerComment
comment on: http://stackoverflow.com/a/48532130
has text: 5000 should be no problem.
type: Comment
score: 0

http://stackoverflow.com/q/48613394
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48613500
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48613430
tagged with: pandas
has answer: http://stackoverflow.com/a/48613731
has answer: http://stackoverflow.com/a/48613430
has body: Consider the following dataframe: import pandas as pd from sklearn.preprocessing import LabelEncoder df = pd.DataFrame(data=[["France", "Italy", "Belgium"], ["Italy", "France", "Belgium"]], columns=["a", "b", "c"]) df = df.apply(LabelEncoder().fit_transform) print(df) It currently outputs: a b c 0 0 1 0 1 1 0 0 My goal is to make it output something like this by passing in the columns I want to share categorial values: a b c 0 0 1 2 1 1 0 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48613500
tagged with: scikit-learn
favorite count: 0
type: Question
score: 5
has title: Label encoding multiple columns with the same category
has answer: http://stackoverflow.com/a/50991057

http://stackoverflow.com/comment/84159447
type: Comment
type: AnswerComment
has text: @Basj, then just instead of writing the log at the start just log whenever the job is finished.
score: 1
comment on: http://stackoverflow.com/a/48580406

http://stackoverflow.com/q/48585318
type: Question
tagged with: numpy
type: UnansweredQuestion
has body: In my training data I have a Unix timestamp that I want to convert to hourOfDay and weekday. From that I want to predict users activity. I use BigQuery to get the data and some some calculations using numpy array in the input_fn. I think I need the session that the input_fn runs under to convert my Tensors to ndarrays. The predictions works and the model trains ok. Anyhow here is the code and the error message: def main(): export_dir = os.path.join(ROOT_DIR, MODEL_NAME) def input_fn_from_bigquery(): features_dict = dict( detectedActivity=tf.FixedLenFeature([1], tf.int64), time=tf.FixedLenFeature([1], dtype=tf.int64), ) training_dict = dict( hourOfDay=tf.FixedLenFeature([1], tf.int64,default_value=0), weekday=tf.FixedLenFeature([1], tf.int64, default_value=0), time=tf.FixedLenFeature([1], dtype=tf.int64) ) label_dict = dict( detectedActivity=tf.FixedLenFeature([1], tf.int64) ) # Create a Reader. reader = bigquery_reader_ops.BigQueryReader(project_id=PROJECT, dataset_id=DATASET, table_id=TABLE, timestamp_millis=TIME, num_partitions=NUM_PARTITIONS, features=features_dict) queue = tf.train.string_input_producer(reader.partitions()) row_id, examples_serialized = reader.read_up_to(queue, 50) features = tf.parse_example(examples_serialized, features=training_dict) labels = tf.parse_example(examples_serialized, features=label_dict) #get all times as numpy array and divide to correct timeformat timearray = (tf.scalar_mul(0.001, tf.cast(features["time"], tf.float32))).eval() hourarray = np.zeros(timearray.shape, dtype=np.int64) weekdayarray = np.zeros(timearray.shape, dtype=np.int64) for i in range(timearray.shape[0]): hourarray[i] = datetime.fromtimestamp(timearray[i]).hour # calculate hours weekdayarray[i] = datetime.fromtimestamp(timearray[i]).weekday() # calculate weekday features["hourOfDay"] = tf.convert_to_tensor(hourarray, np.int64) features["weekday"] = tf.convert_to_tensor(weekdayarray, np.int64) return features, labels["detectedActivity"] feature_columns = [tf.feat…
tagged with: multithreading
tagged with: python
downvote count: 0
answer count: 0
score: 1
upvote count: 1
has title: How to get explicit session for input_fn when training a TensorFlow model
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/48528190
has answer: http://stackoverflow.com/a/48528399
has title: Get dummies when some categories are not present in a pandas column
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/37425961
has comment: http://stackoverflow.com/comment/84053334
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/48528399
score: 4
duplicate of: http://stackoverflow.com/q/37425961
has body: Say I have a pandas column as below Type type1 type2 type3 and now i will take dummies for above as follows: type_dummies = pd.get_dummies(["Type"], prefix="type") Then after joing it with the main DataFrame the resulting df would be something like below: df.drop(['Type'], axis=1, inplace=True) df = df.join(type_dummies) df.head() type_type1 type_type2 type_type3 1 0 0 0 1 0 0 0 1 But what if in my training set there is an another category as type4 in Type column. So how would I use get_dummies() method to generate dummies as much as I want. That is, in this case I want to generate 4 dummy variables although there are only 3 categories in the desired column?
tagged with: data-processing
tagged with: data-science

http://stackoverflow.com/q/48564459
type: AnsweredQuestion
tagged with: python-import
answer count: 2
score: 1
possible better answer: http://stackoverflow.com/a/79168034
upvote count: 1
has answer: http://stackoverflow.com/a/79168034
tagged with: import
has body: Simple question really: I am build a standard repo for doing few simple machine learning tasks, and I almost always import the same dependencies in those .py modules. I was thinking that it would un-clutter my code a bit (and save time) if I could make a .py file that imported all my standard dependencies. This could then be expanded to different classes that depend on the model e.g. sklearn, xgboost, etc. 1) Is is advisable practise to call dependencies from a external function? 2) If so, how would this be done best? So far, I've tried the following: project_dependencies.py contains def get_dependencies(): import numpy as np if __name__ == "__main__": get_dependencies() and model.py might then contain from project_dependencies import get_dependencies get_dependencies() def model(): return np.random.normal(1) if __name__ == "__main__": model() But that does not seem to work. What would a good, long term solution to this be? Thanks!
favorite count: 0
type: Question
tagged with: python-3.x
has title: Using a seperate python function to import dependencies
accepted answer: http://stackoverflow.com/a/48564636
has answer: http://stackoverflow.com/a/48564636
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/84288113
type: QuestionComment
comment on: http://stackoverflow.com/q/48645477
has text: `dir(your_object)` should get you started.
score: 3
type: Comment

http://stackoverflow.com/comment/84288921
type: QuestionComment
has text: [Does this help?](https://stackoverflow.com/questions/773/how-do-i-use-pythons-itertools-groupby)
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48645730

http://stackoverflow.com/comment/134914272
comment on: http://stackoverflow.com/a/48574345
score: 0
has text: The answer is strange. If I want to store actual instance in node I cannot do it and need to covert it to the attributes and back?
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48553276
answer count: 2
downvote count: 0
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/48553614
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48553614
tagged with: pandas
tagged with: group-by
has body: i am willing too add a new column with three consecutives 1 whenever rap is equal to one. The three consecutive 1 must be in the same year when rap is equal one and the two before from that one. New columns must be by id (i have a data panel). df looks like this: id year rap cohort jobs year_of_life 1 2009 0 NaN 10 NaN 1 2012 0 2012 12 0 1 2013 0 2012 12 1 1 2014 0 2012 13 2 1 2015 1 2012 15 3 1 2016 0 2012 17 4 1 2017 0 2012 18 5 2 2009 0 2009 15 0 2 2010 0 2009 2 1 2 2011 0 2009 3 2 2 2012 1 2009 3 3 2 2013 0 2009 15 4 2 2014 0 2009 12 5 2 2015 0 2009 13 6 2 2016 0 2009 13 7 expected output: id year rap cohort jobs year_of_life rap_new 1 2009 0 NaN 10 NaN 0 1 2012 0 2012 12 0 0 1 2013 0 2012 12 1 1 1 2014 0 2012 13 2 1 1 2015 1 2012 15 3 1 1 2016 0 2012 17 4 0 1 2017 0 2012 18 5 0 2 2009 0 2009 15 0 0 2 2010 0 2009 2 1 1 2 2011 0 2009 3 2 1 2 2012 1 2009 3 3 1 2 2013 0 2009 15 4 0 2 2014 0 2009 12 5 0 2 2015 0 2009 13 6 0 2 2016 0 2009 13 7 0
tagged with: python
has answer: http://stackoverflow.com/a/48553379
accepted answer: http://stackoverflow.com/a/48553379
has title: transforming a column of a dataframe according to a condition
tagged with: python-3.x

http://stackoverflow.com/q/48531601
type: AnsweredQuestion
tagged with: int
tagged with: numbers
linked to: http://stackoverflow.com/q/14939953
score: 0
answer count: 1
upvote count: 1
tagged with: string
duplicate of: http://stackoverflow.com/q/14939953
has title: Adding a large number from a user in python
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48531647
has answer: http://stackoverflow.com/a/48531647
has body: def main(): number = input("enter large number:") number = int(number) result = 0 for i in number: result = result + i print("result is:",result) is giving me an error with the int,I'm not sure how to fix it. I need the user to type in a large number like 2541 and it needs to be separated like 2,5,4,1 and added to give me the result of 12 is not supposed to be just 4 number but needs to be a large number.
tagged with: python

finance
tags question: http://stackoverflow.com/q/48633250
type: Tag
tags question: http://stackoverflow.com/q/48530785
tag name: finance

http://stackoverflow.com/comment/84007676
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48501392
has text: @James, Thanks for your inputs. As suggested will check programmatic access

http://stackoverflow.com/comment/84058538
has text: @CarlosCordoba i still got the same problem after running conda update spyder, my spyder is currently at 3.2.6
comment on: http://stackoverflow.com/q/48516018
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48610574
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48610410
has body: r.content returns bytes. (In contrast, r.text returns a str. The requests module attempts to guess the correct decoding based on HTTP headers and decodes the bytes using that encoding for you. In the future maybe that is what you would want to use instead). If r.content contained bytes such as b'command\xc5\xabcor', then str(r.content) returns a str which begins with the characters b' and ends with a literal '. In [45]: str(b'command\xc5\xabcor') Out[45]: "b'command\\xc5\\xabcor'" You can use ast.literal_eval to recover the bytes: In [46]: ast.literal_eval(str(b'command\xc5\xabcor')) Out[46]: b'command\xc5\xabcor' You could then decode these bytes to a str. The URL you posted declares the content is UTF-8 encoded: &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; Assuming all the data you downloaded uses the same encoding, you could recover the content as a str by calling the bytes.decode('utf-8') method: In [47]: ast.literal_eval(str(b'command\xc5\xabcor')).decode('utf-8') Out[47]: 'commandūcor' import ast import requests r = requests.get("https://www.dizionario-latino.com/dizionario-latino-flessione.php?lemma=COMMANDUCOR100", verify = False) out = str(r.content) with open("test.html", 'w') as file: file.write(out) with open("test.html", 'r') as f_in, open("test-fixed.html", 'w') as f_out: broken_text = f_in.read() content = ast.literal_eval(broken_text) assert content == r.content text = content.decode('utf-8') f_out.write(text)
answers question: http://stackoverflow.com/q/48610410
type: Answer
score: 1

http://stackoverflow.com/q/48555290
tagged with: http://stackoverflow.com/tag/r
tagged with: deep-learning
has body: I have already performed the tensor flow installation with the following command: pip install --ignore-installed https://github.com/mind/wheels/releases/download/tf1.5-gpu-cuda91-nomkl/tensorflow-1.5.0-cp27-cp27mu-linux_x86_64.whl This is the latest tensorflow wheel catered for CUDA 9.1. (3x faster than CUDA 8.0) And I can call it successfully in my python code. How can I make the keras in R to call the tensorflow installed by python above? The reason I asked that because I the default installation method keras::install_keras(method="conda", tensorflow = "gpu") It failed to recognize the cuda-9.1 library. &gt; conv_base &lt;- keras::application_vgg16( + weights = "imagenet", + include_top = FALSE, + input_shape = c(150, 150, 3) + ) /home/ubuntu/anaconda2/envs/r-tensorflow/lib/python2.7/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Using TensorFlow backend. Error: ImportError: Traceback (most recent call last): File "/home/ubuntu/anaconda2/envs/r-tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/home/ubuntu/anaconda2/envs/r-tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/home/ubuntu/anaconda2/envs/r-tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory This is because R installation method calling for tensorflow version 1.5.0 that is still not catered for CUDA 9.1.
score: 12
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/48675539
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/48675539
favorite count: 0
has comment: http://stackoverflow.com/comment/84269679
type: Question
upvote count: 12
possible better answer: http://stackoverflow.com/a/48667606
tagged with: python
has answer: http://stackoverflow.com/a/48667606
has title: How to make keras in R use the tensorflow installed by Python

http://stackoverflow.com/q/48603739
has title: Checking to see if calendar has changed using google calendar API
has answer: http://stackoverflow.com/a/48609239
score: 0
tagged with: calendar
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/21301918
tagged with: flags
has body: I'm using the google calendar API (python) to do some calendar parsing, and I'm going to be running a script once an hour to download events for the next two weeks. I'm on a pretty old system which has a lot going on so I want to only pull when there has been data changed. Is there any flag within the api to check if there is a change since last read? Thanks for your time!
tagged with: google-calendar-api
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84112774
has text: Thank you for your answer. But as you can see in my added example, remembering all variables in imported module seems unrealistic. Maybe I can use a variable to record the result of locals() after importing, but it is a little troublesome to do that.
type: Comment
comment on: http://stackoverflow.com/a/48555188
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84045201
type: AnswerComment
has text: emcconville is correct, the problem is that your input file doesn't exist. This is only clear because in the comments above you mention that GS returns an error 'undefinedfilename' which you didn't mention anywhere else. If you ahev extra information, please share it!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48524302

http://stackoverflow.com/comment/84118368
comment on: http://stackoverflow.com/a/48560666
score: 0
has text: Yes, I am using Python 2.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48590628
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84183694
answers question: http://stackoverflow.com/q/48590488
upvote count: 10
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/84228599
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48590488
has body: There are many ways to do this. One way to do it would be the following: def like_function(x): group = "unknown" for key in product_map: if key in x: group = product_map[key] break return group df['company'] = df.comp.apply(like_function)

http://stackoverflow.com/q/48638595
has answer: http://stackoverflow.com/a/48638923
type: Question
tagged with: xpath
has title: Python: How to write to csv properly after using webdriver
has body: I used xpath helper to help me scrapping a table in a login website. Code: g=driver.find_element_by_xpath("//table[@id='DataGrid']/tbody").text print(g) The result looks like this, data type is "string": #@5@#*&( &*(%#IO !@%&*(O) 2018/02/02 206 MAZDA MAZDA 5 5660-ES 2006 01 1999 70000 white A 2018/02/02 210 BMW 330 9378-W6 2006 01 2996 80000 black C 2018/02/02 211 MITSUBISHI FORTIS ALK-3501 2015 04 1798 100000 white C+ I want to write this string into csv without the first three lines and use comma to separate them otherwise they will all combine together. Code here: if "#@5@#*&(" in g and "&*(%#IO" in g and "!@%&*(O)" in g: g=g.replace("#@5@#*&(", "") g=g.replace("&*(%#IO", "") g=g.replace("!@%&*(O)", "") g=g.replace(' ', ',') print(g) file_name="C:/Test.csv" with open(file_name,'a') as file: file.write(g+'\n') What bothered me is that I don't know how to delete the first three lines. I replace them with blank space, but they are still there, everytime when I write into csv, they all take place. Second is that, when I separate them with comma, there were some errors. Like Mazda 5, it should not be separated. Is there any good way to solve this problem? or should I just correct it in csv file? source code: 2018/02/02 206 MAZDA MAZDA 5 5660-ES 2006 01 1999 70000 white A
has answer: http://stackoverflow.com/a/48638947
tagged with: python
possible better answer: http://stackoverflow.com/a/48638923
tagged with: selenium-webdriver
accepted answer: http://stackoverflow.com/a/48638947
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: selenium
tagged with: webdriver

libspatialindex
type: Tag
tag name: libspatialindex
tags question: http://stackoverflow.com/q/48507359

http://stackoverflow.com/q/48584949
possible better answer: http://stackoverflow.com/a/64295468
has comment: http://stackoverflow.com/comment/84166687
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/64295468
upvote count: 1
has title: I am getting ImportError no module named pytube from python3
linked to: http://stackoverflow.com/q/20534556
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48585093
tagged with: pytube
has comment: http://stackoverflow.com/comment/84166729
has answer: http://stackoverflow.com/a/48585093
linked to: http://stackoverflow.com/q/11268501
tagged with: python
has body: I have installed pytube by following command sudo pip install pytube It's ok when I import pytube from python 2.x. But I am getting ImportError while importing from python3

http://stackoverflow.com/a/48596865
accepted answer of: http://stackoverflow.com/q/48596733
type: Answer
answers question: http://stackoverflow.com/q/48596733
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84190669
has body: First you cannot split, because values of Series are tuples and Nones It is a bit complicated, because Nones, so first remove them by dropna, use DataFrame contructor and last add NaNs by reindex: matching_results = pd.Series([None, ('Nokia X3', 62, 1293), None], index=[12,13,14]) print (matching_results) 12 None 13 (Nokia X3, 62, 1293) 14 None dtype: object new = matching_results.dropna() df = pd.DataFrame(new.values.tolist(), columns="Model Match_Score Id".split(), index=new.index).reindex(matching_results.index) print (df) Model Match_Score Id 12 NaN NaN NaN 13 Nokia X3 62.0 1293.0 14 NaN NaN NaN

http://stackoverflow.com/a/48591993
accepted answer of: http://stackoverflow.com/q/48590768
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/48590768
type: AcceptedAnswer
downvote count: 0
has body: After reading the logs it showed that there was an Error Code R13. I was able to follow this thread to get what I needed to be fixed but was unable to run anything that needs to actually be attached (like an interactive shell). Tried filing something with Heroku support but they basically said that it's outside the scope of free support. Disappointing.
score: 3

http://stackoverflow.com/q/48645349
answer count: 0
tagged with: celery
tagged with: python
has title: Group or Chain tasks from different REMOTE celery applications/workers
type: UnansweredQuestion
tagged with: celery-task
score: 3
upvote count: 3
downvote count: 0
has body: I want to experiment on grouping tasks from different celery applications, running on different/remote servers/machines. So for example, in application 1, running in server 1, I have this task: @app.task(name='func1', bind=True, queue='func1') def func1(self, args): ret = {"func1_status":"success"} return ret In application 2, running in server 2, I have this task: @app.task(name='func2', bind=True, queue='func2') def func2(self, args): ret = {"func2_status":"success"} return ret Now in application 3, running in server 3, I want to have a task that uses the 2 remote tasks ins a group: from celery import chain, group from celery.result import allow_join_result @app.task(name='func3', bind=True, queue='func3') def func3(self, args): ret = None res = group(func2.s(args), func1.s(args))() with allow_join_result(): ret = res.get() return ret Then I will just add/call a task, via func3, like this: res = func3.delay(args) So the above is what I wanted to do, but I don't know how can I import/call func1 and func2 tasks to be used, remotely, in the group for func3. Any ideas are greatly appreciated. Thanks in advance!
favorite count: 0
type: Question

http://stackoverflow.com/comment/84046519
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48525743
score: 1
has text: use threads or wxThread. don't do anything (especially long-running) on the main (GUI) thread.

http://stackoverflow.com/comment/84255903
type: Comment
comment on: http://stackoverflow.com/a/48618766
type: AnswerComment
score: 0
has text: @JohnBailey Please test your keys with the demo code.

http://stackoverflow.com/a/48587184
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48587076
has comment: http://stackoverflow.com/comment/84171969
has body: Assuming your series is called series and your dataframe is called df, the solution would be: pd.merge(df, pd.DataFrame(series), left_index=True, right_index=True) Edit: In looking a little more closely at your desired output, you may be looking for something more like: new_df = pd.concat((data, series), axis=0) new_df['%change'][len(df):] = new_df[new_df.columns.values[-1]][len(df):] new_df.drop(new_df.columns.values[-1], axis=1, inplace=True) This will give you the values of your series added as new rows to the '%change' column.
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48587076
upvote count: 2

http://stackoverflow.com/a/48542148
downvote count: 0
has comment: http://stackoverflow.com/comment/84090917
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84091494
has body: That doesn't work because image.plot apparently comes from the package fields. Using image from base R's graphics library, do e.g. this: import numpy as np from rpy2.robjects.packages import importr from rpy2.rinterface import RRuntimeError import rpy2.robjects.numpy2ri from IPython.display import Image, display from rpy2.robjects.lib import grdevices rpy2.robjects.numpy2ri.activate() grf = importr('graphics') a = np.array([1.5,2.3]) b = np.array([4.2,5.1]) c = np.array([[0.3, 0.6],[0.6, 0.3]]) with grdevices.render_to_bytesio(grdevices.png, width=1024, height=896, res=150) as img: grf.image(a, b, c) display(Image(data=img.getvalue(), format='png', embed=True)) gives To use image.plot, you'd have to run fields = importr('fields') and replace grf.image(a, b, c) with fields.image.plot(a, b, c)
has comment: http://stackoverflow.com/comment/84091013
has comment: http://stackoverflow.com/comment/84096387
has comment: http://stackoverflow.com/comment/84091317
has comment: http://stackoverflow.com/comment/84091582
accepted answer of: http://stackoverflow.com/q/48538314
type: Answer
answers question: http://stackoverflow.com/q/48538314
has comment: http://stackoverflow.com/comment/84091523
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/84096411
has comment: http://stackoverflow.com/comment/84097272

http://stackoverflow.com/q/48505979
accepted answer: http://stackoverflow.com/a/48506532
has comment: http://stackoverflow.com/comment/84006380
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84006253
tagged with: automated-tests
tagged with: python
has body: So I am trying to verify text is an element, basically I'm testing what happens when no search results are found. However I'm getting the following error message every time and I cannot figure out why. Traceback (most recent call last): File "test.py", line 40, in test_article_no_result_search assert article_results_page.is_articles_not_found(), "Articles found surprisingly." File "/Users/tester/Documents/Automated Tests/foobar/page.py", line 71, in is_articles_not_found return "No Results Available" in element.get_attribute("value") TypeError: argument of type 'NoneType' is not iterable HTML element I'm trying to verify No Results Available Here is my test case from test.py class SearchTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get(TestingURLS.URL) def test_article_no_result_search(self): main_page = MainPage(self.driver) main_page.load_page() main_page.click_article_search_input_clear() main_page.enter_no_result_search_term() main_page.click_article_search_button() article_results_page = ArticleResultsPage(self.driver) article_results_page.load_page() assert article_results_page.is_articles_not_found(), "Articles found surprisingly." def tearDown(self): self.driver.quit Relevant function in page.py def is_articles_not_found(self): element = self.driver.find_element(*SearchResultLocators.UPPER_RESULT_DISPLAY) return "No Results Available" in element.get_attribute("value") Relevant locator from locators.py class SearchResultLocators(object): UPPER_RESULT_DISPLAY = (By.CSS_SELECTOR, "div.simple-div.results-num-span") RESULT_COUNT = (By.CSS_SELECTOR, "div.num-shown") FIRST_ARTICLE_RESULT = (By.CSS_SELECTOR, "div.result")
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Trouble verifying text is present in a div with Selenium/Python
tagged with: selenium
has answer: http://stackoverflow.com/a/48506532

http://stackoverflow.com/a/48511481
upvote count: 3
answers question: http://stackoverflow.com/q/48511451
has comment: http://stackoverflow.com/comment/84017988
accepted answer of: http://stackoverflow.com/q/48511451
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: str.replace does not use regular expressions. You would have to use the re module for that. But since you are just replacing a comma by a comma and a space, you don’t actually need regular expressions here: s = '''SMITH,JOHN JONES,TOMMY etc.''' s = s.replace(',', ', ') print(s) # SMITH, JOHN # JONES, TOMMY # etc. I only need to replace the commas that are immediately preceded and proceeded by uppercase text characters. Then you might want to use regular expressions after all. You will have to use re.sub for this: import re s = 'FOO, SMITH,JOHN' s = re.sub('([A-Z]),([A-Z])', r'\1, \2', s) print(s) # FOO, SMITH, JOHN This uses references to put in those two characters around the comma. You can also use lookbehinds and lookaheads for this: s = 'FOO, SMITH,JOHN' s = re.sub('(?&lt;=[A-Z]),(?=[A-Z])', ', ', s) print(s) # FOO, SMITH, JOHN
score: 3

http://stackoverflow.com/a/48602263
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84217346
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84201426
has comment: http://stackoverflow.com/comment/84207509
answers question: http://stackoverflow.com/q/48595023
has comment: http://stackoverflow.com/comment/84217163
has body: The theoretical bounds are: Sorting: O(n log n) heap selection: O(n log k) quick select: O(n) One of the problems with your heap selection method is that you're creating a heap of the entire set of items. You really only need to create a heap of the first k items. The algorithm is: h = create a min heap of first k items // O(k) for each remaining item if item is larger than smallest item on heap remove smallest item from heap add new item to heap The worst case for that algorithm is O(n log k). The idea is that in the worst case you end up doing n insertions and n removals from a heap of size k. In the average case, the number of insertions and removals is quite a bit smaller. It depends on the relationship of k to n. If k is much smaller than n, this method can be very fast. In your code, you're creating a min-heap of the first k items, and then you have this loop: for number in numbers[k+1:]: my_heap.extract_min() my_heap.insert(number) That code will not reliably produce the correct result because you're unconditionally removing the minimum element. So if the heap already contains the top k elements, but you still have numbers left, it will replace a larger element by a smaller one. You need to modify your code: for number in numbers[k+1:]: if (number &lt; my_heap.get_min()) // get_min returns the minimum element, but doesn't remove it my_heap.extract_min() my_heap.insert(number) Not only will that give you the correct answer, it will reduce the number of insertions and removals you have to make in the average case, which will speed up your program. Your heap implementation also is non-optimum. You'll save considerable time making your heapify function iterative rather than recursive, and there are ample opportunities for you to optimize that function. As I mentioned above, quick select is an O(n) algorithm. In general, quick select is faster when k is more than about 2% of n. So if you're selecting 100 items from a list of 1,000, quick select will almost certain…
has comment: http://stackoverflow.com/comment/84201598
has comment: http://stackoverflow.com/comment/84202590
accepted answer of: http://stackoverflow.com/q/48595023

http://stackoverflow.com/comment/84272463
type: AnswerComment
comment on: http://stackoverflow.com/a/48633379
score: 0
type: Comment
has text: @kinderchan, the key to using `einsum` here is that it creates a `view`. Anything that can be done with a regular `view` (e.g. `x[1:10,:]`), should work with one produced by `einsum`. But you can test this yourself. Once you understand the pieces you can use them in various ways. (edit) `np.einsum('iii->i',A)[...] += 100` works

http://stackoverflow.com/a/48497557
type: Answer
score: 0
has body: First code snippet looks like an easy way to let client fetch calculations results. However, make_collection is a blocking one and Nginx will keep one of its workers busy with it. Since usual way of Nginx configuration is to have one worker per CPU core, that leaves you with one worker less each time you make a HTTP request to /paths. If there are multiple requests to /paths then is not surprise that you get a poor performance. Not to mention WSGI server that you probably have e.g. uwsgi, gunicorn, etc. and their workers and threads per worker process. Solution with threads might look like a good solution, but you can end up with a lot of threads. Pay attention to threads in Python and try to avoid CPU bound work from being delegated to threads in Python unless you really know what you are doing. In general you should try to avoid these blocking calls, like the one you make and offload them to a separate worker queue while keeping a reference for getting results later on.
answers question: http://stackoverflow.com/q/48496634

http://stackoverflow.com/a/48560304
has body: You can pass a pointer pointing to the image instead of the image or the filename of the image EDIT def image_function(imagePointer): #DO SOMETHING WITH THE IMAGE #HERE IS THE IMAGE POINTER image = open('your_image.png') #CALLING THE FUNCTION image_function(image) Sorry, I don't know opencv so I can not help in your code :(
answers question: http://stackoverflow.com/q/48560201
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48560201

http://stackoverflow.com/a/48588634
type: Answer
has body: Thank you for all the help! Solved the problem. It dealt with user input and the files that i read in. The files that i read in had a '\N' attached to it. Which is why i kept getting multiple errors and it was not searching the word.
score: 0
answers question: http://stackoverflow.com/q/48574363
has comment: http://stackoverflow.com/comment/84174466

http://stackoverflow.com/comment/84141905
comment on: http://stackoverflow.com/q/48568065
type: Comment
type: QuestionComment
score: 0
has text: Please refer to my updated code above.

http://stackoverflow.com/comment/84145425
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48574314
score: 0
has text: @juanpa.arrivillaga - this was unspecified in my reference - please see my edit for more context

http://stackoverflow.com/comment/84225296
comment on: http://stackoverflow.com/q/48614176
has text: Similarly cannot reproduce the error after correcting the original indentation.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84080902
has text: What did you try already?
type: QuestionComment
comment on: http://stackoverflow.com/q/48542940
score: 2
type: Comment

http://stackoverflow.com/comment/84176589
score: 0
comment on: http://stackoverflow.com/q/48585988
type: QuestionComment
has text: @Adam: thanks for the tip, I just not sure about my answer that's why its in the comment section. I didn't want to pollute the answer pool :)
type: Comment

http://stackoverflow.com/q/48603339
score: 12
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48603374
answer count: 3
has answer: http://stackoverflow.com/a/48603374
downvote count: 0
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48603451
tagged with: urllib
favorite count: 0
type: Question
has title: How to call JavaScript function using BeautifulSoup and Python
possible better answer: http://stackoverflow.com/a/60018939
upvote count: 12
has answer: http://stackoverflow.com/a/60018939
has body: I am performing web scraping to grab data from a website as part of my project. I can make the request and grab the data which is present in the dom. However, some data is getting rendered on javascript onClick function. One way could be, using the selenium to click on the link (which calls the javascript function) and grab the rendered data, but this process is time-consuming, and I don't want to open the browser. Is there any way other than selenium to achieve this? Website: http://catalog.fullerton.edu/preview_entity.php?catoid=16&amp;ent_oid=1849 In the courses section of this webpage, all the courses are hyperlinks, and as soon as someone clicks on the courses, a javascript method gets called. I need the data which gets rendered after the javascript function call.
tagged with: javascript
tagged with: python
linked to: http://stackoverflow.com/q/390992

http://stackoverflow.com/a/48779917
type: Answer
accepted answer of: http://stackoverflow.com/q/48612105
score: 0
answers question: http://stackoverflow.com/q/48612105
type: AcceptedAnswer
has body: I have solved it. It was due to miscoding. The code was not in the right place. Thanks.

http://stackoverflow.com/q/48595039
has body: I'd like to print any number that appears more than once. How do I change my for loops into list comprehensions? from collections import Counter cnt=Counter() in1="4 8 0 3 4 2 0 3".split(" ") for elt in in1: cnt[elt]+=1 more_than_one=[] for value, amount in cnt.items(): if amount &gt; 1: more_than_one.append(value) print(*more_than_one) Desirable output: 4 0 3
type: AnsweredQuestion
has title: For loops into List comprehensions
score: 1
has answer: http://stackoverflow.com/a/48595128
accepted answer: http://stackoverflow.com/a/48595058
possible better answer: http://stackoverflow.com/a/48595128
tagged with: loops
favorite count: 0
type: Question
answer count: 2
upvote count: 5
has answer: http://stackoverflow.com/a/48595058
tagged with: python
downvote count: 4

http://stackoverflow.com/q/48533033
tagged with: anaconda
has title: Can't install anything with Conda
has comment: http://stackoverflow.com/comment/84065248
upvote count: 3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84064068
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84086375
has answer: http://stackoverflow.com/a/54632061
type: UnansweredQuestion
tagged with: python
has body: I keep getting the following error when I try to install or update modules with Conda. Any help? I install using the following commands (basically any installation or upgrade command): conda install tensorflow conda install numpy And this is the error message: Fetching package metadata ... CondaHTTPError: HTTP 000 CONNECTION FAILED for url Elapsed: - An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way. ConnectionError(MaxRetryError("HTTPSConnectionPool(host='pypi.python.org', port= 443): Max retries exceeded with url: /simple/win-64/repodata.json (Caused by New ConnectionError(': Failed to establish a new connection: [Errno 11004] getaddrinfo fail ed',))",),) Also pip is not able to install any modules either. It keeps saying: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection : [Errno 11004] getaddrinfo failed',)': /simple/tensorflow/
has comment: http://stackoverflow.com/comment/84075692
has comment: http://stackoverflow.com/comment/84061815
tagged with: conda
score: 3
linked to: http://stackoverflow.com/q/54612022

http://stackoverflow.com/q/48512695
tagged with: python
has title: Using Pybluez to connect to already paired bluetooth device?
tagged with: pybluez
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/67731835
favorite count: 0
tagged with: bluetooth
type: Question
has body: I am writing a python program that involves using a bluetooth device.Right now I'm able to connect to the bluetooth device from the python program but everytime I quit the python program I have to bring my device pack to pairing mode (by pulling a switch) and then pair with it again. I was hoping if you could show any method through which I could connect automatically to the paired device , instead of bringing it to pairing mode and connecting again for each time I run the python program. This is the code to my bluetooth python module : import bluetooth from bluetooth.btcommon import BluetoothError import time class DeviceConnector: TARGET_NAME = "Device name" TARGET_ADDRESS = None SOCKET = None def __init__(self): pass def getConnectionInstance(self): self.deviceDiscovery() if(DeviceConnector.TARGET_ADDRESS is not None): print('Device found!') self.connect_bluetooth_addr() return DeviceConnector.SOCKET else: print('Could not find target bluetooth device nearby') def deviceDiscovery(self): try: nearby_devices = bluetooth.discover_devices(lookup_names = True, duration=5) while nearby_devices.__len__() == 0 and tries &lt; 3: nearby_devices = bluetooth.discover_devices(lookup_names = True, duration=5) tries += 1 time.sleep (200.0 / 1000.0) print ('couldnt connect! trying again...') for bdaddr, name in nearby_devices: if bdaddr and name == DeviceConnector.TARGET_NAME: DeviceConnector.TARGET_ADDRESS = bdaddr DeviceConnector.TARGET_NAME = name except BluetoothError as e: print ('bluetooth is off') def connect_bluetooth_addr(self): for i in range(1,5): time.sleep(1) sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) try: sock.connect((DeviceConnector.TARGET_ADDRESS, 1)) sock.setblocking(False) DeviceConnector.SOCKET = sock return except BluetoothError as e: print('Could not connect to the device') return None Thank you :)
score: 1

http://stackoverflow.com/comment/84038855
score: 0
type: Comment
type: QuestionComment
has text: Did you check this page? https://developer.twitter.com/en/docs/basics/rate-limiting.html
comment on: http://stackoverflow.com/q/48521587

http://stackoverflow.com/a/48597062
type: Answer
answers question: http://stackoverflow.com/q/48596929
has body: I think you need concat with parameter axis=1 for concatenate along columns and select by xs second level of MultiIndex in columns: df = pd.concat(f, axis=1).xs('close', axis=1, level=1) print (df) BP CVX date 2017-01-03 38.00 117.85 2017-01-04 38.29 117.82 2017-01-05 38.57 117.31 2017-01-06 37.91 116.84 2017-01-09 37.31 115.84 2017-01-10 37.11 NaN 2017-01-11 37.55 NaN 2017-01-12 37.76 NaN Or concatenate along indices, but get MultiIndex in indices: df = pd.concat(f)['close'] print (df) date BP 2017-01-03 38.00 2017-01-04 38.29 2017-01-05 38.57 2017-01-06 37.91 2017-01-09 37.31 2017-01-10 37.11 2017-01-11 37.55 2017-01-12 37.76 CVX 2017-01-03 117.85 2017-01-04 117.82 2017-01-05 117.31 2017-01-06 116.84 2017-01-09 115.84 Name: close, dtype: float64
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/48596929

mouse
tags question: http://stackoverflow.com/q/48532625
type: Tag
tags question: http://stackoverflow.com/q/48554151
tag name: mouse

http://stackoverflow.com/q/48604921
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: Override Django Handler404 with JSON type handler
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has body: I'm using Django 2.0.1 and I'm trying to override Django 404 page with another response. Instead of returning a regular template, I want to return a JSON response. here is my project/urls.py from django.conf.urls import include from django.contrib import admin from django.urls import path from django.conf.urls import handler404 from django.http import JsonResponse urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('accounts.urls')) ] def response404(request, status=200, message='Not Found', data=None): data = {'status': 404, 'message': message, 'data': data} return JsonResponse(data=data, status=status) def response500(request, status=500, message='Not Found', data=None): data = {'status': status, 'message': message, 'data': data} return JsonResponse(data=data, status=status) handler404 = response404 handler500 = response505 and in accounts/urls/py from django.urls import path from .views import UserView, AuthenticationView urlpatterns = [ path('', UserView.as_view()), path('auth/', AuthenticationView.as_view()), ] but by it 404 returns it still return me the basic Django 404 page even if I change Debug option to True in settings.py file
tagged with: django
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48605025
has answer: http://stackoverflow.com/a/78719384
type: UnansweredQuestion

http://stackoverflow.com/comment/84089855
type: Comment
type: QuestionComment
has text: that's why I propose you to replace duplicated element by NaN for example
score: 0
comment on: http://stackoverflow.com/q/48546353

http://stackoverflow.com/q/48604004
score: -2
tagged with: python
upvote count: 0
tagged with: weka
downvote count: 2
type: UnansweredQuestion
has body: I have this dataset, and I'm using SKlearn to generate a random forest model as follows: from sklearn.ensemble import RandomForestClassifier as RandomForest from sklearn.cross_validation import cross_val_score, cross_val_predict import pandas as pd import numpy as np df = pd.read_csv('trainingSetExample.csv') X_train = df.iloc[:, df.columns != 'label'] y_train = df.ix[:]['label'] clf = RandomForest() print np.mean(cross_val_score(clf, X_train, y_train, cv=10)) print 'precision', np.mean(cross_val_score(clf, X_train, y_train, cv=10, scoring='precision_macro')) Accuracy and precision are both 0.99, but when I use WEKA random-forest, accuracy and precision are both 0.95. It looks like the default values of the parameters for both is the same, in addition, I tried WEKA with 10000 iterations instead of 100 and it didn't improve. Why are the results that much different?
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/84205611
has title: Why SKlearn and WEKA results do not match?
favorite count: 0
has answer: http://stackoverflow.com/a/48621144
type: Question
tagged with: random-forest

http://stackoverflow.com/q/48518179
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: django
has body: To make part of the django-tables2 API usable in templates, I want to define a property on a class that translates the attribute name to an argument to another method. The current implementation looks (vaguely) like this: class Row(object): _cells = {'first_name': 'James', 'last_name': 'Charland'} def get_cell(self, name): return self._cells[name] This makes it impossible to access a specific cell from a django template, because django templates do not allow passing arguments to functions. I want to support something like row.cell.first_name, which would be easy if the internal structure contained a dict _cells. In reality, the implementation is a bit more complex (getting the value involves calling a function). Computing a dict for all possible cells is not desirable either because it might involve doing unnecessary work. My naive solution looks like this: class Row(object): _cells = {'first_name': 'James', 'last_name': 'Charland'} def get_cell(self, name): return self._cells[name] @property def cell(self): class CellReader(object): def __init__(self, row): self.row = row def __getattr__(self, name): return self.row.get_cell(name) return CellReader(self) Which works and doesn't use too much code, but it feels a bit verbose. Is there something in the standard library I did not think of to implement this functionality in a more concise way?
type: Question
score: 2
tagged with: python
has title: Property allowing attribute access
favorite count: 0
has comment: http://stackoverflow.com/comment/84033649
upvote count: 2

http://stackoverflow.com/comment/84053299
type: AnswerComment
comment on: http://stackoverflow.com/a/48528492
has text: The benchmarks seem like a mission for [perfplot](https://github.com/nschloe/perfplot).
score: 1
type: Comment

http://stackoverflow.com/comment/84074916
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48519308
has text: thanks @eyllanesc. I found that I have set QSortFilterModel too. I will try to create a custom Proxymodel to filter and set font color.
score: 0

http://stackoverflow.com/q/48610611
tagged with: cron
upvote count: 1
score: 1
tagged with: python
has title: Sklearn import issue with cron
favorite count: 0
type: Question
has body: I have a python script that use sklearn package. It runs fine when I launch it from terminal But when I try to run this script in a cron job, it faills ! It seems that import faills from sklearn.neural_network import MLPRegressor from sklearn.externals import joblib How can I solve this issue ?
answer count: 0
type: UnansweredQuestion
tagged with: scikit-learn
downvote count: 0

http://stackoverflow.com/comment/84251861
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48624104
type: QuestionComment
has text: Do you want to zoom?

http://stackoverflow.com/comment/84241888
has text: No, it won't. 8.1 < 9.1. You need a later client version. What's the idea of using a prehistoric version like that? You're playing with the life of your data.
comment on: http://stackoverflow.com/a/48617760
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48572925
has body: I have 2 models venta and detalleventa which is fine since a sale can have many details class Venta(models.Model): cliente = models.ForeignKey(Cliente,on_delete=models.CASCADE,verbose_name='Cliente') fecha = models.DateField(auto_now_add=True) descripcion = models.CharField(max_length=300, blank=True, verbose_name='Detalle del pedido') total = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Total de la venta') def __str__(self): return '{}'.format(self.id) class DetalleVenta(models.Model): producto = models.ForeignKey(Producto,on_delete=models.CASCADE,verbose_name='Producto') cantidad = models.IntegerField(verbose_name='Cantidad') venta = models.ForeignKey(Venta,on_delete=models.CASCADE, verbose_name='Venta') def __str__(self): return '{} - {}'.format(self.venta,self.producto) How do I access detail from venta if the foreign key has detalle? because if there are several detalles you should not edit one by one if you do not edit the venta that contains all the detalles So far I can edit but through its detalle: class VentaUpdate(UpdateView): model = DetalleVenta second_model = Venta template_name = 'venta/venta_form.html' form_class = DetalleForm second_form_class = VentaForm success_url = reverse_lazy('venta:ventas_listar') def get_context_data(self, **kwargs): context = super(VentaUpdate, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) detalle = self.model.objects.get(id=pk) venta = self.second_model.objects.get(id=detalle.venta_id) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in context: context['form2'] = self.second_form_class(instance=venta) context['id'] = pk return context def post(self, request, *args, **kwargs): self.object = self.get_object id_detalle = kwargs['pk'] detalle = self.model.objects.get(id=id_detalle) venta = self.second_model.objects.get(id=detalle.venta_id) form = self.form_class(request.POST, instance=detalle) form2 = self.second_form_class(request.POST, instance=venta) if form…
has comment: http://stackoverflow.com/comment/84164285
has comment: http://stackoverflow.com/comment/84164585
has comment: http://stackoverflow.com/comment/84164751
has comment: http://stackoverflow.com/comment/84167453
has comment: http://stackoverflow.com/comment/84152304
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/84164868
has comment: http://stackoverflow.com/comment/84165053
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84167257
tagged with: django
has comment: http://stackoverflow.com/comment/84167386
has title: Relationships between models (Django)
has comment: http://stackoverflow.com/comment/84165951
score: 0
has comment: http://stackoverflow.com/comment/84164389
has comment: http://stackoverflow.com/comment/84166419

http://stackoverflow.com/q/48535757
score: 0
answer count: 2
has body: I am using mysql 5.7.21, Connector/Python 2.0.4, Python 3.6.3 I defined a table in my python script, TABLES['report'] = ( "CREATE TABLE `report` (" " `t` varchar(4) NOT NULL," " `s` varchar(50) NOT NULL," " `d` varchar(10) NOT NULL," " `v` int(12) NOT NULL," " `g` varchar(12) NOT NULL," " `q` varchar(12) NOT NULL," " PRIMARY KEY (`t`)" ") ENGINE=InnoDB") and have created it successfully in the db. But, when I tried to insert the following data data= ('1111', 'xxxxxxxxxx-cc', 'AsOf20170630', '81785000', 'xxxx-cc', '2017Q2') into table with cursor.execute("INSERT INTO report (t, s, d, v, g, q) VALUES (%s, %s, %s, %s, %s, $s)", data) I got an error, ProgrammingError: Not all parameters were used in the SQL statement
tagged with: mysql
has title: Python/mySQL : ProgrammingError: Not all parameters were used in the SQL statement
tagged with: mysql-connector-python
type: Question
has answer: http://stackoverflow.com/a/48535892
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84066833
has comment: http://stackoverflow.com/comment/84110601
has answer: http://stackoverflow.com/a/48536658
tagged with: python

decode
tag name: decode
tags question: http://stackoverflow.com/q/48536461
type: Tag
tags question: http://stackoverflow.com/q/48507025

http://stackoverflow.com/comment/84062979
type: AnswerComment
comment on: http://stackoverflow.com/a/48533556
has text: You can use `random.choice(string.ascii_lowercase)` instead of hardcoding all alphabets.
score: 1
type: Comment

http://stackoverflow.com/comment/84223684
comment on: http://stackoverflow.com/q/48613381
score: 0
has text: CPU is at almost 0, but appears to be going up by about 0.1% every time I call a command, or every 10 seconds. But after a time it evens out at around 6.8%. Memory is constant at 1.2%... All data from a RPi 3 B
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48624524
has body: Using a Lock may help with synchronisation: import multiprocessing def p_get_reading(newport, N, interval, lock, return_dict): lock.acquire() lock.release() reading = newport.get_reading(N, interval) return_dict['power_meter'] = reading def p_capture(camera, N, lock, return_dict): lock.acquire() lock.release() img = camera.capture(N) return_dict['image'] = img if __name__ == "__main__": for i in range(10): manager = multiprocessing.Manager() return_dict = manager.dict() lock = multiprocessing.Lock() lock.acquire() p = multiprocessing.Process(target=p_capture, args=(camera,10,lock,return_dict)) p.start() p2 = multiprocessing.Process(target=p_get_reading, args=(newport,100,1,lock,return_dict)) p2.start() lock.release() p.join() p2.join() print(return_dict) The two Process objects can now be created and start()ed in any order as the main routine has already acquired the lock. Once released, the two processes will fight between themselves to acquire and release the lock, and be ready almost at the same time. Also, note the use of if __name__ == "__main__" as this helps when multiprocessing makes new processes. I must say this seems like an abuse of a Lock
answers question: http://stackoverflow.com/q/48623544
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/48612031
type: Answer
answers question: http://stackoverflow.com/q/48606817
score: 14
upvote count: 14
type: AcceptedAnswer
downvote count: 0
has body: A socket.io server can only communicate with a socket.io client. It cannot communicate with a plain webSocket client. Socket.io adds it's own data format and connection scheme on top of webSocket and its server expects that data format and connection scheme to be there in order to even allow an initial connection. So, you can't use a webSocket client to connect to a socket.io server. Your options here are to either get a socket.io client library for Python or change your server to just a plain webSocket server.
has comment: http://stackoverflow.com/comment/89093682
accepted answer of: http://stackoverflow.com/q/48606817

http://stackoverflow.com/q/48529524
favorite count: 0
has comment: http://stackoverflow.com/comment/84132727
has answer: http://stackoverflow.com/a/48645723
has comment: http://stackoverflow.com/comment/84055695
has title: Error when trying to update_index with an ElasticSearch backend
tagged with: elasticsearch
tagged with: python
type: Question
score: 2
has body: I have a Django environment set up to use ElasticSearch as the backend for our CMS, which is in Wagtail. I installed a recent version of ES (5.6.5 according to the service when I CURL it), and have my settings file using 'wagtail.wagtailsearch.backends.elasticsearch5' as the 'BACKEND' for WAGTAILSEARCH_BACKENDS. Wagtail is on version 1.13.1 according to my pip freeze, and the elasticsearch Python package is at 5.5.2. This all seems right per my reading of http://docs.wagtail.io/en/v1.13.1/topics/search/backends.html. The problem I am having is that when I try to do a './manage.py update_index', it gives me the following error: $ ./manage.py update_index Updating backend: default default: Rebuilding index wagtail__wagtailcore_page Traceback (most recent call last): File "manage.py", line 17, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailsearch/management/commands/update_index.py", line 120, in handle self.update_backend(backend_name, schema_only=options.get('schema_only', False)) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailsearch/management/commands/update_index.py", line 77, in update_backend index.add_model(model) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtail…
upvote count: 2
tagged with: wagtail
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84056106
answer count: 1
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/83998164
comment on: http://stackoverflow.com/q/48502286
has text: Ok maybe i missed a point. a.py is started before b.py and is still running because of the while loop and then b.py is executed.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48522997
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84040510
has answer: http://stackoverflow.com/a/48523087
answer count: 3
tagged with: argparse
accepted answer: http://stackoverflow.com/a/48524828
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48524828
type: Question
has answer: http://stackoverflow.com/a/56474100
tagged with: pycharm
upvote count: 0
has body: Here's my code: def parse_args(): parser = argparse.ArgumentParser(description='Simple training script for object detection from a CSV file.') parser.add_argument('csv_path', help='Path to CSV file') parser.add_argument('--weights', help='Weights to use for initialization (defaults to ImageNet).', default='imagenet') parser.add_argument('--batch-size', help='Size of the batches.', default=1, type=int) return parser.parse_args() when I run my code, I get an error: usage: Train.py [-h] [--weights WEIGHTS] [--batch-size BATCH_SIZE] csv_path Train.py: error: too few arguments Any idea where I'm going wrong?
has title: Python argparse: Too few arguments
downvote count: 1
has comment: http://stackoverflow.com/comment/84056397
favorite count: 0
possible better answer: http://stackoverflow.com/a/48523087
linked to: http://stackoverflow.com/q/33102272

http://stackoverflow.com/comment/84170627
comment on: http://stackoverflow.com/q/48586022
type: Comment
type: QuestionComment
has text: @KRKirov also in case of instantiating what will be the CV ? Is it the same as n_splits now ?
score: 0

http://stackoverflow.com/q/48630276
type: UnansweredQuestion
tagged with: python
has body: I'm trying to set up Django. I have Python 3.6 installed, and I installed virtualenvwrapper using pip3. Here is what my bash profile looks like: # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi export PATH="$PATH:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenv" export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 export PROJECT_HOME=$HOME/Devel source /Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenvwrapper.sh Every time I run $ mkvirtualenv my_django_env I get ERROR: virtualenvwrapper could not find virtualenv in your path
linked to: http://stackoverflow.com/q/31274642
tagged with: bash
tagged with: django
has comment: http://stackoverflow.com/comment/84258018
has comment: http://stackoverflow.com/comment/84258485
score: 1
has comment: http://stackoverflow.com/comment/84257912
has answer: http://stackoverflow.com/a/61327680
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Can't find virtualenv in path even though its there
has comment: http://stackoverflow.com/comment/84257574
has comment: http://stackoverflow.com/comment/84257826

http://stackoverflow.com/a/48603499
type: Answer
has comment: http://stackoverflow.com/comment/84203718
score: 2
has body: Here is one way via df.apply: def set_owner(order_id): min_idx = df['count'].idxmin() df.loc[min_idx, 'count'] += 1 return df.loc[min_idx, 'Id'] orders['newowner'] = orders['order_id'].apply(set_owner) orders # order_id newowner # 0 a1 a # 1 a2 a # 2 a3 b # 3 a4 a # 4 a5 b # 5 a6 a # 6 a7 b # 7 a8 c # 8 a9 a # 9 a10 b # 10 a11 c # 11 a12 d # 12 a13 a df # Id count # 0 a 8 # 1 b 7 # 2 c 7 # 3 d 7 # 4 e 8 # 5 f 9 # 6 g 12 # 7 h 13 # 8 i 15 # 9 j 55
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48601406
has comment: http://stackoverflow.com/comment/84203698
has comment: http://stackoverflow.com/comment/84204066
answers question: http://stackoverflow.com/q/48601406

http://stackoverflow.com/comment/84019864
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48512045
score: 0
has text: Updated description.

http://stackoverflow.com/a/52968578
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48493192
type: Answer
has body: In case you are still getting errors with the above solutions just make sure that the shapely wheel you are downloading (here) is the correct one and matching your system's requirements. Make sure you choose the correct 32 bit or 64 bit that also matches the python version (cp37 is for python 3.7). After downloading the file and moving it to your Python directory, run the administrative cmd on Python directory and run: py -3.7 -m pip install Shapely-1.6.4.post1-cp37-cp37m-win_amd64.whl (Shapely-1.6.4.post1-cp37-cp37m-win_amd64.whl is the name of the wheel you decide to download)

http://stackoverflow.com/comment/84035758
comment on: http://stackoverflow.com/a/48520069
score: 0
type: Comment
type: AnswerComment
has text: The second line works fine. I think the lambda is slightly better in this case. The last row does not work. It returns all the rows.

http://stackoverflow.com/comment/84042400
has text: It might have to do with how `.apply` works. It has to infer the shape of the output data and map it to the input DataFrame shape. The example that toto_tico did was a pretty simple one so it didn't have trouble guessing the shape. Check out this Pandas issue https://github.com/pandas-dev/pandas/issues/15628
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48523392

http://stackoverflow.com/q/48608576
tagged with: python
tagged with: kivy
type: Question
has title: Python requests module error, 'temporary failure in name resolution' in kivy Android app
upvote count: 3
type: UnansweredQuestion
has body: Built with buildozer using: Python 2.7.12 Kivy 1.10.0 Cython 0.25.2 My app is a simple test app that continuously checks an API I created with AWS API-Gateway/lambda for a changes in a returned value and alerts me. The program runs fine with kivy on my ubuntu and mac desktops, I can hit the API no problem, but once the apk is built and put on my phone it doesn't work correctly and dies as soon as I hit a button to trigger the api checks. I've tested on 2 phones, Android 6 and 7. Example of the check, I'm not doing anything crazy, and as I said it works from my desktop machine. (I've scrambled the API address below) api = 'https://34kjh545df.execute-api.us-east-1.amazonaws.com/test/dar_status' getApi = requests.get(darUI.api) check = getApi.text return check Using adb logcat I've grabbed the log output from when I press the button. This is the line saying there is a DNS issue, but I can hit the API fine on my phone in the browser. 02-04 10:31:32.995 14079 14094 I python : requests.exceptions.ConnectionError: HTTPSConnectionPool(host='34kjh545df.execute-api.us-east-1.amazonaws.com', port=443): Max retries exceeded with url: /test/dar_status (Caused by NewConnectionError('&lt;requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0xdeb44ff0&gt;: Failed to establish a new connection: [Errno 2] temporary failure in name resolution.',)) The rest of the log around that period. 02-04 10:31:32.987 14079 14094 I python : File "/work/dar/.buildozer/android/app/main.py", line 96, in my_callback 02-04 10:31:32.988 14079 14094 I python : File "/work/dar/.buildozer/android/app/main.py", line 79, in api_check 02-04 10:31:32.988 14079 14094 I python : File "/work/dar/.buildozer/android/platform/build/dists/testApp/private/lib/python2.7/site-packages/requests/api.py", line 70, in get 02-04 10:31:32.988 14079 14094 I python : File "/work/dar/.buildozer/android/platform/build/dists/testApp/private/lib/python2.7/site-packages/requests/api.py", line 56, in request 02-04 1…
answer count: 1
downvote count: 0
tagged with: aws-api-gateway
tagged with: amazon-web-services
favorite count: 0
has answer: http://stackoverflow.com/a/48622029
tagged with: android
score: 3

http://stackoverflow.com/comment/84219522
score: 0
has text: expected result is 'eo'
type: Comment
comment on: http://stackoverflow.com/q/48611525
type: QuestionComment

http://stackoverflow.com/comment/84275182
has text: @SyedElec Thanks for the added details. Please see my [other answer](https://stackoverflow.com/a/48639406/1639625) then. Hope it helps.
score: 0
comment on: http://stackoverflow.com/a/48619647
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/112040663
has text: @GaneshKathiresan , I know this is pretty old at this point, but curious what meta data you ended up using. I'd ideally like to identify if a video's channel is an 'Official Artist Channel' from the api results, been looking and can't find a good way to do it
comment on: http://stackoverflow.com/q/48605643
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48662686
type: Answer
score: 95
has comment: http://stackoverflow.com/comment/128514336
has comment: http://stackoverflow.com/comment/105372599
downvote count: 0
has comment: http://stackoverflow.com/comment/120863614
upvote count: 95
answers question: http://stackoverflow.com/q/48629486
has body: I accepted the answer above but I post here what I did step by step for complete beginners like me who easily get lost. Before I begin I post my complete test1.py example script with all the modules I actually need. My apologies if it is a bit more complex than the original question but maybe this can help someone. test1.py looks like this: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.image as image import numpy as np import os.path import pandas as pd import re from matplotlib.ticker import AutoMinorLocator from netCDF4 import Dataset from time import time from scipy.spatial import distance from simpledbf import Dbf5 from sys import argv print('Hello World') I added matplotlib.use('Agg') (as my actual code is creating figures) Generating a PNG with matplotlib when DISPLAY is undefined 1) Install a new version of python independently from anaconda. downloaded python from: https://www.python.org/downloads/ installed selecting 'add python to path' and deselecting install launcher for all users (I don't have admin rights) check that I am using the same version from CMD, just writing python I get: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. 2) Create and activate the environment, from CMD D:\> mkdir py36envtest ... D:\py36envtest>python -m venv venv_py36 ... D:\py36envtest\venv_py36\Scripts>activate.bat 3) Install in the environment all the modules needed in the script Making sure they are compatible to the python version with the command: (from Matplotlib not recognized as a module when importing in Python) (venv_py36) D:\py36envtest> python -m pip install nameofmodule NB: in my case I also had to add the option --proxy https://00.000.000.00:0000 for the example I used development version of py installer: (venv_py36) D:\py36envtest> python -m pip install https://github.com/pyinstaller/pyinstaller/archive/devel…

http://stackoverflow.com/a/48530073
answers question: http://stackoverflow.com/q/48529957
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: The problem You need to change list_bto: list_b = [['name2', 2], ['name4', 4], ['name4', 1], ['name4', 6], ['name2', 6]] Now: &gt;&gt;&gt; data_sums(list_b) [['name2', 8], ['name4', 11]] because in this loop: for name, value in matrix: conceptionally this happens: name, value = ['name2', 2] name, value = ['name4', 4] ... This is called unpacking. For your list_b this happens: name, value = 'name2' which throws this error: ValueError: too many values to unpack (expected 2) because there is only one value at the right hand side but Python needs two. Alternative Solution You can start with flat list and just zip each second element together by starting a zero and one: flat_list = ['name2', 2, 'name4', 4, 'name4', 1, 'name4', 6, 'name2', 6] sums = defaultdict(int) for name, value in zip(flat_list[::2], flat_list[1::2]): sums[name] += value result = [[k,v] for k,v in sums.items()] and result is: [['name2', 8], ['name4', 11]]

http://stackoverflow.com/q/48533983
tagged with: flask
has comment: http://stackoverflow.com/comment/84087481
score: 3
has body: I'm trying to write my setup.py to install a Flask application with pip. I have a large number of non-Python files to install as package data, e.g. static assets. I need to recursively include these files as there's many nested subdirectories, e.g. in bootstrap/ in the below example: myproject ├── MANIFEST.in ├── setup.py └── myproject/ └── app/ ├── __init__.py ├── static/ | ├── bootstrap/ (*) | | └── ... | ├── some.json | └── other.json └── templates/ └── index.html It seems like there's primarily 2 ways to do this, however I couldn't get either approach to work. Method 1: Use MANIFEST.in and include_package_data=True # setup.py setup_info = dict( ... include_package_data=True, #package_data={}, ... ) and the following in MANIFEST.in: recursive-include myproject *.json *.html followed by pip install . from my project root. This method doesn't install any package data files at all. In fact it seems to be ignoring my MANIFEST.in as I tried graft, exclude etc. and they don't seem to have an effect. Method 2: Use package_data with a custom recursive find function # setup.py EXTENSIONS = ['*.js', '*.html'] def recursive_get_package_data(): matches = [] THIS_FILE_DIR = os.path.dirname(os.path.realpath(__file__)) for ext in EXTENSIONS: for root, dirnames, filenames in os.walk(THIS_FILE_DIR): for filename in fnmatch.filter(filenames, ext): matches.append(os.path.join(os.path.relpath(root, THIS_FILE_DIR), filename)) return matches setup_info = dict( ... #include_package_data=False, package_data = {'': recursive_get_package_data()}, ... } setup(**setup_info) followed by followed by pip install . from my project root. This method doesn't install any package data files at all. However, if instead of using the explicit relative paths from recursive_get_package_data(), I use a list of the extension globs, i.e. setup_info = dict( ... #include_package_data=False, package_data = {'': EXTENSIONS}, ... ) it's able to install only .js and .html files where I have __init__.py. What am …
has comment: http://stackoverflow.com/comment/84087523
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/84111885
tagged with: setuptools
has comment: http://stackoverflow.com/comment/84107073
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84110553
type: Question
has comment: http://stackoverflow.com/comment/84069750
has comment: http://stackoverflow.com/comment/84087843
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84065295
has title: Installing with pip: Recursively adding files in directory as package data
tagged with: pip
tagged with: python

http://stackoverflow.com/comment/84027588
comment on: http://stackoverflow.com/q/48515006
score: 2
has text: To add to @jordanms answer try running 16 instances of your code on at the same time on each machine. Then you might see a time difference.
type: Comment
type: QuestionComment

authentication
tags question: http://stackoverflow.com/q/48625138
tags question: http://stackoverflow.com/q/48636305
tags question: http://stackoverflow.com/q/48605974
tags question: http://stackoverflow.com/q/48591708
tags question: http://stackoverflow.com/q/48570320
tags question: http://stackoverflow.com/q/48560539
tag name: authentication
tags question: http://stackoverflow.com/q/48550545
type: Tag
tags question: http://stackoverflow.com/q/48611992
tags question: http://stackoverflow.com/q/48631901
tags question: http://stackoverflow.com/q/48628886
tags question: http://stackoverflow.com/q/48527260

http://stackoverflow.com/comment/84252932
comment on: http://stackoverflow.com/a/48627900
has text: Great! That's much faster. I'll wait a tiny bit to see whether there are any pandas solutions (just out of interest), but otherwise I'll accept this for sure. Thanks!
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/48804725
answers question: http://stackoverflow.com/q/48624987
has body: ...wondering if anyone had an easy solution to do that. I have not used zipline and don't have an implemented solution for what you are asking. All I can help you with is with pickling your test state. Though from the information you've provided, I can only read that perf_tracker is what you need help with. Looking at its source there shouldn't be any problem with pickling it (correct me if I am wrong, because I haven't done it myself). Also you can read about pickling custom objects here. Another interesting method is __repr__ which helps recreating objects from strings.
score: 0
type: Answer

apache-spark
tags question: http://stackoverflow.com/q/48549326
tags question: http://stackoverflow.com/q/48642605
tags question: http://stackoverflow.com/q/48549140
tags question: http://stackoverflow.com/q/48576065
tags question: http://stackoverflow.com/q/48557880
tags question: http://stackoverflow.com/q/48541987
tags question: http://stackoverflow.com/q/48499301
tags question: http://stackoverflow.com/q/48535236
tags question: http://stackoverflow.com/q/48645148
tags question: http://stackoverflow.com/q/48527047
tags question: http://stackoverflow.com/q/48606032
tags question: http://stackoverflow.com/q/48645028
tags question: http://stackoverflow.com/q/48493384
tags question: http://stackoverflow.com/q/48499139
tags question: http://stackoverflow.com/q/48566982
tags question: http://stackoverflow.com/q/48504849
tags question: http://stackoverflow.com/q/48607923
tags question: http://stackoverflow.com/q/48500850
tags question: http://stackoverflow.com/q/48564888
tags question: http://stackoverflow.com/q/48493733
tags question: http://stackoverflow.com/q/48628648
tags question: http://stackoverflow.com/q/48623438
tags question: http://stackoverflow.com/q/48636280
tags question: http://stackoverflow.com/q/48547700
tags question: http://stackoverflow.com/q/48565965
tags question: http://stackoverflow.com/q/48544021
tags question: http://stackoverflow.com/q/48546335
tags question: http://stackoverflow.com/q/48505638
tags question: http://stackoverflow.com/q/48509857
tags question: http://stackoverflow.com/q/48492741
tags question: http://stackoverflow.com/q/48637278
tags question: http://stackoverflow.com/q/48556872
tags question: http://stackoverflow.com/q/48541064
tags question: http://stackoverflow.com/q/48639069
tags question: http://stackoverflow.com/q/48510895
tags question: http://stackoverflow.com/q/48612052
type: Tag
tags question: http://stackoverflow.com/q/48558131
tags question: http://stackoverflow.com/q/48488866
tags question: http://stackoverflow.com/q/48578787
tag name: apache-spark
tags question: http://stackoverflow.com/q/48553005
tags question: http://stackoverflow.com/q/48555860
tags question: http://stackoverflow.com/q/48644689
tags question: http://stackoverflow.com/q/48523629
tags question: http://stackoverflow.com/q/48593268
tags question: http://stackoverflow.com/q/48582698
tags question: http://stackoverflow.com/q/48565186

http://stackoverflow.com/comment/84295761
has text: `dict(df1.values)` is causing a `ValueError`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48592789

http://stackoverflow.com/q/48561250
has comment: http://stackoverflow.com/comment/84127986
has title: Avoiding redundant write operations with Django ORM
has comment: http://stackoverflow.com/comment/84123387
has comment: http://stackoverflow.com/comment/84118245
tagged with: python
tagged with: mysql
linked to: http://stackoverflow.com/q/1355150
has comment: http://stackoverflow.com/comment/84121711
has body: I have a periodically running task that performs a lot of write calls to the database on existing data. In most cases, records that are written don't contain a change, so the update queries are redundant. The redundant write calls do put an unnecessarily high load on our database replication, though. This is roughly the algorithm: Fetch existing row from database Potentially modify a lot of fields based on parameters that were passed to the algorithm Save the updated row to database using instance.save() Since it's easier to scale our task processors than our database replication, I thought I'd shift some of the processing load towards code by doing this: if original_instance != possibly_updated_instance: possibly_updated_instance.save() Thing is: Django ORM's equality operator only seems to compare primary keys, so we'd incorrectly be dropping changes. Is there a better way to handle this?
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: django
favorite count: 0
type: Question

http://stackoverflow.com/comment/84161812
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48573306
type: QuestionComment
has text: option 2), create a new view with an associated template. template is two iframes (sigh) with one of the given routes in each frame. then some javascript to auto refresh, and fix up ui etc.

http://stackoverflow.com/a/48597422
downvote count: 0
has comment: http://stackoverflow.com/comment/84201780
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48593329
has body: You can't invoke the actual built-in argument verification for a function without calling the function, but you can use something pretty close. The inspect module has a function signature(), which returns a Signature object representing the argument signature of the function passed to it. That Signature object has a bind() method which attempts to create a BoundArguments object using the arguments passed to it. If those arguments don't match the signature, a TypeError is raised. While this mostly behaves like the built-in argument binding logic, it has a few differences. For example, it can't always determine the signature of functions written in C, and its interaction with decorators will depend on whether they use functools.wraps (or something else that sets the __wrapped__ attribute). That said, since the real argument binding logic is inaccessible, inspect.signature is the best alternative. We can use all this to create your decorator: import functools import inspect def preprocess(func): sig = inspect.signature(func) @functools.wraps(func) def wrapper(*args, **kwargs): try: sig.bind(*args, **kwargs) except TypeError: pass # bad arguments; skip preprocessing else: print("Preprocessing: args=%r, kwargs=%r" % (args, kwargs)) # ... etc. return func(*args, **kwargs) return wrapper Usage: @preprocess def test_func(x, y, z=None): print(x, y, z) &gt;&gt;&gt; test_func(2) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 10, in wrapper TypeError: test_func() missing 1 required positional argument: 'y' &gt;&gt;&gt; test_func(1, 2, 3, a=5) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 10, in wrapper TypeError: test_func() got an unexpected keyword argument 'a' &gt;&gt;&gt; test_func(1, 2) Preprocessing: args=(1, 2), kwargs={} 1 2 None Note that, if bad arguments are supplied, you do in fact want to call the function, because you "want the exact behav…
type: Answer
accepted answer of: http://stackoverflow.com/q/48593329
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/84204008

http://stackoverflow.com/a/48615499
type: Answer
accepted answer of: http://stackoverflow.com/q/48577073
score: 0
has body: # Defining a function to convert phone numbers to International format def phone_cleaner(fc_lead_phone): for match in phonenumbers.PhoneNumberMatcher(fc_lead_phone,"PH"): return phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.E164) leads['phone_one_clean'] = leads['phone_one'].apply(phone_cleaner)
answers question: http://stackoverflow.com/q/48577073
type: AcceptedAnswer

http://stackoverflow.com/a/48617070
has comment: http://stackoverflow.com/comment/84231434
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48616996
has comment: http://stackoverflow.com/comment/84230928
has body: You're nearly there. Assuming that .split() actually splits the lines correctly (which it wouldn't do if there are actual commas between the values), you just need an additional unpacking operator (*): d = {} with open("servers.txt") as f: for line in f: key, *val = line.split() # first element -&gt; key, rest -&gt; val[0], val[1] etc. d[int(key)] = val If you want to check if a user-entered key exists, you can do something like ukey = int(input("Enter key number: ")) values = d.get(ukey) if d is not None: # do something else: print("That key doesn't exist.")
answers question: http://stackoverflow.com/q/48616996
has comment: http://stackoverflow.com/comment/84231512

http://stackoverflow.com/q/48519062
type: Question
linked to: http://stackoverflow.com/q/25086060
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
score: 38
has answer: http://stackoverflow.com/a/48519389
upvote count: 38
has body: I read the similar topic here. I think the question is different or at least .index() could not solve my problem. This is a simple code in R and its answer: x &lt;- c(1:4, 0:5, 11) x #[1] 1 2 3 4 0 1 2 3 4 5 11 which(x==2) # [1] 2 7 min(which(x==2)) # [1] 2 which.min(x) #[1] 5 Which simply returns the index of the item which meets the condition. If x be the input for Python, how can I get the indeces for the elements which meet criteria x==2 and the one which is the smallest in the array which.min. x = [1,2,3,4,0,1,2,3,4,11] x=np.array(x) x[x&gt;2].index() ##'numpy.ndarray' object has no attribute 'index'
tagged with: python
has answer: http://stackoverflow.com/a/69815221
answer count: 6
accepted answer: http://stackoverflow.com/a/48519235
has answer: http://stackoverflow.com/a/48519134
has answer: http://stackoverflow.com/a/48519235
tagged with: numpy
has answer: http://stackoverflow.com/a/54924701
has title: R's which() and which.min() Equivalent in Python
possible better answer: http://stackoverflow.com/a/48519134
downvote count: 0
has answer: http://stackoverflow.com/a/48521954
favorite count: 0

http://stackoverflow.com/a/48589756
has body: Just test for the object type then, in a conditional expression: [d.date() if isinstance(d, datetime.datetime) else d for d in i] This produces a list with all the values in there, with the datetime objects replaced with dates: &gt;&gt;&gt; [d.date() if isinstance(d, datetime.datetime) else d for d in i] [1127, 1, 2, datetime.date(1900, 1, 1), 'America/NewYork', None, None, datetime.date(1970, 1, 1), datetime.date(9999, 12, 31), 62, 3, ' ', 2, datetime.date(2017, 12, 6)] If you wanted to have just the dates, use a filter: [d.date() for d in i if isinstance(d, datetime.datetime)] Now we are filtering, so only the dates remain: &gt;&gt;&gt; [d.date() for d in i if isinstance(d, datetime.datetime)] [datetime.date(1900, 1, 1), datetime.date(1970, 1, 1), datetime.date(9999, 12, 31), datetime.date(2017, 12, 6)]
answers question: http://stackoverflow.com/q/48589705
score: 0
type: Answer

http://stackoverflow.com/a/48635553
score: 2
has comment: http://stackoverflow.com/comment/84343542
type: Answer
has comment: http://stackoverflow.com/comment/84429635
has comment: http://stackoverflow.com/comment/84455988
upvote count: 2
has comment: http://stackoverflow.com/comment/84407386
has comment: http://stackoverflow.com/comment/84295469
accepted answer of: http://stackoverflow.com/q/48635552
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84642837
downvote count: 0
has body: Your Python project is a reverse proxy, and the API you're looking for is just ordinary HTTP. (After&nbsp;all, that's how web browsers interact with Apache already...) To make HTTP requests, you need a client like urllib or requests: import requests response = requests.get("http://" + apache_host + ":8080/" + parsed_path) By default, all your apps and microservers will think that all clients come from localhost. If that's a problem, see if your apps accept the X-Forwarded-For header. (If they do, include it in all your requests.)
has comment: http://stackoverflow.com/comment/84408894
has comment: http://stackoverflow.com/comment/84429706
answers question: http://stackoverflow.com/q/48635552

http://stackoverflow.com/q/48548257
accepted answer: http://stackoverflow.com/a/48548290
has answer: http://stackoverflow.com/a/48548465
has body: is there a way to pass an argument to the input function? what I would like to do is have the console output look like this Enter data for row 0: Enter data for row 1: Enter data for row 2: However when I add row to the input I get the below error. Is there a way to display the row count when accepting input from the user? TypeError: input expected at most 1 arguments, got 2 def get_matrix(): matrix = [] for row in range(0, 3): value = input("Enter data for row : ", row).strip() &lt;do stuff&gt; return matrix
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48548290
duplicate of: http://stackoverflow.com/q/14856953
answer count: 2
possible better answer: http://stackoverflow.com/a/48548465
downvote count: 0
linked to: http://stackoverflow.com/q/14856953
has title: Python: pass an argument to be displayed in the input() function
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/48492759
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48492129
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48492129
has body: Your problem is that replace is the name of a function, and you are trying to concatenate it to a string, which is why this return contractions_re.sub(r'(?:\W|^)'+replace+'(?!\w)', s) is giving you the error you report. When you call sub() you can either supply a replacement string, or the name of a function to call, but you can't combine the two approaches the way you are trying to do. I would go back to your original approach of supplying sub() a function. I think what you are missing is the special regex sequence \b. It matches the empty string, but only at word boundaries. Like this: contractions_re = re.compile("|".join(r'(\b%s\b)' % c for c in contractions_dict.keys())) This gives the following re pattern: r"(\bdidn't\b)|(\bdon't\b)|(\bur\b)" This will avoid nasty syou areprises. Note the r'...' string notation. You need it so that the backslashes won't trip you up. This works with multiple tokens in a string, as it should: &gt;&gt;&gt; expand_contractions("didn't that surprise you") 'did not that surprise you' but doing that also shows the limitations of token-by-token substitution of contractions. To begin a question did not that is very 19th-century (and in fact they probably said didn't that even when they wrote did not that). The present-day English for that would be did that not surprise you.
has comment: http://stackoverflow.com/comment/84184161
downvote count: 0

http://stackoverflow.com/comment/84089738
has text: @FlorentB. what is viewport? browser window?
comment on: http://stackoverflow.com/q/48543737
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84194738
comment on: http://stackoverflow.com/a/48598904
score: 0
type: AnswerComment
type: Comment
has text: True. I am not sure as well. It should depend on OP's problem.

http://stackoverflow.com/q/48607198
answer count: 3
has body: I need to send an image file to a flask server using Postman.I did send it using a web browser and "render template".But when i tried the same program with postman it showed "method not allowed" . I also tried /upload, but it says "bad request"
downvote count: 0
tagged with: flask-restful
accepted answer: http://stackoverflow.com/a/48607411
tagged with: postman
favorite count: 0
possible better answer: http://stackoverflow.com/a/61142860
type: Question
has answer: http://stackoverflow.com/a/61142860
has comment: http://stackoverflow.com/comment/95936680
tagged with: python
has title: How to send an image to a flask server using Postman
score: 4
has answer: http://stackoverflow.com/a/74372100
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48607411

http://stackoverflow.com/comment/84051242
type: Comment
type: QuestionComment
has text: And perhaps you should not use people's real names to protect their privacy
comment on: http://stackoverflow.com/q/48528112
score: 1

http://stackoverflow.com/comment/115451286
comment on: http://stackoverflow.com/a/48622736
has text: You can implement bicubic in a shader.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48546675
tagged with: element
has comment: http://stackoverflow.com/comment/84090010
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84091446
has body: I am trying to get a csv file but selenium is not able to find the element i am able to fill the form. website url is "https://www.nseindia.com/products/content/equities/equities/eq_security.htm" to download the csv i have to click on element with text = Download file in csv format but it's not finding it. print(browser.find_element_by_xpath('//* @id="historicalData"]/div1/span[2]/a').click()) i have tried using css selector and link text, tag name but getting error not able to locate element. link is highlighted here
type: AnsweredQuestion
tagged with: find
downvote count: 2
answer count: 1
tagged with: selenium
upvote count: 1
accepted answer: http://stackoverflow.com/a/48547618
favorite count: 0
type: Question
has title: finding link element using selenium inside span
has answer: http://stackoverflow.com/a/48547618

http://stackoverflow.com/comment/108260443
comment on: http://stackoverflow.com/a/61194615
score: 0
type: AnswerComment
type: Comment
has text: @AdamGriffiths. I didn't realize you were the one placing the bounty. Do you get to decide who gets it regardless of OP's selection?

http://stackoverflow.com/comment/84306508
type: Comment
has text: Am I correct to say that `self.listbox2` hasn't a `listvariable` because Method2 does not use a `listvariable' to load data into a `tk.Listbox` but instead uses the `.insert(tk.END, item)` method? If so, this means that tk.Listbox has 2 methods of storing data. In the question by @Nae, I gathered that `listvariable` is a variable class. So what type of object is used to store the data via `.insert(tk.END, item) ` method? I gather it is not a variable class since `getvar` returns `""`.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48626736

http://stackoverflow.com/a/78158109
has comment: http://stackoverflow.com/comment/139323338
score: 1
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48609891
has body: It's already mentioned by Stephen but changing l in the OP into a generator expression (g below) allows you to evaluate f only once without creating an unnecessary list in the middle. f = lambda x: x if x &lt; 3 else None l = [f(x) for x in [1,2,3,4]] # &lt;--- list (inefficient) g = (f(x) for x in [1,2,3,4]) # &lt;--- generator (efficient) output = [x for x in g if x is not None] You can use filter() on the generator too (for a solution closer to what OP had in mind): output = list(filter(None, g)) N.B. filter(None, g) will filter out all falsy values, so it will filter out 0; if you don't want to do that, then probably the list comprehension above is the cleaner solution. Python&gt;=3.9 Since Python 3.9, creating a singleton list and looping over it has been optimized. So instead of using a generator expression (which may be exhausted by accident) or the walrus operator (which leaks the loop variable to the outer scope), you can create a nested loop where the second loop is over a singleton list: output = [y for x in [1,2,3,4] for y in [f(x)] if y is not None] Simple timeit test (on Python 3.12) shows that this is actually slightly faster than the other options (including the one using the walrus operator).

http://stackoverflow.com/q/48592450
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/84182248
answer count: 2
tagged with: sha256
has answer: http://stackoverflow.com/a/77481512
downvote count: 0
tagged with: sha
tagged with: python-requests
has body: Haven't worked in Python much and I'm obviously not sending the proper signature being asked for. How do I hash it and pass it in properly? SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body. Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation. Use your secretKey as the key and totalParams as the value for the HMAC operation. The signature is not case sensitive. totalParams is defined as the query string concatenated with the request body. Full Documentation: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md import requests, json, time, hashlib apikey = "myactualapikey" secret = "myrealsecret" test = requests.get("https://api.binance.com/api/v1/ping") servertime = requests.get("https://api.binance.com/api/v1/time") servertimeobject = json.loads(servertime.text) servertimeint = servertimeobject['serverTime'] hashedsig = hashlib.sha256(secret) userdata = requests.get("https://api.binance.com/api/v3/account", params = { "signature" : hashedsig, "timestamp" : servertimeint, }, headers = { "X-MBX-APIKEY" : apikey, } ) print(userdata) I am getting {"code":-1100,"msg":"Illegal characters found in parameter 'signature'; legal range is '^[A-Fa-f0-9]{64}$'."}
favorite count: 0
type: Question
tagged with: python-3.x
has title: Binance API call with SHA56 and Python requests
has answer: http://stackoverflow.com/a/48592499
type: UnansweredQuestion
score: 6

http://stackoverflow.com/q/48616216
type: AnsweredQuestion
has body: I am new to kivy/python.I want to add a calendar on textBox. this code gives error ImportError: No module named KivyCalendar Can someone tell me how to make it? Any advise or guidance would be greatly appreciated..!! demo.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.textinput import TextInput from kivy.uix.popup import Popup from KivyCalendar import CalendarWidget class SetIndex(BoxLayout): def setDate(self, *args): popup = Popup(title='Insert Old Date', content=CalendarWidget(), size_hint=(.9, .5)).open() class Demo(App): def bulid(self): return SetIndex() if __name__ == '__main__': Demo().run() demo.kv BoxLayout: orientation: "vertical" size_hint: 1, .4 TextInput: id: old_date hint_text: "Old Date" on_focus: root.setDate()
tagged with: python-2.7
score: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: kivy-language
has title: Python/Kivy : add a calendar in kivy
upvote count: 1
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/48636476
accepted answer: http://stackoverflow.com/a/48636476

http://stackoverflow.com/q/48604896
answer count: 3
has answer: http://stackoverflow.com/a/48604965
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84206368
has title: Trying to send an email with python but getting error
linked to: http://stackoverflow.com/q/37752903
type: Question
has comment: http://stackoverflow.com/comment/84206380
has answer: http://stackoverflow.com/a/48604953
has body: Hi I been trying to send an email with python but errors keep popping up. This is my script. import smtplib from string import Template from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText MY_ADDRESS = '*****@gmail.com' PASSWORD = '*****' def get_contacts(filename): """ Return two lists names, emails containing names and email addresses read from a file specified by filename. """ names = [] emails = [] with open(filename, mode='r', encoding='utf-8') as contacts_file: for a_contact in contacts_file: names.append(a_contact.split()[0]) emails.append(a_contact.split()[1]) return names, emails def read_template(filename): """ Returns a Template object comprising the contents of the file specified by filename. """ with open(filename, 'r', encoding='utf-8') as template_file: template_file_content = template_file.read() return Template(template_file_content) def main(): names, emails = get_contacts('mycontacts.txt') # read contacts message_template = read_template('message.txt') # set up the SMTP server s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login(MY_ADDRESS, PASSWORD) # For each contact, send the email: for name, email in zip(names, emails): msg = MIMEMultipart() # create a message # add in the actual person name to the message template message = message_template.substitute(PERSON_NAME=name.title()) # Prints out the message body for our sake print(message) # setup the parameters of the message msg['From'] = MY_ADDRESS msg['To'] = email msg['Subject'] = "This is TEST" # add in the message body msg.attach(MIMEText(message, 'plain')) # send the message via the server set up earlier. s.send_message(msg) del msg # Terminate the SMTP session and close the connection s.quit() if __name__ == '__main__': main() Traceback (most recent call last): File "C:/Users/tyger_000/Desktop/Object Oriented Programming/Project/Private-Group-Work-OOPP/SmartLifestyle(Combined)/Email Sender/email_sender.py", line 75, in &lt;module&gt; main() File "C:/U…
has answer: http://stackoverflow.com/a/48605017
tagged with: python
score: 0

http://stackoverflow.com/q/48517318
has comment: http://stackoverflow.com/comment/84029600
has answer: http://stackoverflow.com/a/48518234
has comment: http://stackoverflow.com/comment/84029424
score: 1
has comment: http://stackoverflow.com/comment/84029850
tagged with: python
has comment: http://stackoverflow.com/comment/84029378
has comment: http://stackoverflow.com/comment/84030711
type: Question
has title: Django, ImportError: cannot import name Celery
has comment: http://stackoverflow.com/comment/84029468
has comment: http://stackoverflow.com/comment/84030662
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84029165
upvote count: 1
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/84030012
has body: Why is this happening? My celery.py: import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) my init.py # import celery from .celery import app as celery_app I even tried renaming celery.py to something else and the error still persisted. Could it be because of my python version?
has comment: http://stackoverflow.com/comment/84029443
has answer: http://stackoverflow.com/a/48520870
favorite count: 0
tagged with: celery

http://stackoverflow.com/comment/84060455
comment on: http://stackoverflow.com/a/48532274
score: 0
type: Comment
has text: It is because you are iterating over `products` instead of `birdish`.
type: AnswerComment

http://stackoverflow.com/q/48554289
has comment: http://stackoverflow.com/comment/84104943
answer count: 1
downvote count: 0
has title: Python iterator (generator) delete source, still works. what is going on?
has comment: http://stackoverflow.com/comment/84104972
has comment: http://stackoverflow.com/comment/84104921
favorite count: 0
accepted answer: http://stackoverflow.com/a/48554398
type: Question
has comment: http://stackoverflow.com/comment/84105070
has answer: http://stackoverflow.com/a/48554398
has body: I need some clarification on what is going on with the following behavior when using a generator. I'm afraid I am missing something fundamental, so any advice is welcome. (edit) Specifically my question deals with the del of the iterable that an iterator is created on. My ultimate use case is that I am iterating over a pretty massive corpus for text processing. It isn't so large that it can't be held in memory, but is big enough that training a subsequent model is impossible with it in memory. So, in my investigation, I attempted the following and I'm confused how this works. &gt;&gt;&gt; iterable = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] &gt;&gt;&gt; iterable.__sizeof__() 160 &gt;&gt;&gt; iterator = (x+1 for x in iterable) &gt;&gt;&gt; iterator &lt;generator object &lt;genexpr&gt; at 0x1019f8570&gt; &gt;&gt;&gt; iterator.__sizeof__() 64 &gt;&gt;&gt; del iterable &gt;&gt;&gt; for i in iterator: ... print(i) ... 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Once I delete the iterable, what is the iterator referencing? How is it still able to have a smaller mem footprint but also succesfully execute (I was under the impression that the generator simply points to existing data, but if it is deleted I have to shrug?) What am I missing? (something clearly. Sorry. I'm self taught). Thanks in advance!
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84105109
has comment: http://stackoverflow.com/comment/84104938
tagged with: generator
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12477835

http://stackoverflow.com/comment/83972287
type: QuestionComment
comment on: http://stackoverflow.com/q/48489530
has text: I am looking at your regex demo and it's unclear what are you trying to match. There are char like `% ?` that you want to skip...
score: 0
type: Comment

http://stackoverflow.com/comment/84116109
type: Comment
comment on: http://stackoverflow.com/q/48560227
score: 0
has text: Why would you do that? The mean of weights doesn't mean anything at all.
type: QuestionComment

http://stackoverflow.com/a/52758310
downvote count: 0
has body: If you are using windows then go to C: and search for python. A folder with user version number will be shown like 'Python37'. Open the folder and you'll see a folder named Scripts, open that, then you'll find pip.exe. Now copy the folder path and open 'Edit the system environment variables' in control panel. In that click on Environmental Variables and you'll something called path. Select path and click on edit, a window pops up, in that click and new and paste the directory address you copied previously. Save and exit everything. Now open cmd and type pip install [whatever].
answers question: http://stackoverflow.com/q/48572380
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/84266955
comment on: http://stackoverflow.com/a/48633358
score: 0
has text: what if I wanted to send an additional parameter to each call? Then the function would receive 3 parameters: the list element, its index and the other param.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48513263
has title: Elasticsearch's format error
answer count: 1
has answer: http://stackoverflow.com/a/48513483
accepted answer: http://stackoverflow.com/a/48513483
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: elasticsearch
type: Question
has body: I wrote def user(lat, lon, distance, start_time, end_time): param = { "query": { "filter": { "geo_distance": { "distance": distance, "distance_type": "plane", "location": { "lat": lat, "lon": lon } } }, "query": { "bool": { "must": [ {"match": {"start_time": start_time}}, {"match": {"end_time": end_time}} ] } } } } num = 0 results = get_data().query(param) But TransportError(400, 'parsing_exception', 'no [query] registered for [filter]') error happens.I think the way of writing format of Elasticsearch is wrong.I used as reference,https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-geo-distance-query.html .But I cannot find the wrong point.How should I fix this?What is wrong in my code?

http://stackoverflow.com/a/48489958
type: Answer
answers question: http://stackoverflow.com/q/48488723
has body: Here is an approach without cv::HoughLines(): on the binary image, execute a function to detect the most distant pixel from the center of the image towards a specific direction (left, right, top, bottom). This function returns the following pixels, drawn in the image below in red, green and blue: Left: [21, 35] Top: [43, 0] Right: [63, 35] From these 3 points you have a couple of options to detect the angle: Discard one of the points and compute the angle between the other 2; Figure out which one is the center point and compute the angle between all 3 of them; The source code below figures out which one is closest to the center of the image and computes the angle from all the 3 points using the atan2() method. Running the example with the binary image outputs: Angle: 57.8477 (degrees) Seems legit! There's a few improvements you can do from here on to improve the accuracy of the angle. One of them is to skeletonize the binary image and make those lines really thin. Source code: #include &lt;opencv2/opencv.hpp&gt; #include &lt;opencv2/highgui.hpp&gt; #include &lt;opencv2/imgproc.hpp&gt; #include &lt;iostream&gt; enum imgEdge { LEFT = 0, RIGHT = 1, TOP = 2, BOTTOM = 3 }; // Find the most distant pixel from the center in a particular direction cv::Point mostDistantPixel(const cv::Mat&amp; input, const imgEdge&amp; edge) { if (edge &lt; 0 || edge &gt; 3) { std::cout &lt;&lt; "!!! mostDistantPixel() invalid side" &lt;&lt; std::endl; return cv::Point(); } if (input.channels() &gt; 1) { std::cout &lt;&lt; "!!! mostDistantPixel() only single channel img is supported" &lt;&lt; std::endl; return cv::Point(); } cv::Point mostDistant(-1,-1); for (int r = 0; r &lt; input.rows; r++) { for (int c = 0; c &lt; input.cols; c++) { // Examine pure white pixels only (row, col) if (input.at&lt;uchar&gt;(r,c) == 255) { switch (edge) { case imgEdge::LEFT: if (c &lt;= mostDistant.x || mostDistant == cv::Point(-1, -1)) mostDistant = cv::Point(c, r); break; case imgEdge::RIGHT: if (c &gt;= mos…
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48488723
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/a/48527837
downvote count: 0
upvote count: 1
has body: You can try something like this: data = ['0','0','0','0','131997','https://www.google.com.ar/','google.com.ar','0','0','0','0','134930','https://www.a-a.com/','a-a.com'] a = [] count = 1 b = [] for item in data: if count == 7: a.append(b) count = 1 b = [] else: b.append(item) count = count + 1 print(a)
answers question: http://stackoverflow.com/q/48527447
score: 1
type: Answer

http://stackoverflow.com/comment/84185842
comment on: http://stackoverflow.com/q/48594308
type: QuestionComment
has text: post some sample input for cards
score: 0
type: Comment

http://stackoverflow.com/q/48552934
upvote count: 1
tagged with: python
favorite count: 0
has title: Python script using webjobs in azure
has answer: http://stackoverflow.com/a/48554567
tagged with: azure
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84104472
tagged with: macos
has body: Hello I'm getting an error when uploading a new azure webjob. The error says it cant create the webjob. I followed this tutorial which I found it in a question that was asked in here. Link My script is the following: import sys, os sys.path.append(os.path.join(os.getcwd(), "site-packages")) import requests as req r = req.get('http://my_website.azurewebsites.net/user/cron') # Development # r = req.get('http://localhost:5000/user/cron') print(r.status_code) And the structure of my files is this one If anyone can point out where I made a mistake, I just searched for hours and many questions and tutorials point out this is the proper way to add a library in Azure.
has comment: http://stackoverflow.com/comment/84894998
type: Question
linked to: http://stackoverflow.com/q/45716757
type: UnansweredQuestion
downvote count: 0
tagged with: azure-webjobs

http://stackoverflow.com/comment/84173885
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48588166
has text: I have tried this, but there are more than 300 files with the same name (each day of the year). The problem is that Chrome has a 100 file auto-rename limit when saving files. After filename (100).jpg, the next file's name will revert back to filename.jpg instead of continuing the sequence (i.e. 'filename (101).jpg').

http://stackoverflow.com/q/48597577
linked to: http://stackoverflow.com/q/7243750
linked to: http://stackoverflow.com/q/45665991
has comment: http://stackoverflow.com/comment/84471524
tagged with: url
linked to: http://stackoverflow.com/q/2549829
accepted answer: http://stackoverflow.com/a/48745034
linked to: http://stackoverflow.com/q/16140921
downvote count: 1
has answer: http://stackoverflow.com/a/48745034
favorite count: 0
type: Question
has body: Problem I'm trying to download &gt;100.000 files from a ftp server in parallel (using threads). I previously tried it with urlretrieve as answered here, however this gave me the following error: URLError(OSError(24, 'Too many open files')). Apparently this problem is a bug (cannot find the reference anymore), so I tried to use urlopen in combination with shutil and then write it to file which I could close myself, as described here. This seemed to work fine, but then I got the same error again: URLError(OSError(24, 'Too many open files')). I thought whenever writing to a file is incomplete or will fail the with statement will cause to file to close itself, but seemingly the files still keep open and will eventually cause the script to halt. Question How can I prevent this error, i.e. make sure that every files get closed? Code import csv import urllib.request import shutil from multiprocessing.dummy import Pool def url_to_filename(url): filename = 'patric_genomes/' + url.split('/')[-1] return filename def download(url): url = url.strip() try: with urllib.request.urlopen(url) as response, open(url_to_filename(url), 'wb') as out_file: shutil.copyfileobj(response, out_file) except Exception as e: return None, e def build_urls(id_list): base_url = 'ftp://some_ftp_server/' urls = [] for some_id in id_list: url = base_url + some_id + '/' + some_id + '.fna' print(url) urls.append(url) return urls if __name__ == &quot;__main__&quot;: with open('full_data/genome_ids.txt') as inFile: reader = csv.DictReader(inFile, delimiter = '\t') ids = {row['some_id'] for row in reader} urls = build_urls(ids) p = Pool(100) print(p.map(download, urls))
has comment: http://stackoverflow.com/comment/84482793
tagged with: data-retrieval
tagged with: download
has title: Urllib urlopen/urlretrieve too many open files error
tagged with: python
has comment: http://stackoverflow.com/comment/84466349
has comment: http://stackoverflow.com/comment/84192147
possible better answer: http://stackoverflow.com/a/48767947
upvote count: 4
has comment: http://stackoverflow.com/comment/84482777
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48789193
answer count: 3
has answer: http://stackoverflow.com/a/48767947

http://stackoverflow.com/a/48615682
has comment: http://stackoverflow.com/comment/84231969
accepted answer of: http://stackoverflow.com/q/48615653
has body: In [128]: a = np.ones((5,3),int) In [129]: a.T Out[129]: array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]) In [131]: list(zip(a.T, (a+3).T)) Out[131]: [(array([1, 1, 1, 1, 1]), array([4, 4, 4, 4, 4])), (array([1, 1, 1, 1, 1]), array([4, 4, 4, 4, 4])), (array([1, 1, 1, 1, 1]), array([4, 4, 4, 4, 4]))] zip iterates over the first dim of the inputs. In this case it's the rows of transposed arrays. So at each iteration is taking one row, a 1d array. The result is a list of tuples, each tuple consisting of two 1d arrays. We could add a dimension to a before processing: In [132]: a=a[None,:,:] In [133]: a.shape Out[133]: (1, 5, 3) In [134]: a.T.shape Out[134]: (3, 5, 1) In [135]: list(zip(a.T, (a+3).T)) Out[135]: [(array([[1], [1], [1], [1], [1]]), array([[4], [4], [4], ... [4], [4]]))] In [136]: _[0][0].shape Out[136]: (5, 1) I wouldn't describe that as pretty, but it seems to meet your requirements. Or you could use a list comprehension to expand the zip, and add the dimension then: In [139]: [(i[:,None],j[:,None]) for i,j in zip(a.T, (a[:2]+3).T)] Out[139]: [(array([[1], [1], [1], [1], [1]]), array([[4], [4]])), (array([[1], [1], [1], [1], [1]]), array([[4], [4]])), (array([[1], [1], [1], [1], [1]]), array([[4], [4]]))] This also works: list(zip(*np.atleast_3d(a.T,b.T))) atleast_3d can operate on a list of arrays, making each (M, N, 1). It's a specialized function that I don't use very often.
has comment: http://stackoverflow.com/comment/84236027
answers question: http://stackoverflow.com/q/48615653
type: Answer
has comment: http://stackoverflow.com/comment/84229384
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84266937
score: 0
type: Comment
has text: The dual of a problem is something very different from duals in a solution.
type: QuestionComment
comment on: http://stackoverflow.com/q/48606094

http://stackoverflow.com/q/48552268
answer count: 2
has title: Selenium Python dropdown menu
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/12019780
has answer: http://stackoverflow.com/a/48552739
linked to: http://stackoverflow.com/q/21350605
has answer: http://stackoverflow.com/a/48556770
linked to: http://stackoverflow.com/q/18600391
tagged with: selenium
has body: I'm a bit new to selenium. I'm trying to select values from a drop-down menu using selenium in python, but for this website it does not seem to work. Any ideas on how it can be done? HTML code of dropdown: Geographical breakdown Geographical breakdown Rating Maturity Benchmark breakdown Risk currency Active currency risk Active duration risk Screenshot of dropdown: Drop down from this page: Web link
downvote count: 1
has comment: http://stackoverflow.com/comment/84102824
favorite count: 0
type: Question

http://stackoverflow.com/q/48490994
linked to: http://stackoverflow.com/q/39434821
answer count: 2
upvote count: 0
type: UnansweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/48491526
has comment: http://stackoverflow.com/comment/84011241
has comment: http://stackoverflow.com/comment/83987926
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84046920
type: Question
has comment: http://stackoverflow.com/comment/83980231
has title: how do i click this element using selenium?
has comment: http://stackoverflow.com/comment/84047079
has comment: http://stackoverflow.com/comment/83980511
has answer: http://stackoverflow.com/a/48495878
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84047002
has body: My end goal is to click a "download menu" button and in order to get to the button i need to click some optinons before hand. One of the options i am strugling with is this one: this is what the html looks like when i do an inspect element on the option: The Pub when i click on the option "The Pub" the list class becomes active and reveals a download menu button to a pdf which is what i want to click, like so: The Pub this is what the selector looks like when i do a copy selector on chrome: #\31 5 this is what the xpath looks like when i do a copy xpath on chrome: //*[@id="15"] i have tried the following and everytime webdriver can not find it: browser.find_element_by_css_selector("#\31 5") browser.find_element_by_css_selector(r"#\31 5") browser.find_element_by_xpath("//*[@id=\"15\"]")
tagged with: selenium-webdriver
tagged with: python-3.x

http://stackoverflow.com/comment/84023174
comment on: http://stackoverflow.com/q/48514110
score: 0
has text: Thanks again Umutto, I will make the change and get back to you
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84059922
type: AnswerComment
has text: i like this solution. can you pls explain what `df2.assign(a='key')` does?
comment on: http://stackoverflow.com/a/48532006
score: 0
type: Comment

http://stackoverflow.com/comment/84199071
type: QuestionComment
comment on: http://stackoverflow.com/q/48600653
has text: @JonClements thanks for letting me know about `datetime.strptime`. What is wrong with my logic?
score: 0
type: Comment

http://stackoverflow.com/comment/84041333
comment on: http://stackoverflow.com/q/48522641
score: 0
has text: @Orenshi thanks, your suggestion works. I don't know why though.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84062442
comment on: http://stackoverflow.com/a/48532948
type: Comment
score: 1
type: AnswerComment
has text: This is a perfect answer, thanks. Just want to note you'd have to use a money sign instead of a period, like so: `ne_chunk(pos_tag(word_tokenize(tagged_tokens)))$pformat()`.

http://stackoverflow.com/comment/84135066
comment on: http://stackoverflow.com/a/48569368
score: 0
type: Comment
has text: @IMCoins: well this fills only the *main* diagonal (it is even in the documentation) :)
type: AnswerComment

http://stackoverflow.com/comment/84268817
comment on: http://stackoverflow.com/a/48635323
score: 0
type: Comment
has text: This solution only works reliably in python 3.6, since it relies on the order of `substrings.items()`.
type: AnswerComment

http://stackoverflow.com/comment/84610996
score: 0
type: AnswerComment
has text: Thank you for letting me know. Done: https://github.com/Georgetown-IR-Lab/simstring/pull/2.
comment on: http://stackoverflow.com/a/48794384
type: Comment

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

http://stackoverflow.com/comment/127113539
has text: @coderanger the point was having credentials set as environment variables at all is almost as bad as having them in the Dockerfile. They can be exposed in logs, etc and are easy to reveal
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50510753
type: AnswerComment

http://stackoverflow.com/comment/89021958
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48586647
has text: i suggest that you post the content of your csv , for other people who struggle withe same issue/concern
type: Comment

http://stackoverflow.com/a/48643217
has comment: http://stackoverflow.com/comment/123457047
answers question: http://stackoverflow.com/q/48639369
upvote count: 5
type: Answer
has body: In the code from the question the OffsetImage is given an argument zoom=0.9. This means that each pixel of the original image takes 0.9/0.72=1.25 pixels on screen. Hence 5 pixels of the original image needs to squeezed into 4 pixels on screen. This inevitably leads to some artifacts as observed in the output of the code. If the requirement is to show the image in the exact resolution of the original image, you need to make sure to use exactly one pixel per pixel for the OffsetImage. This would be accomplished by setting the zoom to the ppi of 72. divided by the figure dpi (100 by default). OffsetImage(arr_img, zoom=72./self.figure.dpi) As a result, the image shown would indeed have the same dimensions in the matplotlib plot as the original image.
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48639369

http://stackoverflow.com/comment/84151575
score: 0
type: AnswerComment
has text: Ah, that text file — it's ok with me. I usually don't do it manually — I use virtualenvwrapper's `togglesitepackages` command.
comment on: http://stackoverflow.com/a/48569214
type: Comment

http://stackoverflow.com/q/48608501
answer count: 2
has comment: http://stackoverflow.com/comment/102361548
type: UnansweredQuestion
downvote count: 0
tagged with: neural-network
score: 6
tagged with: machine-learning
tagged with: keras
favorite count: 0
has body: I want to try to implement the neural network architecture of the attached image: 1DCNN_model Consider that I've got a dataset X which is (N_signals, 1500, 40) where 40 is the number of features where I want to do the 1d convolution on. My Y is (N_signals, 1500, 2) and I'm working with keras. Every 1d convolution needs to take one feature vector like in this picture:1DCNN_convolution So it has to take one chunk of the 1500 timesamples, pass it through the 1d convolutional layer (sliding along time-axis) then feed all the output features to the LSTM layer. I tried to implement the first convolutional part with this code but I'm not sure what it's doing, I can't understand how it can take in one chunk at a time (maybe I need to preprocess my input data before?): input_shape = (None, 40) model_input = Input(input_shape, name = 'input') layer = model_input convs = [] for i in range(n_chunks): conv = Conv1D(filters = 40, kernel_size = 10, padding = 'valid', activation = 'relu')(layer) conv = BatchNormalization(axis = 2)(conv) pool = MaxPooling1D(40)(conv) pool = Dropout(0.3)(pool) convs.append(pool) out = Merge(mode = 'concat')(convs) conv_model = Model(input = layer, output = out) Any advice? Thank you very much
has title: 1d CNN audio in keras
tagged with: deep-learning
has answer: http://stackoverflow.com/a/48619440
tagged with: python
upvote count: 6
type: Question
has answer: http://stackoverflow.com/a/48791576

http://stackoverflow.com/comment/84170617
comment on: http://stackoverflow.com/a/48581193
score: 0
has text: see screenshot at link:: https://i.sstatic.net/g89q0.jpg requiements didnt help,please do help.If you need to know anything else,please let me know. Thanks
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48630908
answer count: 3
score: 0
has answer: http://stackoverflow.com/a/48630973
has body: I have a model field called close_date models.py class Project(models.Model): close_date = models.DateTimeField(blank=True, null=True) In my forms, I don't do add any classes to display this because I will do it in my template using django-widget-tweaks. However, my forms look like this: forms.py class NewProjectForm (ModelForm): class Meta: model = Project fields = ['close_date', ...] templates {% load widget_tweaks %} {{project_form.close_date.label}} {% render_field project_form.close_date class="form-control" type="text" %} All this works fine, I can display the form, save it to the database and even display data to the user, but when I want to edit the this object and I populate the form from my views, I see this in the datepicker input field: 2018-02-28 00:00:00 How can I change what is displayed there from 2018-02-28 00:00:00 to 02/28/2018? Is that on the django side of things or the JS side?
has answer: http://stackoverflow.com/a/48630968
type: Question
tagged with: datepicker
accepted answer: http://stackoverflow.com/a/48633975
tagged with: django
tagged with: javascript
tagged with: python
tagged with: jquery
possible better answer: http://stackoverflow.com/a/48630968
has answer: http://stackoverflow.com/a/48633975
has title: How to change Django datetime field format in datepicker?
type: AnsweredQuestion

http://stackoverflow.com/a/48605900
has comment: http://stackoverflow.com/comment/84208532
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84208087
has comment: http://stackoverflow.com/comment/84208237
accepted answer of: http://stackoverflow.com/q/48605830
has comment: http://stackoverflow.com/comment/84208211
has comment: http://stackoverflow.com/comment/84208636
answers question: http://stackoverflow.com/q/48605830
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84208375
has comment: http://stackoverflow.com/comment/84208572
has body: Why not store the account as a tuple since you know there would be two values. This can be achieved by zip and range. zip would produce an iterable that would end once the shorter of the two ranges is exhausted. for proxy,idx in zip(proxyData, range(0,len(userData), 2)): user1, user2 = userData[idx], userData[idx + 1] proxy['account'] = user1, user2
type: AcceptedAnswer

http://stackoverflow.com/comment/84057785
score: 0
comment on: http://stackoverflow.com/a/48531000
type: Comment
has text: @MCM it is less clear to me. There is no "result array" in your question, because `calc_funct(x, y, z)` returns a scalar. Since you're iterating through the DF by row, there is no array.
type: AnswerComment

http://stackoverflow.com/a/48623073
has body: subprocess.call() executes the given command and returns the command's return code (0 => ok, anything else is an error). The interactive Python shell (whether embedded in your IDE or not) displays the stdout and stderr streams of the command as well as the return code, but this is only an artifact of the interactive Python shell - as you noticed this will not print anything to stdout if you run the same code as a script. Here you want to use subprocess.check_output() instead, which will return the command's output as a string. Then you need to explicitely print this string to your python's process stdout: import subprocess if __name__ == "__main__": found = subprocess.check_output(["which", "jupyter"]) print(found)
has comment: http://stackoverflow.com/comment/84244478
answers question: http://stackoverflow.com/q/48622006
type: Answer
has comment: http://stackoverflow.com/comment/84243940
score: 0

http://stackoverflow.com/comment/84115677
score: 1
has text: Well, MSE goes down to 1.8 in the first epoch and no longer decreases. It is possible that the network learned everything it could already in epoch 1. At the beginning your validation loss is much better than the training loss so there's something to learn for sure. What is the min-max range of y_train and y_test? What is the MSE with random weights? I'm not sure that you normalize y while I see that you normalize x to range (0,1). If y is something like 2800 (S&P 500) and your input is in range (0,1) then your weights will be extreme.
type: QuestionComment
comment on: http://stackoverflow.com/q/48542473
type: Comment

http://stackoverflow.com/a/48607486
answers question: http://stackoverflow.com/q/48602128
score: 0
has comment: http://stackoverflow.com/comment/84265028
type: Answer
has body: Not a solution to this exact problem but I ran into similar issues when implementing this library : https://github.com/thomaxxl/safrs (sqlalchemy + flask-restful + jsonapi compliant spec). I don't remember exactly how I got around it, but if you try it and serialization doesn't work I can help you resolve it if you open an issue in github

http://stackoverflow.com/a/48593212
has comment: http://stackoverflow.com/comment/88692674
downvote count: 0
has comment: http://stackoverflow.com/comment/88703230
answers question: http://stackoverflow.com/q/48593157
score: 5
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/84188877
has comment: http://stackoverflow.com/comment/88717890
has body: A few thousand columns is still manageable in the context of ML classifiers. Although you'd want to watch out for the curse of dimensionality. That aside, you wouldn't want a get_dummies call to result in a memory blowout, so you could generate a SparseDataFrame instead - v = pd.get_dummies(df.set_index('school').city, sparse=True) v azez6576sebd dsqozbc765aj sqdqsd12887s school 1 1 0 0 2 0 1 0 3 0 0 1 4 1 0 0 type(v) pandas.core.sparse.frame.SparseDataFrame You can generate a sparse matrix using sdf.to_coo - v.to_coo() &lt;4x3 sparse matrix of type '&lt;class 'numpy.uint8'&gt;' with 4 stored elements in COOrdinate format&gt;

http://stackoverflow.com/a/48553964
upvote count: 4
score: 4
has body: I use this function to convert a series to a consistent datetime object in pandas / numpy. It works with both scalars and series. import pandas as pd x = '2018-12-11' pd.to_datetime(x) # Timestamp('2018-12-11 00:00:00')
has comment: http://stackoverflow.com/comment/84104730
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84104674
accepted answer of: http://stackoverflow.com/q/48553847
answers question: http://stackoverflow.com/q/48553847
type: Answer

http://stackoverflow.com/comment/84146397
type: QuestionComment
comment on: http://stackoverflow.com/q/48560723
has text: Solve the problem. Quite tricky. Please find:(https://stackoverflow.com/questions/47966728/how-to-fix-float-object-has-no-attribute-exp)
type: Comment
score: 0

http://stackoverflow.com/q/48572525
answer count: 1
has comment: http://stackoverflow.com/comment/84224250
has comment: http://stackoverflow.com/comment/84416472
has comment: http://stackoverflow.com/comment/84198734
has comment: http://stackoverflow.com/comment/84418605
tagged with: unicode
has comment: http://stackoverflow.com/comment/84183244
type: Question
has comment: http://stackoverflow.com/comment/84222224
has comment: http://stackoverflow.com/comment/84417950
has comment: http://stackoverflow.com/comment/84221500
has comment: http://stackoverflow.com/comment/84416020
has comment: http://stackoverflow.com/comment/84222678
has comment: http://stackoverflow.com/comment/84224272
tagged with: h5py
type: UnansweredQuestion
has body: So, with h5py there is no support for unicode in attributes. It throws the error: TypeError: No conversion path for dtype: dtype(' I have seen the recommended work-around which is to encode the strings before storing like so: (f.attrs['x'] = [a.encode('utf8') for a in mylist]) However, I do not understand how to encode them into strings when storing them in a dictionary. My code is as follows: with sess.as_default(): if vae_checkpoint: print('Restoring VAE checkpoint: %s' % vae_checkpoint) saver.restore(sess, vae_checkpoint) nrof_images = len(image_list) nrof_batches = int(math.ceil(len(image_list) / args.batch_size)) latent_vars = np.zeros((nrof_images, args.latent_var_size)) attributes = np.zeros((nrof_images, nrof_attributes)) for i in range(nrof_batches): start_time = time.time() latent_var_, attribs_, indices_ = sess.run([latent_var, attribs, indices]) latent_vars[indices_,:] = latent_var_ attributes[indices_,:] = attribs_ duration = time.time() - start_time print('Batch %d/%d: %.3f seconds' % (i+1, nrof_batches, duration)) # NOTE: This will print the 'Out of range' warning if the last batch is not full, # as described by https://github.com/tensorflow/tensorflow/issues/8330 # Calculate average change in the latent variable when each attribute changes attribute_vectors = np.zeros((nrof_attributes, args.latent_var_size), np.float32) for i in range(nrof_attributes): pos_idx = np.argwhere(attributes[:,i]==1)[:,0] neg_idx = np.argwhere(attributes[:,i]==-1)[:,0] pos_avg = np.mean(latent_vars[pos_idx,:], 0) neg_avg = np.mean(latent_vars[neg_idx,:], 0) attribute_vectors[i,:] = pos_avg - neg_avg &gt; filename = os.path.expanduser(args.output_filename) &gt; print('Writing attribute vectors, latent variables and attributes to %s' % filename) &gt; mdict = {'latent_vars':latent_vars, 'attributes':attributes, &gt; 'fields':fields, 'attribute_vectors':attribute_vectors } &gt; with h5py.File(filename, 'w') as f: &gt; for key, value in iteritems(mdict): &gt; f.create_dataset(ke…
has answer: http://stackoverflow.com/a/48709967
tagged with: python
has comment: http://stackoverflow.com/comment/84416793
has comment: http://stackoverflow.com/comment/84417062
has comment: http://stackoverflow.com/comment/84199865
has title: H5py Unicode support for dictionaries
has comment: http://stackoverflow.com/comment/84142175
has comment: http://stackoverflow.com/comment/84145904
score: 0
has comment: http://stackoverflow.com/comment/84200416
has comment: http://stackoverflow.com/comment/84198449
has comment: http://stackoverflow.com/comment/84399265
has comment: http://stackoverflow.com/comment/84177239

http://stackoverflow.com/a/48577830
score: 2
answers question: http://stackoverflow.com/q/48577014
upvote count: 3
type: AcceptedAnswer
downvote count: 1
type: Answer
has body: In your case, x is a 2x2x4 tensor. So when you do x[0] you obtain the 2x4 tensor which is in the first row. And if you do x[i,j] you obtain the 4 dimensional vector in position (i,j). If you want to retain one of the dimensions you can either use a slice: x[i,j:j+1] OR reshape the tensor: x[i,j].view(1,4). Thus your code would look like: import torch from torch.autograd import Variable t = torch.rand((2,2,4)) x = Variable(t) print(x) shape = x.size() for i in range(shape[0]): for j in range(shape[1]): print(x[i,j:j+1]) or import torch from torch.autograd import Variable t = torch.rand((2,2,4)) x = Variable(t) print(x) shape = x.size() for i in range(shape[0]): for j in range(shape[1]): print(x[i,j].view(1,4) Will give you the desired result. Edit: Yes, or as mentioned in the answer by nnnmmm, torch.unsqueeze(x[i, j], 0) also works as it adds a dimension of size 1 in the 0th position.
accepted answer of: http://stackoverflow.com/q/48577014

http://stackoverflow.com/q/48607396
has answer: http://stackoverflow.com/a/48607686
upvote count: 2
has answer: http://stackoverflow.com/a/69062840
has answer: http://stackoverflow.com/a/75024764
has title: Find complement of number in Python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70296474
downvote count: 2
answer count: 7
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48607617
score: 0
has comment: http://stackoverflow.com/comment/84211069
linked to: http://stackoverflow.com/q/70246943
has answer: http://stackoverflow.com/a/48607532
has answer: http://stackoverflow.com/a/48607506
tagged with: python
has comment: http://stackoverflow.com/comment/84211789
tagged with: python-3.x
has body: I am trying to find the complement of a number in Python. I know there are other solutions but I am trying to make my own. My first try: def findComplement(self, num): """ :type num: int :rtype: int """ numb = str(num) i = 0 while(i&lt;=len(numb)): if numb[i] == "0": numb[i] = "1" else: numb[i] = "0" i=i+1 return int(numb) But strings are immutable so it gave an error, My second try: def findComplement(self, num): """ :type num: int :rtype: int """ numb = str(num) numb2 = [] k =0 for j in numb: numb2[k] = j #error on this line k=k+1 i = 0 while(i&lt;=len(numb2)): if numb2[i] == "0": numb2[i] = "1" else: numb2[i] = "0" i=i+1 return int(numb2) Error in program 2: Line 11: IndexError: list assignment index out of range

http://stackoverflow.com/comment/84060022
type: AnswerComment
has text: You have to roll back...because the other edit should remain in the question...otherwise all the comments can't be followed. And this what you added a minute ago should be marked as edit2.
comment on: http://stackoverflow.com/a/48531455
score: 0
type: Comment

http://stackoverflow.com/comment/84289704
has text: thank you for the explanation... btw. can anyone explain how sys.<argument> get's filled in typically? are these system variables?
comment on: http://stackoverflow.com/q/48633070
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48634578
type: Answer
has body: df[df['Loc'].str.contains('some')]
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48634528

http://stackoverflow.com/q/48644744
has body: I have launched an app on Heroku running Django 2.0.1 with a Postgres resource provisioned. My Procfile, after a few iterations, looks like this: Procfile release: python manage.py migrate --noinput web: gunicorn app.wsgi --log-file - When I deploy from GitHub (not from the command line... I haven't deployed from the command line before as it is critical to me that the GitHub deploy works) everything works fine. The migrations run like they should, and the logs confirm that there are no errors when migrating. In fact, there are no errors deploying to Heroku at all. When I launch the site (forcing it into DEBUG mode to see the errors) I get this error on the front page: ProgrammingError at / relation "posts_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "posts_post" INNER JOIN "u... A similar error exists when trying to load the admin site: ProgrammingError at /admin/login/ relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ I followed the advice in Django: relation "django_site" does not exist to migrate sites first, but that did nothing. Also, this issue on GitHub is related, but was not helpful. To clarify, the app is accessible. The Heroku deploy does not fail. The app is just erroring out. Traceback (partial) Environment: Request Method: GET Request URL: https://somesite.herokuapp.com/ Django Version: 2.0.1 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'accounts.apps.AccountsConfig', 'analytics.apps.AnalyticsConfig', 'api_v1.apps.ApiV1Config', 'api_v2.apps.ApiV2Config', 'meta.apps.MetaConfig', 'posts.apps.PostsConfig', 'users.apps.UsersConfig', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework'] Installed Middleware: ['django.…
favorite count: 0
type: Question
tagged with: heroku
tagged with: postgresql
score: 5
has title: Heroku and Django - relation does not exist
type: UnansweredQuestion
upvote count: 5
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/23925726
has answer: http://stackoverflow.com/a/67036663
has comment: http://stackoverflow.com/comment/84292019
has comment: http://stackoverflow.com/comment/117328712
has comment: http://stackoverflow.com/comment/84302463
has comment: http://stackoverflow.com/comment/128367899
downvote count: 0
has comment: http://stackoverflow.com/comment/109640643
answer count: 1

http://stackoverflow.com/comment/84008975
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48506985
score: 0
has text: @jonathan.scholbach im pretty sure hes using python3 ...

http://stackoverflow.com/a/48511427
has comment: http://stackoverflow.com/comment/84045763
has body: The problem can be in the data transfer to the child processes. When read-only objects must be used I prefer to exploit the copy-on-write mechanism used by the underlying OS to manage the memory of the child processes. However, I don't know if windows 7 uses this mechanism. When copy-on-write is available, you can access area of the parent process without copying them inside the child process. This trick works only if you access them in a read-only way and if the object is created before the creation of the processes. Summing up, a possible solution (at least for linux machines) is this: import multiprocessing as mp import numpy as np def funcA(): print "A {}".format(X.shape) # do something with the global variable X print 'funcA OK' def funcB(): print "B {}".format(X.shape) # do something else with the global variable X print 'funcB OK' if __name__=='__main__': X=np.random.rand(int(5.00e8),) funcA() # OK funcB() # OK X=np.random.rand(int(2.65e8),) P=[mp.Process(target=funcA), mp.Process(target=funcB)] for p in P: p.start() for p in P: p.join() X=np.random.rand(int(2.70e8),) P=[mp.Process(target=funcA), mp.Process(target=funcB)] for p in P: p.start() for p in P: p.join() UPDATE: after various comments about compatibility problems with Windows, I sketched a new solution uniquely based on native memory maps. In this solution I am creating a numpy memory map on file, which is shared through the file descriptor, thus it doens't require to copy the whole array inside the childs. I found this solution much faster than using multiprocessing.Array! UPDATE2: The code below has been updated to avoid memory issues during the randomisation of the memory map. import multiprocessing as mp import numpy as np import tempfile def funcA(X): print "A {}".format(X.shape) # do something with X print 'funcA OK' def funcB(X): print "B {}".format(X.shape) # do something else with X print 'funcB OK' if __name__=='__main__': dim = int(2.75e8) with tempfile.NamedTemporaryFile(dir='/tmp', dele…
has comment: http://stackoverflow.com/comment/84017889
has comment: http://stackoverflow.com/comment/84052216
has comment: http://stackoverflow.com/comment/84017899
answers question: http://stackoverflow.com/q/48511247
has comment: http://stackoverflow.com/comment/84043023
has comment: http://stackoverflow.com/comment/84017965
has comment: http://stackoverflow.com/comment/84017734
has comment: http://stackoverflow.com/comment/84089873
type: Answer
has comment: http://stackoverflow.com/comment/84017934
has comment: http://stackoverflow.com/comment/84017788
has comment: http://stackoverflow.com/comment/84017841
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/84116969
type: Comment
comment on: http://stackoverflow.com/q/48560425
score: 0
has text: I think the request.method will be POST if you use a form to submit?
type: QuestionComment

http://stackoverflow.com/q/48556287
has comment: http://stackoverflow.com/comment/84109036
tagged with: http://stackoverflow.com/tag/csv
score: 0
answer count: 1
tagged with: formatting
has comment: http://stackoverflow.com/comment/84108771
has body: I have a csv file of subjects XY Coordinates. Some XY's have been removed if the X-Coordinate is less than 5. This can be for any player and changes over time. (See example dataset). At the start of this file P2, P7, P12, P17 have removed data. Although, throughout the file each player will have data missing. for about 90% of the file there will be at least 4 players having missing data at any time point. Frame Time P1_X P2_Y P2_X P2_Y P3_X P3_Y P4_X P4_Y P5_X P5_Y P6_X P6_Y P7_X P7_Y P8_X P8_Y P9_X P9_Y P10_X P10_Y P11_X P11_Y P12_X P12_Y 0 10:39.2 65.75 45.10 73.74 -3.52 61.91 41.80 67.07 -24.62 77.14 -22.98 93.95 3.51 56.52 28.44 70.21 11.06 73.08 -35.54 69.79 45.73 73.34 29.26 64.73 -40.69 70.90 6.11 70.94 -45.11 42.78 3.00 61.77 -1.05 72.07 38.62 1 10:39.3 65.77 45.16 73.69 -3.35 61.70 41.79 67.19 -24.59 77.17 -23.03 93.90 3.53 56.54 28.38 70.20 11.00 73.15 -35.48 69.79 45.86 73.20 29.30 64.96 -40.77 70.91 6.10 71.04 -45.29 42.84 3.02 61.82 -0.99 72.12 38.71 2 10:39.4 65.78 45.24 73.63 -3.17 61.70 41.79 67.32 -24.56 77.20 -23.05 93.83 3.55 56.59 28.31 70.20 10.92 73.20 -35.41 69.79 45.86 73.03 29.36 65.19 -40.84 70.91 6.10 71.15 -45.50 42.91 3.04 61.89 -0.91 72.16 38.80 3 10:39.5 65.78 45.33 73.57 -3.00 61.49 41.78 67.45 -24.50 77.25 -23.07 93.75 3.57 56.59 28.31 70.21 10.83 73.25 -35.33 69.77 46.01 72.86 29.43 65.45 -40.86 70.90 6.09 71.15 -45.50 43.01 3.08 61.98 -0.81 72.19 38.86 4 10:39.6 65.78 45.33 73.51 -2.86 61.32 41.76 67.45 -24.50 77.31 -23.09 93.64 3.60 56.65 28.22 70.23 10.72 73.29 -35.22 69.72 46.17 72.69 29.51 65.75 -40.84 70.88 6.08 71.24 -45.71 43.11 3.12 62.06 -0.70 72.22 38.90 5 10:39.7 65.75 45.44 73.51 -2.86 61.20 41.73 67.59 -24.37 77.38 -23.10 93.52 3.63 56.73 28.09 70.25 10.59 73.29 -35.22 69.68 46.33 72.49 29.60 66.06 -40.84 70.86 6.05 71.31 -45.91 43.22 3.14 62.13 -0.59 72.26 38.92 6 10:39.8 65.72 45.56 73.45 -2.72 61.08 41.71 67.72 -24.19 77.44 -23.12 93.39 3.69 56.80 27.91 70.27 10.45 73.34 -35.08 69.66 46.48 72.27 29.67 66.36 -40.87 7…
type: Question
has comment: http://stackoverflow.com/comment/84110677
has comment: http://stackoverflow.com/comment/84109337
has comment: http://stackoverflow.com/comment/84108735
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84110179
tagged with: python
has title: Remove values when reading a csv and return to a list
has comment: http://stackoverflow.com/comment/84108707
has answer: http://stackoverflow.com/a/48556460
has comment: http://stackoverflow.com/comment/84108738
tagged with: list

http://stackoverflow.com/comment/84295966
has text: @mitch I wasn't talking to you, so I'm not sure what you mean. However, I'm glad you got a resolution.
type: AnswerComment
comment on: http://stackoverflow.com/a/48627523
score: 0
type: Comment

http://stackoverflow.com/q/48527619
accepted answer: http://stackoverflow.com/a/48527728
has body: I'm trying to modify a function which uses a module-level variable variable defined below it, similar to this: def say_hello(): print(MESSAGE) MESSAGE = "Hello, world!" say_hello() I would like to make the message a parameter, like so: MESSAGE = "Hello, world!" def say_hello(message=MESSAGE): print(message) say_hello() I've noticed that in order for this to work, I had to move the definition of MESSAGE up in the code. Apparently, all module-levels are first 'bound' and are then available within function bodies, but when provided as default function arguments, they have to be defined before the function. Is this correct? (I would also like to read up on this to fully understand it; any references would be much appreciated).
has answer: http://stackoverflow.com/a/48527728
type: AnsweredQuestion
score: 3
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48527961
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48527772
has title: Order of binding of variables in Python
has answer: http://stackoverflow.com/a/48527772
tagged with: python

http://stackoverflow.com/a/48578300
accepted answer of: http://stackoverflow.com/q/48578039
score: 8
has comment: http://stackoverflow.com/comment/84161679
answers question: http://stackoverflow.com/q/48578039
type: AcceptedAnswer
downvote count: 0
upvote count: 8
type: Answer
has body: You can do what you want with specifying sharey='row', as shown in this matplotlib demo. Here bit of code to show hot to do this: from matplotlib import pyplot as plt import numpy as np x1 = np.linspace(0,2*np.pi,100) x2 = np.linspace(-1,1,100) f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey='row') ax1.plot(x1, np.sin(x1)) ax1.set_title('sin(x)') ax2.plot(x1, 2*np.cos(x1)+1) ax2.set_title('2*cos(x)+1') ax3.plot(x2, np.sqrt(np.abs(x2))) ax3.set_title('sqrt(abs(x))') ax4.plot(x2, x2**3) ax4.set_title('x**3') f.tight_layout() plt.show() This gives the following result:

http://stackoverflow.com/comment/84238544
type: Comment
type: QuestionComment
has text: Hi, your question is not very well formulated. What do you mean by "the values correspond to a pixel within an area are not same (values are changing between [0,1])" ?
comment on: http://stackoverflow.com/q/48617874
score: 0

http://stackoverflow.com/q/48527100
linked to: http://stackoverflow.com/q/1157106
tagged with: arrays
has comment: http://stackoverflow.com/comment/84050678
has comment: http://stackoverflow.com/comment/84062422
type: Question
has comment: http://stackoverflow.com/comment/84062401
has title: How to delete an element from an array which has alphabetic values in python
has comment: http://stackoverflow.com/comment/84070974
has body: I have an Array which has values ['a','b','e','d','f','e'] First Question: How to delete element e from this array? Second Question: What if i want to copy all the elements between the two e elements?
has comment: http://stackoverflow.com/comment/84049211
has comment: http://stackoverflow.com/comment/84049415
has comment: http://stackoverflow.com/comment/84050092
tagged with: python
has comment: http://stackoverflow.com/comment/84049241
has comment: http://stackoverflow.com/comment/84049232
duplicate of: http://stackoverflow.com/q/1157106
tagged with: arraylist
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84049440
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48613796
has body: The code row=row.split(",") sets the row variable to something like ['0.000000', '', '0.000000', '', '0.000000']. Your code is giving index error because there are no index 2 from the string ''. There are 2 ways of doing this: My idea is to remove those annoying empty strings in the array by changing your row=row.split(",") to row=row.split(",,"), this will work perfectly. Change your data=data.replace(" ", ",") to data=data.replace(" ", ",") (two whitespaces), that will also work perfectly.
has comment: http://stackoverflow.com/comment/84224955
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84224681
answers question: http://stackoverflow.com/q/48613584
has comment: http://stackoverflow.com/comment/84224730
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84233964
comment on: http://stackoverflow.com/q/48618586
type: Comment
type: QuestionComment
score: 0
has text: @Elmex80s, that's a good idea. how about the Pandas way?

http://stackoverflow.com/comment/83986902
comment on: http://stackoverflow.com/a/48496707
type: AnswerComment
score: 1
type: Comment
has text: you should explain better in your questions XD!

http://stackoverflow.com/q/48579152
possible better answer: http://stackoverflow.com/a/48579338
has body: I need to add a commandline parameter to a python file (I don't have functions defined inside) so that the parameter would be platform, and then inside the file I need to use: if platform == iphone: &lt;execute some code&gt; elif platform == ipad: &lt;execute some other code&gt; Basically whats defined under if and elif is the same code but using different resources (images, txt files, etc.). What I need is the possibility to run that file from commandline with the platform parameter like: python somefile.py -iphone Now I tried with argparse like that: platform = argparse.ArgumentParser() platform.add_argument("iphone") platform.add_argument("ipad") platform.parse_args() But clearly it is wrong and/or is missing something because it doesn't work at all. I'm looking for a simplest possible way to achieve that.
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48579285
tagged with: argparse
has comment: http://stackoverflow.com/comment/84154599
tagged with: command-line-arguments
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/48579338
accepted answer: http://stackoverflow.com/a/48579285
tagged with: python
linked to: http://stackoverflow.com/q/15008758
has comment: http://stackoverflow.com/comment/84154960
tagged with: execution
has title: Adding custom commandline parameters to run if elif in python

http://stackoverflow.com/comment/84123882
has text: Should you be able to *query* on `y`?
comment on: http://stackoverflow.com/q/48564067
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48489339
has answer: http://stackoverflow.com/a/48490193
has title: Scikit-Learn Pipeline: How to Handle Preprocessing
upvote count: 1
tagged with: scikit-learn
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/90931614
score: 0
answer count: 1
favorite count: 0
type: Question
has body: I'm doing some machine learning practice on Kaggle and I'm beginning to use the sklearn.pipeline.Pipeline class to transform my data several times and then train a model on it. I want to encapsulate several parts of pre-processing my data: dropping rows with 30% or more NaNs, dropping columns with 30% or more NaNs, amongst other things. Here's the start of my attempt at a custom Transformer: class NanHandler(BaseEstimator, TransformerMixin): def __init__(self, target_col, row_threshold=0.7, col_threshold=0.7): self.target_col = target_col self.row_threshold = row_threshold self.col_threshold = col_threshold def transform(self, X): # drop rows and columns with &gt;= 30% NaN values def fit(self, *_): return self However, I want to use this Transformer with k-fold cross-validation. I'm concerned that if I do 3-fold cross-validation, it's unlikely (but possible) that I run into the following situation: Train on folds 1 and 2, test on 3 Train on folds 2 and 3, test on 1 Train on folds 1 and 3, test on 2 Folds 1 and 2 combined may have over 30% Nans in a specific column (call it colA). So my NanHandler will drop this column before training. However, folds 2 and 3 combined may have less than 30% NaNs and so it won't drop colA, resulting my model being trained on different columns than the first pass. 1) How should I handle this situation? 2) Is this also a problem if I want to drop rows that have 30% ore more NaN values (in that I'll train on a different number of rows during k-fold cross-validation)? Thanks!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84024387

http://stackoverflow.com/comment/84179983
comment on: http://stackoverflow.com/q/48590321
type: Comment
has text: You identified the problem neatly: this is *post*-processing, but you're wanting to do it while you're still within the initial processing loop. At best, you can check between the loops to see whether the box you just identified aligns with any previous one.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84097576
score: 0
type: Comment
has text: `pip install dir/` where `dir` contains `setup.py`?
type: QuestionComment
comment on: http://stackoverflow.com/q/48550546

http://stackoverflow.com/comment/84141804
comment on: http://stackoverflow.com/q/48570520
has text: SMTPDataError: (550, '5.7.1 Client does not have permissions to send as this sender')
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48489931
has comment: http://stackoverflow.com/comment/100087933
upvote count: 3
has comment: http://stackoverflow.com/comment/125515929
downvote count: 0
has body: You could use the HYPERLINK function built into pandas import pandas as pd df = pd.DataFrame({'link':['=HYPERLINK("http://www.someurl.com", "some website")']}) df.to_excel('mohammad-rocks.xlsx')
has comment: http://stackoverflow.com/comment/83975205
answers question: http://stackoverflow.com/q/48489893
has comment: http://stackoverflow.com/comment/83973928
has comment: http://stackoverflow.com/comment/124061439
score: 3
has comment: http://stackoverflow.com/comment/83975343
has comment: http://stackoverflow.com/comment/83972847
type: Answer

http://stackoverflow.com/q/48490964
answer count: 1
downvote count: 1
tagged with: celery
favorite count: 0
accepted answer: http://stackoverflow.com/a/48491153
has body: How can I prevent the execution of two or more identical tasks at the same time? For example: if I have a task called do_stuff and a program calling it, it should only get executed if there is no other instance of do_stuff that is currently running.
type: Question
has answer: http://stackoverflow.com/a/48491153
has title: Python + Celery: Prevent duplicate task execution
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83975076
upvote count: 3

http://stackoverflow.com/q/48517060
score: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/84028898
type: Question
has body: I have two tables T1 and T2 in csv format. Both T1 and T2 contain certain data about ships on the North Sea. T1 contains dynamic data for several ships, i.e. the data changes over time (like position, speed and so on). T2 contains exactly one entry per ship (with length, width, ID and so on), called the static data. Both T1 and T2 have an "ID" column, which I want to exploit for concatenating the tables in a certain way: I want to append the static data columns from T2 to every entry in T1 that has the same ID. I read that astropy has some fancy table operations but couldn´t figure out a way to do this. Any ideas? Thanks!
answer count: 0
type: UnansweredQuestion
has title: Concatenate tables in Python
has comment: http://stackoverflow.com/comment/84028884
tagged with: python

http://stackoverflow.com/q/48556211
has comment: http://stackoverflow.com/comment/84203163
has comment: http://stackoverflow.com/comment/84109546
tagged with: vba
has comment: http://stackoverflow.com/comment/84108575
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84109310
has answer: http://stackoverflow.com/a/48557293
has body: I'm trying to figure out the most efficient way to use IF statements in excel. I know what I want my code to look like if it was say, Python, but I'm struggling with it in excel. Heres the code I have in excel, and it works and does what I want: =IFS((AND(B4="Fall", C4="Triple")), 2190, (AND(B4="Fall", C4="Double")), 2731, (AND(B4="Fall", C4="Single")), 3175, AND(B4="Winter", C4="Triple"), 1902, AND(B4="Winter", C4="Double"), 2372, AND(B4="Winter", C4="Single"), 2757, AND(B4="Spring", C4="Triple"), 1671, AND(B4="Spring", C4="Double"), 2084, AND(B4="Spring", C4="Single"), 2423, ISBLANK(B4), "Pick A quarter", ISBLANK(C4), "Pick A dorm style") As you can see, There is lots of stuff that is repeated and is unnecessary. It makes it hard to read, and long to type. Especially since I have to do essentially the same thing with very slight changes to the second parameter in the AND() statements and the results. Here is what I would like the code to be equivalent to. B4 = "Fall" C4 = "Double" if (B4=="Fall"): if (C4 == "Triple"): print(2190) if (C4 == "Double"): print(2731) if (C4 == "Single"): print(3175) elif (B4 == "Winter"): if (C4 == "Triple"): print(1902) if (C4 == "Double"): print(2372) if (C4 == "Single"): print(2757) elif (B4 == "Spring"): if (C4 == "Triple"): print(1671) if (C4 == "Double"): print(2084) if (C4 == "Single"): print(2423) else: print("...") Now admittedly, this code still isn't great and it seems like there would be a much better, shorter more efficient way to write this out. But it gets the point across. (If there was a way to create this in python and change excel cells from python code, that'd be cool to). Anyone have some ideas?
answer count: 4
has title: Using IF, AND, and OR statements to not repeat code in Excel
type: Question
has comment: http://stackoverflow.com/comment/84108864
has answer: http://stackoverflow.com/a/48557826
downvote count: 0
has comment: http://stackoverflow.com/comment/84109014
upvote count: 1
has comment: http://stackoverflow.com/comment/84108601
accepted answer: http://stackoverflow.com/a/48556517
possible better answer: http://stackoverflow.com/a/48556856
tagged with: python
has answer: http://stackoverflow.com/a/48556517
tagged with: excel
has answer: http://stackoverflow.com/a/48556856
has comment: http://stackoverflow.com/comment/84108544
has comment: http://stackoverflow.com/comment/84109214
type: AnsweredQuestion

http://stackoverflow.com/comment/84125478
comment on: http://stackoverflow.com/q/48564743
score: 0
type: Comment
has text: Why do you call these strings 'variances'?
type: QuestionComment

http://stackoverflow.com/q/48524758
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48526754
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: io
tagged with: python
has body: I'm trying to understand subprocess.Popen and subprocess.PIPE. While doing so, I created three small scripts. The goal of this exercise is, to print data with one script, read it from the other and echo this back to the first script. The problem is, that the last sys.stdin.read() prevents the entire code from working properly. test.py #!/usr/bin/python3 from subprocess import Popen, PIPE proc1 = Popen(["python3","script1.py"], stdin=PIPE, stdout=PIPE) proc2 = Popen(["python3","script2.py"], stdin=PIPE, stdout=PIPE) first_output = proc1.stdout.read() print("[test.py:] " + str(first_output)) proc2.stdin.write(first_output) proc2.stdin.flush() proc2.stdin.close() answer = proc2.stdout.read() print("[test.py:] " + str(answer)) proc1.stdin.write(answer) script1.py import sys sys.stdout.write("Hello world") sys.stdout.flush() answer = str(sys.stdin.read()) The last line in script1.py answer = str(sys.stdin.read()) causes the entire program to get stuck. If I comment it out, everything works fine. Why is that so and why am I not able to communicate any further? I didn't find an answer yet. script2.py import sys input_read = str(sys.stdin.read()) sys.stdout.write("[script2.py:] " + input_read + " input read") sys.stdout.flush()
type: Question
accepted answer: http://stackoverflow.com/a/48526754
has comment: http://stackoverflow.com/comment/84051711
tagged with: python-3.x
downvote count: 0
has title: sys.stdin.read() in subprocess never returning
has comment: http://stackoverflow.com/comment/84051246

http://stackoverflow.com/comment/84177418
has text: @Bee, based on your latest comment I see that much of this is not applicable to your problem. Does this make sense to you or would you like further clarification?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48590081
type: Comment

http://stackoverflow.com/comment/84194717
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48599095
type: Comment
has text: Welcome to Stack Overflow. We can help you if you ask a specific question and provide more detail. What happens when you run your code? What do you want it to do differently?

http://stackoverflow.com/comment/84224020
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48612579
type: AnswerComment
has text: yes, printing between numba functions does not work because environment pointers are not passed between them.

rx-py
tag name: rx-py
type: Tag
tags question: http://stackoverflow.com/q/48612791

http://stackoverflow.com/q/48603455
type: Question
has comment: http://stackoverflow.com/comment/84203587
has comment: http://stackoverflow.com/comment/84203611
has comment: http://stackoverflow.com/comment/84203659
upvote count: 2
has body: I am reading some values in from a csv file and converting those values to a list with the following code. The csv file is just one row, of around 2000 values that are either a "1" or a "0". With the code I am trying to count how many of the number of "1"'s there are in the csv file. def countX(a, x): count = 0 for ele in a: if (ele == x): count = count + 1 return count def countX(a, x): return a.count(x) with open(my_file_name, 'r') as in1file: mylist = [row[0] for row in csv.reader(in1file, delimiter=';')] print (mylist) a = [mylist] x = 1 countX print(countX(a, x)) The issue I have is that "my list" returns something like ['0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0'] So when I interrogate my list to count the tally of "1"'s, I am always getting the value 0 for some reason. If i just create a list and make a = [1,1,1,1,1,1,0,0] I will get a counted value of 6. How can I make this work so I get the number of 1's counted from my csv file?
has answer: http://stackoverflow.com/a/48603559
answer count: 5
has comment: http://stackoverflow.com/comment/84203607
downvote count: 0
tagged with: count
tagged with: python
has answer: http://stackoverflow.com/a/48603537
has comment: http://stackoverflow.com/comment/84203646
has answer: http://stackoverflow.com/a/48603523
possible better answer: http://stackoverflow.com/a/48603502
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48603621
has comment: http://stackoverflow.com/comment/84203619
tagged with: list
has answer: http://stackoverflow.com/a/48603502
tagged with: http://stackoverflow.com/tag/csv
has title: csv to list and analyze python
accepted answer: http://stackoverflow.com/a/48603621
favorite count: 0

http://stackoverflow.com/a/67392715
type: Answer
answers question: http://stackoverflow.com/q/48613466
score: 0
has body: You can't write anything directly you can write a=|this|is | b=------------ c=|a |table| print(a) print(b) print(c)

http://stackoverflow.com/a/48555194
has body: If you want to run a function when a mock is called, that's side_effect, not return_value: MyClass.method_one.side_effect = my_mock_gen
type: Answer
score: 4
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48546000
downvote count: 0
answers question: http://stackoverflow.com/q/48546000
has comment: http://stackoverflow.com/comment/84106997
has comment: http://stackoverflow.com/comment/84125334

http://stackoverflow.com/comment/84118462
type: Comment
has text: sorry for my mistake, I upload a picture of my gui , there are 1200 lists (600 Temples + 600 Samples) like `control_type="Header"` in the grid (like the picture shows), in this situation, I got the ElementNotFound error, but when I delete all list in my gui, the code can run well
type: QuestionComment
comment on: http://stackoverflow.com/q/48559538
score: 0

http://stackoverflow.com/comment/83977398
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48489402
type: Comment
has text: thank you so much! the problem is solved but I got another error: now when I open the file I get a bunch of strange symbols and not the text it actually contained, do I have to use some encode/decode function? I'm sorry to bother all of you with questions that could be silly for you but I can't make this program work even if I have been trying all day.

http://stackoverflow.com/a/48571665
has comment: http://stackoverflow.com/comment/84140141
type: Answer
has comment: http://stackoverflow.com/comment/84140334
answers question: http://stackoverflow.com/q/48570481
has comment: http://stackoverflow.com/comment/84141947
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84140452
upvote count: 1
has body: Borrowing @Scratch'N'Purr's code, here's my solution: import numpy as np import pandas as pd df = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': [11, 22, '-', 44], 'col3': ['-', 3, 5, 7]}) df: col1 col2 col3 0 1 11 - 1 2 22 3 2 3 - 5 3 4 44 7 df.replace(to_replace = '-', value = np.nan, inplace = True) df = df.astype(float) # added after OP feedback Output: col1 col2 col3 0 1 11.0 NaN 1 2 22.0 3.0 2 3 NaN 5.0 3 4 44.0 7.0 Plot: import matplotlib.pyplot as plt df.plot() plt.show() I did not look at the data closely; does this solution plot the way you'd hoped? Second, going from int to float is computationally expensive, but works well enough for small enough data sets. Edit: See pandas DataFrame "no numeric data to plot" error In order to plot NaN's, convert to float. The above (edited) code generated PNG images a through hh, based on OP's updated post.

http://stackoverflow.com/q/48502854
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84006164
has title: Failling to load weights on my tensorflow model
tagged with: python
tagged with: deep-learning
answer count: 0
has comment: http://stackoverflow.com/comment/84039575
type: UnansweredQuestion
has body: I've implemented and trained a resnet model on tensorflow. I saved it that way : save_path=saver.save(sess,"/home/.../model.ckpt",global_step=50) saver.save(sess,"/home/s.../model.ckpt",global_step=50) On an other script I try to load it and to test it on some images. My script is build like this: files = [s for s in os.listdir(dossier_source+'/'+d) if s.endswith(".png") or(".jpeg")] print files.__len__() batch_size_arg=files.__len__() x = tf.placeholder(tf.float32, [None,IMAGE_WIDTH,IMAGE_HEIGHT,NUMBER_OF_CHANNELS], name='x-input') y = tf.placeholder(tf.int32, [None], name='y-input') train_file =str(dossier_source+d+"/*.png") I recreate all variables [..] with tf.Session() as sess: sess.run(tf.local_variables_initializer()) saver=tf.train.Saver() saver.restore(sess,tf.train.latest_checkpoint(global_path)) tab= sess.run('conv0/conv:0') print tab[0][0][0] #here is a little test that proves conv0 weights is the same as the ones i get on training for i in xrange(1): im_batch, lab_batch = sess.run([images_batch, labels_batch]) curr=sess.run(accuracy,feed_dict={x: im_batch, y: lab_batch}) top=sess.run(top_k_op ,feed_dict={x: im_batch, y: lab_batch}) conf =sess.run(confusion,feed_dict={x: im_batch, y: lab_batch, }) print "Results" print curr print conf My problem is that even though conv0 show everytime the same weights, the confusion table and the results are different on each test on the very same images.... Am I doing something wrong when i load my weights and model ? EDIT: With the latest tests, i realized that if I do for i in xrange(3): im_batch, lab_batch = sess.run([images_batch, labels_batch]) curr=sess.run(accuracy,feed_dict={x: im_batch, y: lab_batch}) top=sess.run(top_k_op ,feed_dict={x: im_batch, y: lab_batch}) conf =sess.run(confusion,feed_dict={x: im_batch, y: lab_batch, }) print "Results" print curr print conf on the very same batch of 3 images, I get different results aswell.
tagged with: tensorflow

http://stackoverflow.com/a/48551641
has body: This code: listOfLists = [[2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13]] for i in range(len(listOfLists[0])): print('Number',(i+1), end = " ") for i in range(len(listOfLists)): print() for j in listOfLists[i]: print(' ',j, end = (7-len(str(j+1)))*' ') makes output like this: Number 1 Number 2 Number 3 Number 4 Number 5 Number 6 2 3 4 5 6 7 8 9 10 11 12 13
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48539140
answers question: http://stackoverflow.com/q/48539140
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84110118

http://stackoverflow.com/q/48611132
has answer: http://stackoverflow.com/a/48613092
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/48611289
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48611289
has title: Python Pandas groupby or rolling multi year average summary statistics
tagged with: rolling-computation
tagged with: python
type: AnsweredQuestion
has body: I have a pandas time series data frame with approximately 20 rows for for each year, from 2014 to 2017, and I'm trying to calculate the mean value for each two year period. For example: 01/1/2014 ... 31/12/2015, 01/1/2015 ... 31/12/2016, 01/1/2016 ... 31/12/2017 Here is the code I'm using to import the DataFrame: import pandas as pd infile = 'https://environment.data.gov.uk/bwq/downloadAPI/requestDownload?report=samples&amp;bw=ukj2100-14950&amp;to=2018-02-05&amp;from=2014-05-01' df = pd.read_csv(infile,compression='zip',usecols=['intestinalEnterococciCount','sampleTime'], parse_dates=['sampleTime'],infer_datetime_format=True,index_col=['sampleTime'],na_values=True) and an example of the DataFrame: intestinalEnterococciCount sampleTime 2014-05-12 13:00:00 10 2014-05-21 12:27:00 10 2014-05-27 10:55:00 10 2014-06-06 12:19:00 10 2014-06-09 13:26:00 10 I would like to calculate the mean value for each two year period. The expected answers would be: Period Mean Jan 2014 - Dec 2015: 33.575 Jan 2015 - Dec 2016: 22.85 Jan 2016 - Dec 2017: 25.5 What I tried: I know I could use a loop and iterate through a list of the two year periods and calculate it that way, but I’m sure there must be a nicer way to achieve this using Pandas. I tried using .rolling but that appears to give a rolling mean, which increments forward row by row, rather than over two year periods. I can successfully use groupby(df.index.year).mean to get the mean for each year, but how would I go about it for calculating it for each two year period?
answer count: 2
accepted answer: http://stackoverflow.com/a/48613092
linked to: http://stackoverflow.com/q/25695986
tagged with: pandas
tagged with: summary
score: 1

http://stackoverflow.com/a/48632556
accepted answer of: http://stackoverflow.com/q/48632356
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/134087536
downvote count: 0
upvote count: 7
has body: Use a regular expression. There are only a few limits; a tag must start with either # or @, and it may not contain any spaces or other whitespace characters. This code import re tags = [] with open('../Downloads/tags.txt','Ur') as file: for line in f.readline(): tags += re.findall(r'[#@][^\s#@]+', line) creates a list of all tags in the file. You can easily adjust it to store the found tags in your dictionary; instead of storing the result straight away in tags, loop over it and do with each item as you please. The regex is built up from these two custom character classes: [#@] - either the single character # or @ at the start [^\s#@]+ - a sequence of not any single whitespace character (\s matches all whitespace such as space, tab, and returns), #, or @; at least one, and as many as possible. So findall starts matching at the start of any tag and then grabs as much as it can, stopping only when encountering any of the "not" characters. findall returns a list of matching items, which you can immediately add to an existing list, or loop over the found items in turn: for tag in re.findall(r'[#@][^\s#@]+', line): # process "tag" any way you want here The source text file contains Windows-style \r\n line endings, and so I initially got a lot of empty "lines" on my Mac. Opening the text file in Universal newline mode makes sure that is handled transparently by the line reading part of Python.
type: Answer
answers question: http://stackoverflow.com/q/48632356

http://stackoverflow.com/comment/84289077
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48645776
type: Comment
has text: What do you use when you want to read JSON on hadoop ? You do not use sqlContext ?

http://stackoverflow.com/comment/84006164
score: 0
comment on: http://stackoverflow.com/q/48502854
has text: There is a difference of batchnorm in training and inference phase. Not sure, how you implemented it. But when using a `with tf.control_dependencies` for performing the non-gradient updates in the batch-norm layer you'll get different results as the batch-norm statistics changes between different sess.runs.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48570822
has answer: http://stackoverflow.com/a/48570918
tagged with: python
has title: pandas dataframe does not recognize columns
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas
score: 1
has body: So I am trying to add a column to a dataframe and use another column to calculate its value. import pandas as pd import pandasql as pdsql import csv def filter_by_regular(filename): turnstile_data = pd.read_csv(filename) turnstile_data = pd.DataFrame(turnstile_data) q = "SELECT * FROM turnstile_data WHERE 'DESCn == REGULAR';" return turnstile_data turnstile_regular = filter_by_regular('master_file.txt') turnstile_regular.head() turnstile_regular.columns Index([u'C/A', u' UNIT', u' SCP', u' DATEn', u' TIMEn', u' DESCn', u' ENTRIESn', u' EXITSn'], dtype='object') Then when i try to access the ENTRIESn column to use its value to add another column, python does not recognize it. import pandas def get_hourly_entries(df): df['ENTRIESn_hourly'] = df.ENTRIESn.diff(1) df.ENTRIESn_hourly.fillna(1, inplace = True) return df turnstile_hourly = get_hourly_entries(turnstile_regular) turnstile_hourly.head() AttributeError Traceback (most recent call last) &lt;ipython-input-70-890cc0bc29bd&gt; in &lt;module&gt;() 6 return df 7 ----&gt; 8 turnstile_hourly = get_hourly_entries(turnstile_regular) 9 turnstile_hourly.head() &lt;ipython-input-70-890cc0bc29bd&gt; in get_hourly_entries(df) 2 3 def get_hourly_entries(df): ----&gt; 4 df['ENTRIESn_hourly'] = df.ENTRIESn.diff(1) 5 df.ENTRIESn_hourly.fillna(1, inplace = True) 6 return df /Users/flmlopes/anaconda3/envs/py2/lib/python2.7/site-packages/pandas/core/generic.pyc in __getattr__(self, name) 3079 if name in self._info_axis: 3080 return self[name] -&gt; 3081 return object.__getattribute__(self, name) 3082 3083 def __setattr__(self, name, value): AttributeError: 'DataFrame' object has no attribute 'ENTRIESn' So anyone know how can i solve this?
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48570918
tagged with: attributeerror

http://stackoverflow.com/comment/84054679
has text: @MohammadElsayed it is hard to say why in the world the instructor is using `upper` from `django.template.defaultfilters` Indeed, it makes little sense unless it is a class specifically about `django`. Note, in the [source code](https://github.com/django/django/blob/master/django/template/defaultfilters.py#L293) the functio is essentially `def upper(my_string): return my_string.upper()`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48529274
score: 0

http://stackoverflow.com/a/57718781
upvote count: 1
answers question: http://stackoverflow.com/q/48581038
score: 1
has body: I feel your pain. However, I am getting data in my dataframe (df) doing similar steps to yours. To troubleshoot, look at the type of your df being returned: import tabula pdf_file_name = "my_filename.pdf" df = tabula.read_pdf(pdf_file_name, encoding='Ansi') # or encoding='utf-8' print(type(df)) # df.to_csv("output.csv", index=False) It is quite possible that, due to you having pages="all", your df is a list of df's, which would require you to look into each df in the list to see evidence of your data. Also, if the multiple_tables parameter for tabula.read_pdf is set to True, df would be a list of df's, and, again, this would also require you to look into each df in the list to see your data.
type: Answer
downvote count: 0

http://stackoverflow.com/q/48610789
tagged with: python
has title: MySQLdb in python does not rollback the effect of a trigger
downvote count: 0
tagged with: transactions
score: 1
upvote count: 1
answer count: 1
tagged with: mysql-python
linked to: http://stackoverflow.com/q/48608442
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48613041
tagged with: rollback
type: UnansweredQuestion
has body: In MySQL (version 5.6.32-78.1) I have 2 tables named Test1, Test2 (say), where Test1 has a trigger (After INSERT) inserting something into a 3rd table called Test1A. I'm using MySQLdb module in python 3.6 to work with my DB. I'm trying to bundle 2 separate inserts in Test1 and Test2 into a single transaction. The problem I have, is that while the entire transaction might be rolled back due to an error in the 2nd insert, the result of the trigger fired after Insert in Test1 is NOT being rolled back. So, after the rollback we get back to the states of tables Test1 and Test2 before the transaction, however, the effect of the trigger on Test1 remains. Any ideas/suggestions ? Here is the model code import MySQLdb cnn = MySQLdb.connect (host = "hostname", user = "username", passwd = password", db = "dbname") cursor = cnn.cursor() try: cursor.execute( "SET AUTOCOMMIT = 0 " ) print('done with step 1') s = "Insert INTO Test1 ( field1) Values (%s ) " cursor.execute(s, ( 'abc', ) ) # this fires a trigger print('done with step 2') s = "Insert INTO Test2 (ID, field1) Values (%s, %s)" cursor.execute( s , ('1', 'aa' ) ) print('done step 3') cursor.close() cnn.commit() print('DONE') except: cnn.rollback() # the effect of the trigger on Test1 is not being print('Rollbacked') # rolled back The trigger on Test1 is INSERT INTO Test1A (field1) SELECT Test1.field1 FROM Test1 WHERE Test1.ID = NEW.ID A few comments: If I don't turn off the autocommit, then commit is called on each insert statement above, so that seems to be necessary. Of course, one may suggest to put Test1 as the last table inside a transaction, but that's not an option, as I might need an info from Test1 (say new ID) to operate on Test2.
tagged with: triggers

http://stackoverflow.com/q/48591768
score: 4
favorite count: 0
has body: I have a dataframe (called Errors) that look like this: Code ID Error1 Error 2 Time 2010-01-01 00:00:31.690 105278.0 None 5 2010-01-01 00:00:32.000 105278.0 1 None 2010-01-01 00:00:32.140 105278.0 3 None 2010-01-01 00:00:32.350 105278.0 None 7 2010-01-01 00:00:32.460 105278.0 None 1 I want to count different type of errors for each time stamp and save them in separate column: error_count = pd.get_dummies(errors.set_index('Time')).reset_index() error_count.columns = ['Time', 'machineID', 'error1', 'error2', 'error3', 'error4', 'error5'] # combine errors for a given machine in a given hour error_count = error_count.groupby(['machineID', 'datetime']).sum().reset_index() I have two issue one is that: When I run pd.get_dummies(errors.set_index('Time')).reset_index() I get the key error (KeyError: 'Time') The second issue is that I don't know how many different code I will get in my errors ( Error1 and Error 2 ) so I am not sure how I can write error_count.columns = ['Time', 'machineID', 'error1', 'error2', 'error3', 'error4', 'error5'] to reflect that. Thank you in advance
has comment: http://stackoverflow.com/comment/84182493
type: AnsweredQuestion
has title: Key Error mulitindex dataftame pandas
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/84201487
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/48592769
tagged with: pivot-table
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48592769
tagged with: machine-learning

rounding-error
tag name: rounding-error
type: Tag
tags question: http://stackoverflow.com/q/48638398

http://stackoverflow.com/comment/83993585
comment on: http://stackoverflow.com/a/48499923
score: 0
type: Comment
type: AnswerComment
has text: Can you send me your csv to my email in my profile? I can check your data.

http://stackoverflow.com/comment/84167060
comment on: http://stackoverflow.com/a/48584043
score: 0
type: AnswerComment
has text: Prblm fixed Thanks
type: Comment

http://stackoverflow.com/comment/84203035
score: 0
type: Comment
has text: ok, unfortunately i can't help with your question, but look up h5py documentation, the syntax is easy to pick up to start storing / appending numeric data, and if used correctly can be fast.
comment on: http://stackoverflow.com/q/48603119
type: QuestionComment

http://stackoverflow.com/comment/84204154
score: 0
type: Comment
type: QuestionComment
has text: One image is cropped at the top, the other is not. They are different sizes too
comment on: http://stackoverflow.com/q/48603371

http://stackoverflow.com/a/48581382
has comment: http://stackoverflow.com/comment/84159533
answers question: http://stackoverflow.com/q/48581155
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84159381
downvote count: 0
has comment: http://stackoverflow.com/comment/84278616
has comment: http://stackoverflow.com/comment/84318900
has body: Depending on the kind of model you use, there's a strong probability that you absolutely can't. If you have such a large model, I guess it is a Neural Network or a Random Forest model. And unfortunately there are no easy way to do this, and if you do this, you will most likely decrease your accuracy. For Neural Networks there are no way to do this, just decrease the complexity of your network. For Random Forest, you can have a look to Tree Pruning, however I don't think you will earn a significant amount of memory. If your question was: is there anything in the model only useful for training that I can delete => maybe a few variables, nothing big enough to be worth your time (a few KB at maximum).
has comment: http://stackoverflow.com/comment/84375006
type: Answer
has comment: http://stackoverflow.com/comment/84283615

http://stackoverflow.com/comment/84108515
score: 0
has text: I am a BIG pycharm, but what is the scope here? Alternative to requiring the caller to store to pass the tuple explicitly: `store((weight, color))`, or change the base store to `store(*args)`, then args is always tuple.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48556205

http://stackoverflow.com/q/48507133
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84009292
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48507593
upvote count: 6
has answer: http://stackoverflow.com/a/48507177
tagged with: python
has comment: http://stackoverflow.com/comment/84009325
answer count: 4
downvote count: 0
has body: I am trying to get only files in the folder excluding any other directories. but the below script is moving all the files and folders to another directory. while True: # Go through each of the directories for mylist in dirlist: check_dir = mylist[0] callback = mylist[1] # get the list of files in the directory filelist = os.listdir(check_dir) for this_file in filelist: if ((this_file == ".") or (this_file == "..") or (this_file == "donecsvfiles") or (this_file == "doneringofiles")): print "Skipping self and parent" continue full_filename = "%s/%s"%(check_dir, this_file)
has title: Distinguishing between files and directories in Python
tagged with: file
score: 6
tagged with: directory
has answer: http://stackoverflow.com/a/48507391
has answer: http://stackoverflow.com/a/48507475

http://stackoverflow.com/q/48582628
tagged with: python
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: pyvmomi
has body: I'm trying to get the load average of my ESX, using python script et pyVmomi. I cannot find the numbers 1.71, 1.72, 1.72 from the API, as described in the commands below. Any clues ? # ssh my-esx [root@my-esx:~] uptime 12:07:54 up 8 days, 21:02:09, load average: 1.71, 1.72, 1.72 [root@my-esx:~] uname -a VMkernel my-esx 6.0.0 #1 SMP Release build-3073146 Sep 16 2015 04:08:47 x86_64 x86_64 x86_64 ESXi For now, I get the overallCpuUsage as described here, but this data is more like a percentage of allocated Mhz. It cannot be compared to the classic "linux load average". It's important for me, because our monitoring page compare cpu load of ESXs server and Linux server.
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: vmware
has title: VMWare python API : How to access cpu load average?
score: 1

http://stackoverflow.com/q/48635552
score: 0
tagged with: reverse-proxy
has comment: http://stackoverflow.com/comment/84267753
has body: So many web applications these days run on their own microservers, it can be hard to implement them on shared hosting platforms. The apps listen on a dedicated port you can customize or reverse proxy, but shared hosting usually only has 80 and 443 open. Just as an example, the handy web-based editor ICEcoder is a PHP application, so you just drop the files in a directory and away you go. However, the Cloud9 editor runs its own server. You can customize the port, but again, you cant run the reverse proxy. I had the idea of using a PHP or Python CGI script as an intermediary. Something like: www.mydomain/mydirectory/middleman.py from BaseHTTPServer import BaseHTTPRequestHandler import urlparse, json # hpyothetical apache api import apache parsed_path = urlparse.urlparse(self.path) response = apache(url=parsed_path, port=8080) sendStuffBack(response) Would this be possible with Apache? How would I implement it? Edit: Here is what I did based on @grawity's answer. helloflask.py #!/usr/bin/env python from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() middle.py #!/usr/bin/env python print ("Content-Type: text/html") print() import requests #response = requests.get("http://localhost:5000") response = requests.get("http://localhost:8888/token=8a387fe88d662e2568f9b8ec2398191452492e7184536670") print(response.text)
tagged with: port
has answer: http://stackoverflow.com/a/48635553
accepted answer: http://stackoverflow.com/a/48635553
tagged with: python
has title: How to programmatically communicate with Apache?
has comment: http://stackoverflow.com/comment/84267754
linked to: http://stackoverflow.com/q/48673359
tagged with: shared-hosting
answer count: 1
tagged with: web-applications
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/84102162
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48551189
has text: Thanks this wil help
type: Comment

http://stackoverflow.com/comment/84231938
comment on: http://stackoverflow.com/q/48562947
score: 0
type: Comment
type: QuestionComment
has text: @ArminRigo I am having issues in installing gcloud as well. Any idea what this means? error: Setup script exited with error: command 'C:\\Users\\Shrestha\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2

http://stackoverflow.com/comment/83978200
score: 0
has text: Could you please add a bit more information about what you are trying to achieve and the codebase which already been used there?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48488932

http://stackoverflow.com/a/48489200
score: -1
has comment: http://stackoverflow.com/comment/83971471
has body: According to the docs, the correct import statement is: from Tkinter import * Does that work?
has comment: http://stackoverflow.com/comment/83973696
upvote count: 0
has comment: http://stackoverflow.com/comment/83971409
downvote count: 1
answers question: http://stackoverflow.com/q/48489171
type: Answer

http://stackoverflow.com/q/48511765
has answer: http://stackoverflow.com/a/48512467
has body: I have an application that is developed in Python 5.3 and PyQt 7.1 (I think). So far I have everything in the GUI working just fine. I now need to be able to detect the pressing of two external mechanical buttons via GPIO.add_event_detect. I added the GPIO command for detecting the falling edge of the signal and when I try to execute the code I get the "Conflicting edge detection already enabled for this GPIO Channel." I tried moving the the code to different classes (it's not in a while loop) just to see if I would get a different error. I am looking for any documentation or instructions that explains how to use the add_event_detect into an event based application like QT. As always, much thanks! Mike EDIT: I tried the recommendation below and I am having an issue with execution. The code below is only three classes - I didn't add a executable code because I wasn't sure anybody would want to spend time to add 2 N.C. buttons to GPIO pins. I am hoping you'll be able to see an issue just by reading the code. The class ExecuteSession works fine. I am trying to add the ability to read the falling edge of two signals on the GPIO pins 16 &amp; 18 in classes PStop and EStop. When the ExecuteSession starts I can see the print statements "In PStop" and "In EStop". When I push the buttons I don't see the other print statement. I am pretty new to Python and Threads and would appreciate any suggestions. I did create a small test program to make sure the Pi was seeing the state transition, and it did. Thanks class PStop(QThread): PT_event_detected = pyqtSignal(int) def __init__(self): QThread.__init__(self) self.queue=Queue() GPIO.add_event_detect(16, GPIO.FALLING, callback=self.queue.put) print("In PStop") def run(self): while True: print("In PStop Run") self.PT_event_detected.emit(self.queue.get()) print("PT EVENT " +str(self.queue.get())) class EStop(QThread): ER_event_detected = pyqtSignal(int) def __init__(self): QThread.__init__(self) self.queue=Queue() GPIO.add_event_dete…
tagged with: pyqt
type: UnansweredQuestion
tagged with: gpio
answer count: 1
has title: Detecting Mechanical Button Press with Python3 and QT5
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/84019265
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/84018378
has comment: http://stackoverflow.com/comment/84018393
score: 0
linked to: http://stackoverflow.com/q/38125047
linked to: http://stackoverflow.com/q/37394390
tagged with: python
has comment: http://stackoverflow.com/comment/84019317
has comment: http://stackoverflow.com/comment/84019519
type: Question

http://stackoverflow.com/comment/135381349
type: Comment
comment on: http://stackoverflow.com/a/76768191
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).

http://stackoverflow.com/q/48521710
answer count: 1
has body: I have a series of csv files which I would like to run a script on. Each file has the same headers and the same number of rows just different data. So far I have used Pandas to import all csv files from my directory. I have a list of all files names and a list of dataframes containing the data from each file. I would like to run a script on each file/dataframe and name the exports with the prefix of the filename. Is this possible and is a loop the correct way to proceed?
tagged with: loops
type: Question
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
score: 0
has title: Python loop over dataframes and rename results
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48521810

amazon-vpc
type: Tag
tag name: amazon-vpc
tags question: http://stackoverflow.com/q/48492495

http://stackoverflow.com/comment/84223949
type: AnswerComment
score: 1
type: Comment
has text: Thanks! It is working now, but I did not understand exactly what the rule is? Is it the print() statement?
comment on: http://stackoverflow.com/a/48612579

http://stackoverflow.com/comment/84004014
type: Comment
score: 0
type: QuestionComment
has text: This is how transparency should work. What did you expect instead? It might be a good idea to post a picture demonstrating the problem.
comment on: http://stackoverflow.com/q/48504405

http://stackoverflow.com/comment/84263356
has text: @DYZ fair enough. Can't say I've ever used the array so I don't actually know how useful it is :)
comment on: http://stackoverflow.com/q/48633070
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83979898
has text: No I checked my file and it has information it it
comment on: http://stackoverflow.com/q/48493270
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48581621
answers question: http://stackoverflow.com/q/48581558
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48581558
has comment: http://stackoverflow.com/comment/84159719
has body: data['maps'] is a simple list, so you can iterate over it as such: for map in data['maps']: print(map['id']) To store them in a variable, you'll need to output them to a list. Storing them each in a separate variable is not a good idea, because like you said, you don't have a way to know how many there are. ids = [] for map in data['maps']: ids.append(map['id'])
has comment: http://stackoverflow.com/comment/84159540
has comment: http://stackoverflow.com/comment/84159552
type: AcceptedAnswer
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84159901
score: 1

http://stackoverflow.com/comment/84111703
comment on: http://stackoverflow.com/q/48557705
score: 0
has text: Hi Garbage Collector, cause I have other options (such as `$addFields` and sort by the added field), so I must use `aggregate` to do this.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48641292
upvote count: 3
type: UnansweredQuestion
downvote count: 0
has body: So I have recently gotten on board with AWS Lambda and I've been working on a bot since yesterday afternoon but now all of a sudden, this is happening. I whenever I go to build the bot or save the intent, I just keep getting the message 'The checksum value doesn't match for the resource named 'isRecyclableGarden'.' isRecyclableGarden is one of the intents I am using within my code. I can't share the code as it's work code and I am fairly new to this. Any help on how I can work out how to validate the check sum again would be helpful as I cant actually edit or progress with this code! Pictured is the problem I am having.
tagged with: amazon-web-services
tagged with: checksum
tagged with: aws-lambda
score: 3
has title: The checksum value doesn't match for the resource named 'isRecyclableGarden'
answer count: 1
has answer: http://stackoverflow.com/a/48663127
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/84261851
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48629285
type: Comment
has text: See e.g. https://stackoverflow.com/questions/44076203/getting-percentages-in-legend-from-pie-matplotlib-pie-chart

http://stackoverflow.com/a/48635320
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48634363
type: AcceptedAnswer
has body: The library tifffile ( https://pypi.python.org/pypi/tifffile ) does exactly what you are looking for. Here is an example that creates an int16 numpy array, saves it on the disk, then load it back again: import tifffile import numpy as np # random array of numbers between -5 and 5 a = np.asarray(np.random.rand(8, 8)*10-5, dtype=np.int16) # save array to disk and display its content tifffile.imsave("test.tiff", a) print(str(a) + "\n") # load the array back from the disk and display its content too b = tifffile.imread("test.tiff") print(b) The output: a=[[ 1 -1 -3 2 3 -1 4 0] [ 2 -2 2 0 -1 0 3 -4] [ 0 -4 3 2 -4 -2 0 -3] [ 0 -1 0 -2 0 3 -3 1] [ 0 -4 3 1 -1 3 2 3] [-3 4 4 3 -3 1 -3 -2] [ 4 0 -4 -2 1 -3 3 -3] [ 4 0 4 2 3 1 -2 -4]] b=[[ 1 -1 -3 2 3 -1 4 0] [ 2 -2 2 0 -1 0 3 -4] [ 0 -4 3 2 -4 -2 0 -3] [ 0 -1 0 -2 0 3 -3 1] [ 0 -4 3 1 -1 3 2 3] [-3 4 4 3 -3 1 -3 -2] [ 4 0 -4 -2 1 -3 3 -3] [ 4 0 4 2 3 1 -2 -4]]
accepted answer of: http://stackoverflow.com/q/48634363
type: Answer

http://stackoverflow.com/comment/84058567
type: Comment
comment on: http://stackoverflow.com/a/48531046
score: 0
type: AnswerComment
has text: That seems to have fixed the syntax error however the code says that the band is not in the list when it actually is. "Enter band name band2 band2 is not in list" However band2 is in the list

http://stackoverflow.com/comment/84198797
has text: If your just learning you should go for Python 3 which is the latest version
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48601095

http://stackoverflow.com/comment/84006370
comment on: http://stackoverflow.com/q/48506031
score: 0
type: Comment
type: QuestionComment
has text: You have an implicit many-to-many relation between `Build` and `Case` through `Result`. Is there any reason you don't want or you can't declare this relation explicitly?

http://stackoverflow.com/comment/84094795
comment on: http://stackoverflow.com/q/48549416
type: QuestionComment
has text: Related: https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h
score: 0
type: Comment

http://stackoverflow.com/q/48509015
has body: I want to run hcitool lescan --duplicates &amp; hcidump -R using Popen. However Popen does not seem to consider the &amp; (the way it works in bash scripting) and gives error as "lescan: too many arguments" Am I doing something incorrect
has answer: http://stackoverflow.com/a/48527631
tagged with: popen
has title: How can I execute a bash command containing '&' with Popen
has comment: http://stackoverflow.com/comment/84012835
tagged with: python
linked to: http://stackoverflow.com/q/1196074
type: Question
has comment: http://stackoverflow.com/comment/84049210
has comment: http://stackoverflow.com/comment/84013863
score: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/48518876
has body: As per your code block I don't see any issue in navigating to that web page and wait for a fixed time (eg. 30 sec) and then navigate to next url. But the main factor is what would you like the webdriver instance to do for the specified time. The only way looks viable to me is inducing sleep or keep the browser busy doing nothing where there will be no chances of your program getting crashed. So the simplest solution will be to induce sleep as follows : time.sleep(30) As an enhancement you can configure a pre-defined time for each iteration to happen following the discussion python and selenium webdriver wait until time was equal to specific
type: Answer
answers question: http://stackoverflow.com/q/48518011
score: 0

http://stackoverflow.com/a/48618453
upvote count: 2
has comment: http://stackoverflow.com/comment/84242280
has body: Low hanging fruit: use __slots__ in your node class, otherwise, each TrieNode object is carrying around a dict. class TrieNode: __slots__ = "word", "children" def __init__(self): self.word = None self.children = {} Now, each TrieNode object will not carry around an attribute dict. Compare the sizes: &gt;&gt;&gt; class TrieNode: ... def __init__(self): ... self.word = None ... self.children = {} ... &gt;&gt;&gt; tn = TrieNode() &gt;&gt;&gt; sys.getsizeof(tn) + sys.getsizeof(tn.__dict__) 168 Vs: &gt;&gt;&gt; class TrieNode: ... __slots__ = "word", "children" ... def __init__(self): ... self.is_word = False ... self.children = {} ... &gt;&gt;&gt; sys.getsizeof(tn) 56 &gt;&gt;&gt; tn.__dict__ Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'TrieNode' object has no attribute '__dict__' Another optimization, use int objects. Small int objects are cached, it is probable most of your characters will be in that range anyway, but even if they aren't, an int, while still beefy in Python, is smaller than even a single character string: &gt;&gt;&gt; 'ñ' 'ñ' &gt;&gt;&gt; ord('ñ') 241 &gt;&gt;&gt; sys.getsizeof('ñ') 74 &gt;&gt;&gt; sys.getsizeof(ord('ñ')) 28 So you can do something like: def insert( self, word, value): node = self for letter in word: code_point = ord(letter) if code_point not in node.children: node.children[code_point] = TrieNode() node = node.children[code_point] node.is_word = True #Don't save the word, simply a reference to a singleton Also, you are keeping around a class variable values dict that is growing enormously, but that information is redundant. You say: I just add a dictionary to hold some value with quick access (I need it) You can reconstruct the words from the path. It should be relatively fast, I would seriously consider against having this dict. Check out how much memory it requires simply to hold a million one-character strings: &gt;&gt;&gt; d = {str(i):i for i in range(1000000)} &gt;&gt;&gt; (s…
downvote count: 0
score: 2
type: Answer
answers question: http://stackoverflow.com/q/48618073

http://stackoverflow.com/a/48638890
has body: conn is None, so you must have failed to acquire a connection. Presumably the notebook where this is working has "QueryBuilder" set up correctly, and wherever else you have tried to use this does not. I'm not familiar with that name specifically, but you may need to set up the data source, or you may need to install the appropriate ODBC driver. You should be able to look at pyodbc.dataSources() and/or pyodbc.drivers() to get more details about what data sources are configured and what drivers are installed, and see what the difference is between your systems.
score: 4
answers question: http://stackoverflow.com/q/48638592
has comment: http://stackoverflow.com/comment/84274766
type: Answer
has comment: http://stackoverflow.com/comment/84274115
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/84255414
type: QuestionComment
has text: formatting: code, text, quote
comment on: http://stackoverflow.com/q/48626933
score: 0
type: Comment

http://stackoverflow.com/a/48521583
answers question: http://stackoverflow.com/q/48521360
score: 5
has body: First forward fill last column close and then bfill by columns: print (df) open high low close date 2017-12-03 07:00:00 14.46 14.46 14.46 14.81 2017-12-03 07:03:00 NaN NaN NaN NaN 2017-12-03 07:06:00 14.50 14.50 14.50 14.59 2017-12-03 07:09:00 NaN NaN NaN NaN 2017-12-03 07:12:00 14.50 14.56 14.50 14.56 df['close'] = df['close'].ffill() df = df.bfill(axis=1) print (df) open high low close date 2017-12-03 07:00:00 14.46 14.46 14.46 14.81 2017-12-03 07:03:00 14.81 14.81 14.81 14.81 2017-12-03 07:06:00 14.50 14.50 14.50 14.59 2017-12-03 07:09:00 14.59 14.59 14.59 14.59 2017-12-03 07:12:00 14.50 14.56 14.50 14.56
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84037760
downvote count: 0
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48521360

http://stackoverflow.com/q/48502446
upvote count: 2
tagged with: peewee
type: UnansweredQuestion
tagged with: python
has title: Declaring PeeWee models inside class, passing database parameter to BaseModel
has answer: http://stackoverflow.com/a/64912723
score: 2
has body: I'm not sure if it's reasonable what I'm tring to do, but I want to put all classes and methods connected with database management in one single class. So there will be DataSaver class representing one instance of database. Now, official PeeWee docs recommend to create BaseModel and store database variable there. Here is how it's shown in example: from peewee import * db = SqliteDatabase('my_app.db') class BaseModel(Model): class Meta: database = db class User(BaseModel): username = CharField(unique=True) class Tweet(BaseModel): user = ForeignKeyField(User, backref='tweets') message = TextField() created_date = DateTimeField(default=datetime.datetime.now) is_published = BooleanField(default=True) Now I'm trying to do the same thing, but inside class: class DataSaver: def __init__(self, database_save_path): self.database_save_path = database_save_path self.db = SqliteDatabase(database_save_path) db.connect() db.create_tables([User, Chat, Message], True) class BaseModel(Model): class Meta: database = self.db class User(BaseModel): name = CharField(unique=True) class Chat(BaseModel): name = CharField(unique=True) And the problem here is: BaseModel don't have currently access to variable db. self currently isn't pointing to DataSaver so it's rather clear that complier can be a little confused at this point. Do you have any idea how to pass db variable to BaseModel so second block of code will work similarily as the first one?
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48527148
favorite count: 0
type: Question

http://stackoverflow.com/comment/84051492
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48528111
has text: view template from which the post request is coming

http://stackoverflow.com/q/48573445
has comment: http://stackoverflow.com/comment/84144532
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48573683
accepted answer: http://stackoverflow.com/a/48573683
answer count: 3
has answer: http://stackoverflow.com/a/48573677
has comment: http://stackoverflow.com/comment/84144527
has body: Appreciate any help for a beginner :) I tried the below but not sure how to wrap the def Job(): import time from progressbar import ProgressBar pbar = ProgressBar() def job(): Script .... Script ... Script ... Script ...
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48573629
possible better answer: http://stackoverflow.com/a/48573629
has comment: http://stackoverflow.com/comment/101696193
score: 5
upvote count: 5
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/3160699
has title: Add progress bar to a python function
tagged with: progress-bar

http://stackoverflow.com/q/48634565
has title: Reduce by column max in numpy
has answer: http://stackoverflow.com/a/48634972
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48634708
type: UnansweredQuestion
has body: Imagine that I have the following array: b = np.array([[1,2],[3,4],[5,6],[3,3]]) I want to halve its length by taking pairs of elements and discarding the one with the lower sum of values. This is easy in one dimensions where no sum is necessary: a = np.array([1,2,3,4]) a.reshape((-1,2)).max(axis=1) And yields the desired result: [2,4] My question, is it possible to do the equivalent in two dimensions such that the operation on b yields [[3,4],[5,6]]? For reference, here is a non-numpy way of doing this: b = [[1,2],[3,4],[5,6],[3,3]] c = [] for i in range(0,len(b) - 1,2): if sum(b[i]) &gt; sum(b[i+1]): c += [b[i]] else: c += [b[i+1]] print(c)
tagged with: python
has answer: http://stackoverflow.com/a/48635055
score: 0
answer count: 3

http://stackoverflow.com/q/48635934
score: 1
has comment: http://stackoverflow.com/comment/84268737
has comment: http://stackoverflow.com/comment/84268746
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has comment: http://stackoverflow.com/comment/84268452
downvote count: 1
linked to: http://stackoverflow.com/q/31948285
has body: I want to have a html file with buttons, and when I click on a button it should run a python script and display the output onto the browser as a webpage. Any help would be appreciated.
has title: Python: How to display/redirect the output of a python script onto the browser as a html file?
favorite count: 0
duplicate of: http://stackoverflow.com/q/31948285
type: Question
has comment: http://stackoverflow.com/comment/84268677
type: UnansweredQuestion
tagged with: javascript
tagged with: python
tagged with: flask
linked to: http://stackoverflow.com/q/7460938
upvote count: 2
has answer: http://stackoverflow.com/a/48636039
has comment: http://stackoverflow.com/comment/84268530

http://stackoverflow.com/a/48502686
type: AcceptedAnswer
has body: Here is a solution, basically you need to run AutoIt server on the node: https://github.com/daluu/AutoItDriverServer
has comment: http://stackoverflow.com/comment/83998789
accepted answer of: http://stackoverflow.com/q/48490437
type: Answer
answers question: http://stackoverflow.com/q/48490437
score: 0

http://stackoverflow.com/a/48584130
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48583184
has body: It looks like you have 2 levels of processing: first by key, then by length of value. As per my comment above, the output is a list of tuples, as currently ordered dictionaries are considered an implementation detail. If you wish to use an ordered dictionary, use collections.OrderedDict as below. from collections import OrderedDict test = {346: [235, 238], 347: [129, 277], 348: [115, 191, 226], 349: [194, 328], 351: [150, 70, 118], 352: [123, 334], 353: [161, 196]} s1 = OrderedDict(sorted(test.items())) s2 = sorted(s1.items(), key=lambda k: len(s1[k[0]]), reverse=True) # [(348, [115, 191, 226]), # (351, [150, 70, 118]), # (346, [235, 238]), # (347, [129, 277]), # (349, [194, 328]), # (352, [123, 334]), # (353, [161, 196])] d = OrderedDict(s2) # OrderedDict([(348, [115, 191, 226]), # (351, [150, 70, 118]), # (346, [235, 238]), # (347, [129, 277]), # (349, [194, 328]), # (352, [123, 334]), # (353, [161, 196])])
answers question: http://stackoverflow.com/q/48583184
type: AcceptedAnswer

list
tags question: http://stackoverflow.com/q/48552366
type: Tag
tags question: http://stackoverflow.com/q/48527573
tags question: http://stackoverflow.com/q/48515746
tags question: http://stackoverflow.com/q/48624071
tags question: http://stackoverflow.com/q/48513956
tags question: http://stackoverflow.com/q/48641350
tags question: http://stackoverflow.com/q/48574533
tags question: http://stackoverflow.com/q/48560045
tags question: http://stackoverflow.com/q/48598639
tags question: http://stackoverflow.com/q/48561673
tags question: http://stackoverflow.com/q/48534380
tags question: http://stackoverflow.com/q/48502077
tags question: http://stackoverflow.com/q/48642581
tags question: http://stackoverflow.com/q/48547355
tags question: http://stackoverflow.com/q/48499207
tags question: http://stackoverflow.com/q/48593822
tags question: http://stackoverflow.com/q/48515896
tags question: http://stackoverflow.com/q/48523043
tags question: http://stackoverflow.com/q/48534034
tags question: http://stackoverflow.com/q/48618935
tags question: http://stackoverflow.com/q/48635310
tags question: http://stackoverflow.com/q/48627255
tags question: http://stackoverflow.com/q/48606932
tags question: http://stackoverflow.com/q/48615252
tags question: http://stackoverflow.com/q/48524397
tags question: http://stackoverflow.com/q/48497201
tags question: http://stackoverflow.com/q/48619260
tags question: http://stackoverflow.com/q/48620587
tags question: http://stackoverflow.com/q/48615790
tags question: http://stackoverflow.com/q/48593969
tags question: http://stackoverflow.com/q/48498521
tags question: http://stackoverflow.com/q/48532721
tags question: http://stackoverflow.com/q/48492155
tags question: http://stackoverflow.com/q/48514315
tags question: http://stackoverflow.com/q/48539919
tags question: http://stackoverflow.com/q/48560599
tags question: http://stackoverflow.com/q/48514464
tags question: http://stackoverflow.com/q/48628860
tags question: http://stackoverflow.com/q/48568833
tags question: http://stackoverflow.com/q/48618653
tags question: http://stackoverflow.com/q/48591755
tags question: http://stackoverflow.com/q/48538451
tags question: http://stackoverflow.com/q/48589366
tags question: http://stackoverflow.com/q/48550533
tags question: http://stackoverflow.com/q/48549326
tags question: http://stackoverflow.com/q/48567471
tags question: http://stackoverflow.com/q/48609055
tags question: http://stackoverflow.com/q/48584855
tags question: http://stackoverflow.com/q/48555034
tags question: http://stackoverflow.com/q/48573384
tags question: http://stackoverflow.com/q/48550696
tags question: http://stackoverflow.com/q/48556287
tags question: http://stackoverflow.com/q/48598222
tags question: http://stackoverflow.com/q/48564743
tags question: http://stackoverflow.com/q/48514970
tags question: http://stackoverflow.com/q/48603455
tags question: http://stackoverflow.com/q/48522054
tags question: http://stackoverflow.com/q/48632756
tags question: http://stackoverflow.com/q/48593221
tags question: http://stackoverflow.com/q/48620109
tags question: http://stackoverflow.com/q/48630181
tags question: http://stackoverflow.com/q/48557336
tags question: http://stackoverflow.com/q/48530728
tags question: http://stackoverflow.com/q/48538179
tags question: http://stackoverflow.com/q/48515861
tags question: http://stackoverflow.com/q/48638951
tags question: http://stackoverflow.com/q/48570795
tags question: http://stackoverflow.com/q/48515039
tags question: http://stackoverflow.com/q/48600381
tags question: http://stackoverflow.com/q/48530309
tags question: http://stackoverflow.com/q/48641000
tags question: http://stackoverflow.com/q/48585532
tags question: http://stackoverflow.com/q/48590291
tags question: http://stackoverflow.com/q/48570620
tags question: http://stackoverflow.com/q/48596726
tags question: http://stackoverflow.com/q/48553745
tags question: http://stackoverflow.com/q/48513401
tags question: http://stackoverflow.com/q/48576952
tags question: http://stackoverflow.com/q/48604179

http://stackoverflow.com/q/48547349
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: vb6
has title: Reading python shell line from VB6
type: Question
accepted answer: http://stackoverflow.com/a/48551489
tagged with: python
has body: I have python script that prints as result a file path. I need to read convert that result into a string that can be used as a variable in my vb6 program.This is the output of the script I tried different code that i found on web but none of them worked. I post them anyway since it can be my mistake. Private Sub Command1_Click() Dim wscript As Object Dim objShell As Object Dim objExecObject As Object Set objShell = wscript.CreateObject("WScript.Shell") Set objExecObject = objShell.Exec("python.exe /k Get_Info.py") Text1.Text = "" Do While Not objExecObject.StdOut.AtEndOfStream Text1.Text = Text1.Text &amp; vbCrLf &amp; objExecObject.StdOut.ReadLine() Loop End Sub With this one I don't know very well how to declare the 3 variables so i'm not sure isn't working Private Sub Command4_Click() Shell "python.exe Get_Info.py folder", vbMaximizedFocus Sleep 1000 MsgBox Command$ End Sub This one instead doesnt' get anything. Returns Command$ as "" I also tried typing script = App.path &amp; "\" &amp; "Get_Info.py" path = Shell("python.exe script &amp; parameter ", vbMaximizedFocus) Sleep 1000 MsgBox path I get a different 4 digit number as output everytime i click but no trace of the path. Please help me on this :) Thanks
has answer: http://stackoverflow.com/a/48551489

http://stackoverflow.com/comment/84057515
has text: @JohnH Sorry, I seemed to have missed this comment. I don't have an expected number of sublists, since I'm parsing a file. The number of sublists could be 2, but it could go up to 50 or more. I'd like to be able to produce one sum for every time the 1st object and 3rd object are the same.
type: Comment
comment on: http://stackoverflow.com/q/48530728
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84056287
type: Comment
type: QuestionComment
has text: no need to declare start value of range if it is `0`...
score: 0
comment on: http://stackoverflow.com/q/48530092

http://stackoverflow.com/comment/84119626
type: QuestionComment
has text: Is there anything in syslog? There should be an error message saying why cronjob failed.
score: 0
comment on: http://stackoverflow.com/q/48561120
type: Comment

http://stackoverflow.com/a/48626948
score: 2
has comment: http://stackoverflow.com/comment/84250717
upvote count: 2
answers question: http://stackoverflow.com/q/48626852
has comment: http://stackoverflow.com/comment/84250776
downvote count: 0
type: Answer
has body: By using natsort sort by index list then reindex df=pd.DataFrame({'v':[1,2,3]},index=['b1','b11','b2']) from natsort import natsorted, ns df.reindex(natsorted(df.index.tolist(), alg=ns.IGNORECASE)) Out[795]: v b1 1 b2 3 b11 2

http://stackoverflow.com/a/48637135
has comment: http://stackoverflow.com/comment/84271225
has comment: http://stackoverflow.com/comment/84279718
has comment: http://stackoverflow.com/comment/84271479
has comment: http://stackoverflow.com/comment/84271146
answers question: http://stackoverflow.com/q/48637047
has comment: http://stackoverflow.com/comment/84271292
type: Answer
has body: Give like this : answer = "the value which you can give as default" if F ==0: answer=float(m)*float(a) if m ==0: answer=float(F)/float(a) if a ==0: answer=float(F)/float(m) or if F ==0: answer=float(m)*float(a) elif m ==0: answer=float(F)/float(a) elif a ==0: answer=float(F)/float(m) else : answer = "the value which you can give as default" If none of the conditions is matching which value you want to assign to answer? that value you can give in mentioned place in that above answers
has comment: http://stackoverflow.com/comment/84271110
score: 0
has comment: http://stackoverflow.com/comment/84270747
has comment: http://stackoverflow.com/comment/84270783

http://stackoverflow.com/comment/84299233
score: 0
has text: Thought it would be possible to customize or even bypass with odbc... well then I'll have to take the long way. Thanks @Alan
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48642889

http://stackoverflow.com/q/48533418
type: UnansweredQuestion
has title: Python build doesn't work on Sublime Text
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84063786
has answer: http://stackoverflow.com/a/64612024
has answer: http://stackoverflow.com/a/73661311
has answer: http://stackoverflow.com/a/48538526
has answer: http://stackoverflow.com/a/48533653
tagged with: python
tagged with: sublimetext3
answer count: 4
score: 0
has body: Whenever I build (Cmd+B) on Sublime Text 3 it doesn't execute my code. I used Shift+Command+B to set the build system to Python. I also tried making my own build system by using the which python3.6 command in terminal, which said /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 I put in this in my custom build system { "cmd": ["python", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python" } However I still get the same error. Please help. I know this is a really stupid question, I'm sure I just have to change some settings to solve this, thanks for you time.

http://stackoverflow.com/q/48515654
has comment: http://stackoverflow.com/comment/84025681
favorite count: 0
type: Question
has title: Download file from a URL into a remote machine
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84025520
downvote count: 2
answer count: 1
upvote count: 1
tagged with: sftp
has body: I am looking at downloading a file from URL into remote machine directly.. Is this possible with python paramiko sftp?
has answer: http://stackoverflow.com/a/48520140
has comment: http://stackoverflow.com/comment/84025503
tagged with: python
score: -1

http://stackoverflow.com/a/48534421
has body: After switching to first iframe , you have to switch back to default context (your main page containing multiple iframes) &amp; then switch to next iframe . So your pseudo code should look like driver.switch_to.frame(driver.find_element_by_tag_name("iframe_1")) driver.switch_to.defaultContent() driver.switch_to.frame(driver.find_element_by_tag_name("iframe_2")) driver.switch_to.defaultContent() &amp; so on
answers question: http://stackoverflow.com/q/48533101
type: Answer
score: 0

http://stackoverflow.com/q/48591723
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48591812
possible better answer: http://stackoverflow.com/a/48593087
has answer: http://stackoverflow.com/a/57357865
has body: I have the following dataframe in pandas df = pd.DataFrame({'a' : ['hello', 'world', 'great', 'hello'], 'b' : ['world', None, 'hello', 'world'], 'c' : [None, 'hello', 'great', None]}) i would like to count the occurrence of the unique values in column 'a' across all the other columns and column 'a' too and save that into new columns for the dataframe with appropriate naming that take on the values in column 'a' such as 'hello_count', 'world_count' and so on. Hence the end result would be something like df = pd.DataFrame({'a' : ['hello', 'world', 'great', 'hello'], 'b' : ['world', None, 'hello', 'world'], 'c' : [None, 'hello', 'great', None], 'hello_count' : [1,1,1,1], 'world_count' : [1,1,0,1], 'great_count' : [0,0,2,0]}) i tried df['a', 'b', 'a'].groupby('a').agg(['count]) but that did not work. Any help is really appreciated
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: Count occurance of unique values in a pandas dataframe across multiple columns
answer count: 3
has answer: http://stackoverflow.com/a/48593087
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/48591812

http://stackoverflow.com/q/48623164
tagged with: python
has answer: http://stackoverflow.com/a/48623354
type: AnsweredQuestion
score: 0
has body: myproject/urls.py urlpatterns = [ url(r'^$', include('website-app.urls', namespace='website')), ] website-app/urls.py urlpatterns = [ url(r'^$', views.somedef, name='somename') ] I want to connect url domain.com/ to views.somedef which is not in myproject. What domain.com/ means is just domain and end of address with /. It is with No other parameters. domain.com/other/parameters/ has other parameters (other/parameters/), so it is not what I want. If I run django with that above code, django says ?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs. Is there any good way to use url domain.com/ in website-app/urls.py , Not in myproject/urls.py?
answer count: 1
tagged with: django
has title: django, how to mapping no other address, but just domain?
type: Question
accepted answer: http://stackoverflow.com/a/48623354

http://stackoverflow.com/q/48526325
type: UnansweredQuestion
has title: How to adjust "requirements.txt" to get Python inserting data to ES?
has body: I am trying to sent data to Elastic Search using Python and Im getting error: ElasticHttpError: 406, Elastic Search Error While indexing Data After some googling I found that I need to specify ES version in "requirements.txt" but I havent found this file. Can anybody help what to do? Thank you
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48526586
answer count: 1
downvote count: 1
tagged with: elasticsearch
score: -1
type: Question
upvote count: 0

http://stackoverflow.com/q/48500590
downvote count: 3
accepted answer: http://stackoverflow.com/a/48500635
has comment: http://stackoverflow.com/comment/83994517
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48501335
has answer: http://stackoverflow.com/a/48500635
answer count: 4
favorite count: 0
type: Question
has title: adding a list to another list
upvote count: 2
tagged with: arrays
has body: let's say there's a list, list1= [[0, 4, 0, 0], [2, 0, 4, 0], [9, 8, 0, 0], [0, 2, 5, 0]] and there's another list list2= [a,b,c,d] I've seen multiple questions that asks similar things but I couldn't get the proper answer for this question. I want to make a list list3= [[a,0,4,0,0],[b,2,0,4,0],[c,9,8,0,0],[d,0,2,5,0]] Is there any easy way to achieve this?
possible better answer: http://stackoverflow.com/a/48500733
has answer: http://stackoverflow.com/a/48501019
has answer: http://stackoverflow.com/a/48500733
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/83994511

http://stackoverflow.com/q/48547639
has answer: http://stackoverflow.com/a/48547821
accepted answer: http://stackoverflow.com/a/48547821
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/84106998
possible better answer: http://stackoverflow.com/a/48548031
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: if-statement
has answer: http://stackoverflow.com/a/48548031
has comment: http://stackoverflow.com/comment/84091683
tagged with: pandas
score: 1
upvote count: 1
has title: Counting values in a row that match a condition - Python
has comment: http://stackoverflow.com/comment/84091365
favorite count: 0
has body: I have a dataframe that contains integers and NaNs. I am almost looking to create a countif statement, which will iterate over each value in a row and count values that are greater than 0. Here is an example df: d = {'col1': [1, "", 5, 0], 'col2': [3, 4, "", 7], 'col3': [2, 8, "", 3]} df = pd.DataFrame(data=d) df = df.convert_objects(convert_numeric = True) df Out[356]: col1 col2 col3 0 1.0 3.0 2.0 1 NaN 4.0 8.0 2 5.0 NaN NaN 3 0.0 7.0 3.0 I have been using this function below that counts values that are not NaNs, however I want to place a condition on this (greater than 0 &amp; not NaN). df.apply(lambda x: x.count(), axis = 1) Out[357]: 0 3 1 2 2 1 3 3 dtype: int64 If anyone could offer advice on how to count values in a row based on a certain condition that would be very useful, thanks in advance.
type: Question

http://stackoverflow.com/comment/84217541
type: Comment
type: QuestionComment
has text: The problem is in this line: "l = [[", ".join ([s.subject for s in x.subject.all ()]), s.id] for x in classes]" because when you try to build the Second list, you use the variable "s" out of context, because "s" only exists within the creation of the second list. What do you want to do in this line?
comment on: http://stackoverflow.com/q/48609401
score: 0

http://stackoverflow.com/q/48630460
tagged with: threshold
has body: I have a 3D time series data matrix from January 1st, 1979 to December 31st, 2005. The matrix is currently 9862x360x720 (daily rainfall x 0.5° latitude x 0.5° longitude). I want to sum the daily rainfall into monthly rainfall (a total of 324 months) while also setting a threshold for summing NaN values. In other words, If there are more than 10 daily NaN values for a particular lat/lon grid cell, I want to marked the monthly summed cell as NaN. If there are less than 10 daily NaN values for the grid cell, I want to sum the remaining non-NaN daily values and use that as the monthly value. I had success using the xarray library's "resample" function, but I couldn't figure out a way to set a threshold for NaN values. Everything I've read says to use sum or nansum functions, but I can't find a way to set a NaN threshold through either of those functions. I'm open to any method at this point (xarray or otherwise). import netCDF4 import numpy as np import xarray as xr import pandas as pd f = netCDF4.Dataset("daily_data", 'r') daily_dataset = xr.Dataset({'precipitation': (['time', 'lat', 'lon'], f['precipitation'][:, :, :])}, coords={'lat': (f['lat'][:]), 'lon': (f['lon'][:]), 'time': pd.date_range('1979-01-01', periods=9862)}) monthly_dataset = daily_dataset['precipitation'].resample('M', dim='time', how='sum', skipna=False) I was able to sum the daily data to monthly with the above code, but I was not able to set a NaN threshold. The daily data is currently stored in a NetCDF file.
has comment: http://stackoverflow.com/comment/84258103
tagged with: python-xarray
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84258022
accepted answer: http://stackoverflow.com/a/48630659
tagged with: sum
tagged with: python
has title: Sum a daily time series into a monthly time series with a NaN value threshold
tagged with: nan
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48630659
downvote count: 2
answer count: 1

http://stackoverflow.com/q/48521762
has body: I am trying to write a py.test test with selenium to test a complex website. Because the setup is complex, the test can fail even before the actual test. But in such a case I want to be able to call a 'debug' function (maybe its a teardown function which I can use to debug things. Example: The test uses a fixture which returns a selenium webdriver def test1(driver): driver.get("my page") ... other tests, login, etc etc But now the call driver.get fails because of any reason. But in such a case I want to be able to investigate things like def debug(driver): driver.screenshot(...) print(driver.page_source) ... driver.quit() (including the shutdown of the driver, as the browser would stay open) with the same driver instance as has been used in the test method. Is there a way to do that?
type: UnansweredQuestion
has title: How to call a 'debug' method in py.test in case of an failure?
answer count: 1
tagged with: python
score: 2
downvote count: 0
tagged with: pytest
has answer: http://stackoverflow.com/a/48525528
tagged with: selenium
has comment: http://stackoverflow.com/comment/84042093
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/a/48587630
has comment: http://stackoverflow.com/comment/84173064
has body: ImportanceOfBeingErnest correctly pointed out that my first comment wasn't entirely clear (or accurately worded).. Most plotting functions in mpl have a kwarg: norm= this denotes a class (subclass of mpl.colors.Normalize) that will map your array of data to the values [0 - 1] for the purpose of mapping to the colormap, but not actually impact the numerical values of the data. There are several built in subclasses, and you can also create your own. For this application, I would probably utilize BoundaryNorm. This class maps N-1 evenly spaced colors to the space between N discreet boundaries. I have modified the example slightly to better fit your application: #adaptation of https://matplotlib.org/users/colormapnorms.html#discrete-bounds import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from matplotlib.mlab import bivariate_normal #example data N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \ - 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2 Z1 = Z1/0.03 ''' BoundaryNorm: For this one you provide the boundaries for your colors, and the Norm puts the first color in between the first pair, the second color between the second pair, etc. ''' fig, ax = plt.subplots(3, 1, figsize=(8, 8)) ax = ax.flatten() # even bounds gives a contour-like effect bounds = np.linspace(-1, 1) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) pcm = ax[0].pcolormesh(X, Y, Z1, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical') # clipped bounds emphasize particular region of data: bounds = np.linspace(-.2, .5) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) pcm = ax[1].pcolormesh(X, Y, Z1, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical') # now if we want 0 to be white still, we must have 0 in the middle of our array bounds = np.append(np.linspace(-.2, 0), np.linspace(0, .5)) norm = c…
type: Answer
has comment: http://stackoverflow.com/comment/84173258
has comment: http://stackoverflow.com/comment/84192333
accepted answer of: http://stackoverflow.com/q/48584159
score: 0
has comment: http://stackoverflow.com/comment/84172802
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84172939
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48584159

http://stackoverflow.com/q/48494877
has comment: http://stackoverflow.com/comment/83982900
answer count: 1
has answer: http://stackoverflow.com/a/48497571
has comment: http://stackoverflow.com/comment/83983918
type: Question
tagged with: python-3.x
has body: So I'm reading contents from the database and I have appended necessary elements into lists. I am trying to display each elements in the list in a label. For example, I have a list from the database: test = ['Name' , 'Age', 'Location'] I want to display the label with text- Name (i.e test[0]) on button press. Likewise, when I press the button again I want the label to display, Age (i.e. test[1]) and so on upto the length of the list. What I tried: from tkinter import * import sqlite3 # connecting to the database conn = sqlite3.connect('database.db') c = conn.cursor() # empty lists to later append elements into all_ids = [] all_names = [] all_time = [] # execute sql sql = ('SELECT * FROM appointments') res = c.execute(sql) for r in res: idd = r[0] name = r[1] time = r[6] all_ids.append(idd) all_names.append(name) all_time.append(time) # variable that determines the index of elements on button press (updates) x = 0 class Application: def __init__(self, master): self.master = master self.heading = Label(master, text="Appointments", font=('arial 60 bold'), fg='steelblue') self.heading.place(x=300, y=0) self.btn = Button(master, text="Next Patient", width=20, height=2, command=self.func) self.btn.place(x=500, y=600) self.display = Label(self.master, text="", font=('arial 200 bold')) self.display.place(x=500, y=80) self.nd = Label(self.master, text="", font=('arial 80 bold')) self.nd.place(x=200, y=400) def func(self): global x for i in all_ids: self.display.config(text=str(all_ids[x])) self.nd.config(text=str(all_names[x])) x += 1 root = Tk() v = Application(root) root.geometry("1366x768+0+0") root.resizable(False, False) root.mainloop() When I press the button, last element is displayed and when I press again, I get list index out of range. Can anyone please tell me what I'm doing wrong? Thanks Output is the label of last element in the list and error on clicking again: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.5/tkinter/__i…
tagged with: python
has comment: http://stackoverflow.com/comment/83983120
has comment: http://stackoverflow.com/comment/83983516
accepted answer: http://stackoverflow.com/a/48497571
has title: Display labels using loop on button press
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/16005707
has comment: http://stackoverflow.com/comment/84001701
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83983414
has comment: http://stackoverflow.com/comment/83983597

http://stackoverflow.com/comment/84136721
has text: @mkrieger1 - I only see `INFO` in the clone.log,so probably `ch` and the "NOT CAPTURING" is on the console
comment on: http://stackoverflow.com/q/48569937
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/50525605
answers question: http://stackoverflow.com/q/48552036
score: 0
type: Answer
has body: First Install psycopg2 on both the python version, only if you don't which one you are targetting. Command - pip install psycopg2 (for python 3) Command - pip3 install psycopg2 (for python 2) Although, if it does not work there is one more way as well using the .whl(wheel file) using the wheel - pip install and from here you can download .whl file pip install your.whl Download the wheel file taking the version of your python in mind. Psycopg2 whl file Hope it helps.

python-idle
tags question: http://stackoverflow.com/q/48534423
tags question: http://stackoverflow.com/q/48566080
tags question: http://stackoverflow.com/q/48638024
tag name: python-idle
tags question: http://stackoverflow.com/q/48528477
type: Tag
tags question: http://stackoverflow.com/q/48581973

http://stackoverflow.com/q/48555034
has comment: http://stackoverflow.com/comment/84106329
tagged with: function
has comment: http://stackoverflow.com/comment/84106332
has comment: http://stackoverflow.com/comment/84107426
answer count: 1
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/48555060
favorite count: 0
type: Question
score: 0
tagged with: strip
tagged with: nonetype
has title: 'NoneType' object has no attribute 'strip'" on my list modifier function in Python 3
has body: I'm a Python newbie. I'm trying to define a function that takes a string list and adds html tags to its elements. For example, it modifies: list_1 = ["hey", "hello", "Joe"] to html_list = [" "," hey ", " hello ", " Joe ",> " "] It is raising the following exception: 'NoneType' object has no attribute 'strip' Here's my code: def html_list(input_list): for index in range(len(input_list)): input_list[index] = " " + input_list[index] + " " input_list.insert(0," ") input_list.append(" ") print(input_list) list_1 = ["hey", "hello", "Joe"] html_list(list_1)
tagged with: python
has comment: http://stackoverflow.com/comment/84107869
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48555060

http://stackoverflow.com/a/48502013
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48501768
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48501768
upvote count: 1
has body: you can convert those strings into PeriodIndex(freq='Q') and then (if needed) into timestamp(freq='M') Demo: In [272]: df Out[272]: qt 0 200101 1 201504 In [273]: pd.PeriodIndex(df.qt.astype(str).str.replace(r'(\d{4})[0]?(\d{1})', r'\1q\2'), freq='Q') \ .to_timestamp(freq='M') Out[273]: DatetimeIndex(['2001-01-31', '2015-10-31'], dtype='datetime64[ns]', name='qt', freq=None)

http://stackoverflow.com/a/48530927
score: 1
type: Answer
upvote count: 1
has body: I think I am doing manually what Ajax1234 does with groupby, here it comes: list_in = [['aa', 2, 'bb'], ['aa', 2, 'bb']] grp = {} for inner in list_in: key = (inner[0],inner[-1]) # tuple is immutable and can be key grp.setdefault(key,0) # create key if needed with value 0 grp[key]+=inner[1] # add value list_out = [[k[0],grp[k],k[1]] for k in grp] # reassemble from dictionary print(list_out) Output: 'aa', 4, 'bb' This will also include any sublist that has NO duplicate entry. Not sure if thats ok.
answers question: http://stackoverflow.com/q/48530728
downvote count: 0

http://stackoverflow.com/q/48585959
tagged with: google-cloud-platform
linked to: http://stackoverflow.com/q/40767189
score: 7
linked to: http://stackoverflow.com/q/46778848
has body: I have upgraded to the latest apache_beam[gcp] package via pip install --upgrade apache_beam[gcp]. However, I noticed that Reshuffle() does not appear in the [gcp] distribution. Does this mean that I will not be able to use Reshuffle() in any dataflow pipelines? Is there any way around this? Or is it possible that the pip package is just not up to date and if Reshuffle() is in master on github then it will be available on dataflow? Based on the response to this question I am trying to read data from BigQuery and then randomize the data before I write it to CSV's in a GCP storage bucket. I have noticed that my sharded .csv's that I am using to train my GCMLE model are not truly random. Within tensorflow I can randomize the batches, but that will only randomize the rows within each file that is built up in the queue and my issue is that currently the files being generated are biased in some way. If there are any suggestions for other ways to shuffle right before writing to CSV in dataflow that would be much appreciated.
favorite count: 0
type: Question
answer count: 1
downvote count: 0
tagged with: apache-beam
tagged with: python
upvote count: 7
tagged with: google-cloud-dataflow
accepted answer: http://stackoverflow.com/a/48589126
has answer: http://stackoverflow.com/a/48589126
has title: apache_beam.transforms.util.Reshuffle() not available for GCP Dataflow
type: AnsweredQuestion

http://stackoverflow.com/q/48500434
has title: How to find end points of bw connected components?
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/83995967
has body: I am using the following code for labeling the connected components in a binary image: def connected_component(img): output = cv2.connectedComponentsWithStats(img, 8) num_labels = output[0] labels = output[1] return labels, num_labels I am calling it in the main as follows: labels, num_labels = connected_component(seg_f) I wish to find the end points of each connected component (given that the connected components are lines). I have tried to do it as follows but I am getting a wrong output: cropped_max_y_1=[] cropped_min_y_1=[] cropped_max_x_1=[] cropped_min_x_1=[] seg_f, _ = ndimage.label(seg_f) num_instances = np.max(np.max(seg_f)) for instance_id in range(1,num_instances+1): im_inst = seg_f == instance_id points = np.nonzero(im_inst) cropped_min_x_1.append(np.min(points[0])) cropped_min_y_1.append(np.min(points[1])) cropped_max_x_1.append(np.max(points[0])+1) cropped_max_y_1.append(np.max(points[1])+1) Kindly suggest changes or an alternate approach to do the same. Here is a sample input: The expected output would be, say, coordinates of the joints
tagged with: labeling
has comment: http://stackoverflow.com/comment/83994649
tagged with: connected-components
accepted answer: http://stackoverflow.com/a/48503782
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84002680
has comment: http://stackoverflow.com/comment/84005623
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84026170
upvote count: 0
has comment: http://stackoverflow.com/comment/83995224
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48503782
tagged with: image-processing
has comment: http://stackoverflow.com/comment/83995414

http://stackoverflow.com/comment/84010975
type: QuestionComment
has text: Please check the answer. Let me know if the problem persists.
score: 0
comment on: http://stackoverflow.com/q/48507546
type: Comment

http://stackoverflow.com/comment/84123680
has text: In the example above there are 4 actual values and 3 missing values that I would like to interpolate and bring to the resulting `df`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48563101
score: 0

http://stackoverflow.com/comment/84030096
type: Comment
score: 0
has text: You might want to clarify that in the question then, because you're saying that "This context is shared among all samples", not just those in a batch. About the size problem, you won't be able to work around that I'm afraid. If the data doesn't fit in the graph when you declare it manually, it also won't fit when you try to run the input pipeline.
type: QuestionComment
comment on: http://stackoverflow.com/q/48517244

http://stackoverflow.com/q/48527447
score: 0
has title: Save html extract to list of list Python
answer count: 3
accepted answer: http://stackoverflow.com/a/48528401
tagged with: beautifulsoup
type: Question
has body: I extract some data from a html page. My output is: 0 0 0 0 131997 https://www.google.com.ar/ google.com.ar 0 0 0 0 134930 https://www.a-a.com/ a-a.com And I'm looking for this kind of output: [['0','0','0','0','131997','https://www.google.com.ar/','google.com.ar'],['0','0','0','0','134930','https://www.a-a.com/','a-a.com']] Here is my python code: sitios = requests.get(url_sitios, auth=HTTPBasicAuth(user, passwd)) sitios2 = sitios.text html = sitios2 soup = BeautifulSoup(html, 'lxml') #add the 'lxml' parser for item in soup.find_all(['nombre', 'url', 'sitio_id', 'ultimas24hrs']): a = item.text + ',' print a
has answer: http://stackoverflow.com/a/48528401
has answer: http://stackoverflow.com/a/48527837
possible better answer: http://stackoverflow.com/a/48527837
has answer: http://stackoverflow.com/a/48527980
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48569937
score: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84136721
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84137171
has body: I have setup logging as follows in my script, however it doesn't capture the warning,debug or when the script fails with an error like TypeError: 'bool' object has no attribute '__getitem__' ### Setup logging log = os.path.join(os.path.dirname(os.path.realpath(__file__)),'clone.log') logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(filename)-15s %(funcName)-20s %(lineno)-5s %(levelname)-8s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S") ch.setFormatter(formatter) logger.addHandler(ch) fh = logging.FileHandler(log, 'w') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(fh) Current log: 2018-02-01 10:44:20 cloneradar_keyword.py clone 61 2018-02-01 10:44:24 cloneradar_keyword.py clone 130 INFO : Updating milestone &amp; category 2018-02-01 10:44:24 cloneradar_keyword.py clone 131 INFO : 12 2018-02-01 10:44:24 cloneradar_keyword.py clone 132 INFO : None 2018-02-01 10:44:24 cloneradar_keyword.py clone 61 INFO : Logging into radar 2018-02-01 10:44:24 cloneradar_keyword.py clone 68 INFO : Getting original Radar details 2018-02-01 10:44:28 cloneradar_keyword.py clone 81 INFO : Creating clone NOT CAPTURING: 2018-02-01 10:44:28 radar.py _login 98 DEBUG : new_time : 1517510668.06 2018-02-01 10:44:28 radar.py _login 99 DEBUG : Difference : 3.45849394798 2018-02-01 10:44:28 radar.py _login 132 DEBUG : Cookie is still valid... 2018-02-01 10:44:28 radar.py CreateCloneProblem 298 INFO : {"component":{"name":"Resource Meter","version":"Lanai"},"originatorOfClone": true,"reason":"Cloning for automation"} 2018-02-01 10:44:28 radar.py CreateCloneProblem 302 WARNING : Error: Unable to get data. Server came back with: 2018-02-01 10:44:28 radar.py CreateCloneProblem 303 WARNING : {"message":"The component you've selected is closed. There is no follow-on component. A problem cannot be saved to a closed component with no follow-on. Please select a differen…
downvote count: 0
has comment: http://stackoverflow.com/comment/84136536
has comment: http://stackoverflow.com/comment/84136520
tagged with: python
has comment: http://stackoverflow.com/comment/84136644
has title: How to capture debugging,warning and error messages?
answer count: 0

http://stackoverflow.com/comment/83981095
type: Comment
type: QuestionComment
has text: Is `"Result: %s"% np.poly1d(parray)` what you're looking for?
score: 0
comment on: http://stackoverflow.com/q/48493533

http://stackoverflow.com/q/48613920
has comment: http://stackoverflow.com/comment/84225011
tagged with: python
tagged with: plot
type: AnsweredQuestion
tagged with: colorbar
has body: I'm trying to create a pcolormesh plot with a discrete colorbar. The output should fulfil these criteria: The first level should be white The data should be cut off at some level Data above the cut off should have a separate colour (namely the last colour of the colormap) I am almost there but the 'extend' keyword does not behave the way I would expect it to (the colour in the "max-arrow" is the same as for the last level - see example). How do I set values above 'vmax' to a separate colour (i.e., the last colour of whatever colormap I use) import numpy as np import xarray as xr import matplotlib as mpl import matplotlib.pyplot as plt ds = xr.Dataset( coords={'lon': np.arange(-180, 180, 10), 'lat': np.arange(-85, 90, 10)}, data_vars={'data': (('lat', 'lon'), np.random.rand(18, 36))}) cmap = plt.cm.get_cmap('Reds') cmap.set_under('w') # cmap.set_over() # do something here? levels = np.arange(0, .7, .1) ds.data.plot.pcolormesh( cmap=cmap, vmin=levels[1], # vmax=levels[-1], extend='max', norm = mpl.colors.BoundaryNorm(levels, ncolors=cmap.N, clip=False) ) I'm using xarray but the behaviour is the same for plt.pcolormesh: p = plt.pcolormesh( np.arange(-180, 180, 10), np.arange(-85, 90, 10), np.random.rand(18, 36), cmap=cmap, vmin=levels[1], # vmax=levels[-1], norm = mpl.colors.BoundaryNorm(levels, ncolors=cmap.N, clip=False) ) plt.colorbar(p, extend='max')
tagged with: matplotlib
downvote count: 0
answer count: 1
has title: Use of extend in a pcolormesh plot with discrete colorbar
favorite count: 0
score: 9
type: Question
tagged with: colormap
accepted answer: http://stackoverflow.com/a/48614231
upvote count: 9
has answer: http://stackoverflow.com/a/48614231

http://stackoverflow.com/q/48614548
linked to: http://stackoverflow.com/q/30647844
has comment: http://stackoverflow.com/comment/84246137
tagged with: python
has title: Scrapy delay etiquette
has comment: http://stackoverflow.com/comment/84392812
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84280043
type: UnansweredQuestion
upvote count: 1
tagged with: scrapy
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84393072
has body: I'm currently working on a project to scrape a Wiki-like website that is a database of historical people and some basic information (all the individual information is on its own page). There are several million (a little under 3 million) names, so I want the crawler to actually completely scrape the information while not hurting the website. I'm completely new to this so I wondered if people could guide me to best practices in web scraping. Specifically, I've posted a little from the settings file below: # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 DOWNLOAD_DELAY = 5 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 AUTOTHROTTLE_ENABLED = True # The initial download delay AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: AUTOTHROTTLE_DEBUG = True I've uncommented out the AutoThrottle settings and set DOWNLOAD_DELAY to 5 seconds. However, this is going to make the scraper move too slowly. Is this unavoidable if I don't want to get banned? What do people usually set the DOWNLOAD_DELAY parameter to?

user-interface
tags question: http://stackoverflow.com/q/48600439
tags question: http://stackoverflow.com/q/48623964
tags question: http://stackoverflow.com/q/48505483
tags question: http://stackoverflow.com/q/48637047
tags question: http://stackoverflow.com/q/48600497
tags question: http://stackoverflow.com/q/48505575
tags question: http://stackoverflow.com/q/48588516
tags question: http://stackoverflow.com/q/48544583
tags question: http://stackoverflow.com/q/48645213
tags question: http://stackoverflow.com/q/48600707
tags question: http://stackoverflow.com/q/48613042
tags question: http://stackoverflow.com/q/48525743
type: Tag
tags question: http://stackoverflow.com/q/48542355
tags question: http://stackoverflow.com/q/48599690
tags question: http://stackoverflow.com/q/48590348
tags question: http://stackoverflow.com/q/48498468
tags question: http://stackoverflow.com/q/48596114
tags question: http://stackoverflow.com/q/48533903
tag name: user-interface
tags question: http://stackoverflow.com/q/48570796
tags question: http://stackoverflow.com/q/48549421
tags question: http://stackoverflow.com/q/48518575
tags question: http://stackoverflow.com/q/48535643
tags question: http://stackoverflow.com/q/48596482

http://stackoverflow.com/comment/84237079
score: 0
has text: this is not the answer to question, but by looking at the image attached, you should use `micros()` instead of `millis()`. Because for same timestamp you have more than one adc values.
comment on: http://stackoverflow.com/q/48620151
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48623937
score: 0
tagged with: subprocess
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84244573
has comment: http://stackoverflow.com/comment/84244713
has title: python copy os.system. resulting file is empty
type: Question
has body: I have a simple progam to read and write a txt file in python: import os with open("1.txt") as infile,open("2.txt","w") as outfile: for line in infile: outfile.write(line) ####problem#### os.system("cp 2.txt 3.txt") ####problem#### The resulting file "2.txt" is fine, but "3.txt" is empty. Can anyone give a solution for this. 1.txt simply contains two words: two words
tagged with: python
has comment: http://stackoverflow.com/comment/84244447
has comment: http://stackoverflow.com/comment/84244523

http://stackoverflow.com/q/48633694
tagged with: python
score: 0
has body: My endpoint is defined as @app.route('/PollingEngineExceptions',methods=['POST']) def PollingEngineExceptions(PollingException): .. return response Im posting to this endpoint def test_atg_polling_exception(self): jsonEncoder = CustomJSONEncoder() a= PollingException('System.OutOfMemoryException','System.OutOfMemoryException','System.OutOfMemoryException','2009-02-15T00:00:00Z') jsonmsg=jsonEncoder.default(a) response = requests.post("http://localhost:5000/PollingEngineExceptions",data=jsonmsg) when I POSTing im getting Traceback (most recent call last): File "/Library/Python/2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/Library/Python/2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/Library/Python/2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/Library/Python/2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/Library/Python/2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) TypeError: PollingEngineExceptions() takes exactly 1 argument (0 given) What Im doing wrong here?
has answer: http://stackoverflow.com/a/48634012
answer count: 1
has title: Type Error:PollingEngineExceptions() takes exactly 1 argument (0 given) in python
has comment: http://stackoverflow.com/comment/84264639
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/84053302
comment on: http://stackoverflow.com/a/48528492
score: 0
type: Comment
has text: And one more thing I just noticed – it may be faster to use `numpy.diff()` instead of `np.r_[True,sorted_a[1:] != sorted_a[:-1],True]`.
type: AnswerComment

http://stackoverflow.com/comment/84158552
comment on: http://stackoverflow.com/q/48581080
type: Comment
type: QuestionComment
score: 1
has text: Please edit your post with the code you are using with code formating

http://stackoverflow.com/q/48531897
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84059557
score: 2
type: AnsweredQuestion
has title: Parsing a python dictionary in bash shell
has comment: http://stackoverflow.com/comment/84059442
has comment: http://stackoverflow.com/comment/84143416
accepted answer: http://stackoverflow.com/a/48573469
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48573469
tagged with: shell
has body: $ query_op=$(ssh -p 29418 myreview-server.com gerrit query --files --current-patch-set --format=JSON --commit-message change:99934 | head -n 1 | python -c "import sys, json; print json.load(sys.stdin)['currentPatchSet']['files']") $ echo $query_op [{u'deletions': 0, u'insertions': 11, u'type': u'ADDED', u'file': u'/COMMIT_MSG'}, {u'deletions': 0, u'insertions': 2, u'type': u'MODIFIED', u'file': u'foo/bar/baz/info.txt'}] How do I find if any of the file starts with string foo? in the above shown example, I need to do some operation as there is a file starting with foo/ which is foo/bar/baz/info.txt, if no file starts with foo/ in the entire dictionary value, then I need to do different operation.
favorite count: 0

http://stackoverflow.com/comment/84259865
has text: Hi, @roganjosh. The preview in the Developer Tools returns JSON.
score: 0
comment on: http://stackoverflow.com/q/48631253
type: Comment
type: QuestionComment

primes
tags question: http://stackoverflow.com/q/48533767
tags question: http://stackoverflow.com/q/48502586
type: Tag
tag name: primes
tags question: http://stackoverflow.com/q/48598558

http://stackoverflow.com/a/48616722
has body: Why don't you try the following code for the 2nd example: import numpy as np from keras import backend as K import tensorflow as tf arr = tf.constant(np.random.rand(19, 19, 5, 80)) with tf.Session() as sess: arr = sess.run(arr) np_argmax = np.argmax(arr, axis=-1) np_max = np.max(arr, axis=-1) k_argmax = K.argmax(arr, axis=-1) k_max = K.max(arr, axis=-1) print('np_argmax shape: ', np_argmax.shape) print('np_max shape: ', np_max.shape) print('k_argmax shape: ', k_argmax.shape) print('k_max shape: ', k_max.shape) After arr = tf.constant(np.random.rand(19, 19, 5, 80)), the type of arr is tf.Tensor, but after running arr = sess.run(arr) its type will be changed to numpy.ndarray.
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48615667

http://stackoverflow.com/a/48574332
accepted answer of: http://stackoverflow.com/q/48572051
type: Answer
answers question: http://stackoverflow.com/q/48572051
has body: If you want a scaled collision rect/hitbox, you need to give your sprites a second rect (I call it hitbox here). You have to do that because pygame blits the images/surfaces at the topleft coords of the self.rect. So the first rect self.rect serves as the blit position and the self.hitbox is used for the collision detection. You also need to define a custom callback function for the collision detection that you have to pass to pygame.sprite.spritecollide as the fourth argument. def collided(sprite, other): """Check if the `hitbox` rects of the two sprites collide.""" return sprite.hitbox.colliderect(other.hitbox) collided_sprites = pg.sprite.spritecollide(player, enemies, False, collided) Here's a complete example (the self.rects are the green rectangles and the self.hitboxes are the reds): import pygame as pg from pygame.math import Vector2 class Entity(pg.sprite.Sprite): def __init__(self, pos, *groups): super().__init__(*groups) self.image = pg.Surface((70, 50)) self.image.fill((0, 80, 180)) self.rect = self.image.get_rect(center=pos) # A inflated copy of the rect as the hitbox. self.hitbox = self.rect.inflate(-42, -22) self.vel = Vector2(0, 0) self.pos = Vector2(pos) def update(self): self.pos += self.vel self.rect.center = self.pos self.hitbox.center = self.pos # Also update the hitbox coords. def collided(sprite, other): """Check if the hitboxes of the two sprites collide.""" return sprite.hitbox.colliderect(other.hitbox) def main(): screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() all_sprites = pg.sprite.Group() player = Entity((300, 200), all_sprites) enemies = pg.sprite.Group( Entity((100, 250), all_sprites), Entity((400, 300), all_sprites), ) done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True elif event.type == pg.MOUSEMOTION: player.pos = event.pos all_sprites.update() # Pass the custom collided callback function to spritecollide. collided_sprites = pg.sprite.spritecollide( player, enemies, Fals…
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48614471
has title: ValueError: Data type datetime64[ns] not understood. Please report an error to the developers
tagged with: python
has body: I'm trying to convert a pandas df using df.to_stata. In the process I'm getting an error: ValueError: Data type datetime64[ns] not understood. Please report an error to the developers A generalized version of the script is: df.to_stata('myfile.dta') For reference, I'm using stacked panel data in the form of: Date id var 2017-01-01 A 5 2017-01-02 A 3 2017-01-03 A 4 2017-01-01 B 2 2017-01-02 B -4 2017-01-03 B 1 2017-01-01 C -2 2017-01-02 C 0 2017-01-03 C 6 Also, when I try to rewrite the line as df.to_stata('myfile.dta', convert_dates={'Date' : 'td' }) I get KeyError: 0 I've transferred to stata and csv many times in the past without issue, and my usual google-search has not led me to a solution.
answer count: 0
downvote count: 0
upvote count: 1
score: 1
tagged with: datetime64
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/48644831
has title: Executing a Python Executable ZIP file using execfile()
answer count: 0
has comment: http://stackoverflow.com/comment/84286346
type: UnansweredQuestion
tagged with: python
has body: We can execute a single Python file inside another Python file using execfile(), but it only works on .py files. In Python we can create an executable ZIP file (that contains __main__.py and other files) How can I execute a ZIP file using execfile()?
score: 0
has comment: http://stackoverflow.com/comment/84299535
has comment: http://stackoverflow.com/comment/84299419
type: Question
tagged with: http://stackoverflow.com/tag/zip

http://stackoverflow.com/comment/83995701
has text: It is said on their support page (https://developers.soundcloud.com/support) that they answer all the questions just right here on SO. This is why I posted my question here. Do I miss something?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48497566
type: QuestionComment

http://stackoverflow.com/q/48595728
has comment: http://stackoverflow.com/comment/84188653
has title: python nlgserv not starting
tagged with: python
tagged with: jython
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55051166
answer count: 1
has comment: http://stackoverflow.com/comment/84188671
type: Question
has body: I tried to install and use nlgserv from https://github.com/mnestis/nlgserv On the first line of the code (import nlgserv) it allready brings an error: File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\nlgserv__init__.py", line 1, in from _controller import start_server, stop_server ModuleNotFoundError: No module named '_controller' (ps: jython is installed)
score: 0

http://stackoverflow.com/q/48512885
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/84021433
has title: max() arg is an empty sequence inside function
has comment: http://stackoverflow.com/comment/84020946
tagged with: python
has answer: http://stackoverflow.com/a/48513236
has comment: http://stackoverflow.com/comment/84020736
has comment: http://stackoverflow.com/comment/84021233
has comment: http://stackoverflow.com/comment/84035014
has comment: http://stackoverflow.com/comment/84020740
score: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4114167
has comment: http://stackoverflow.com/comment/84020675
has body: I have been working on a problem that should return a list with all k-Primed numbers within a range, noted as (k, start, end). The code I wrote until then is as follows: def check_prime(x): c=2 if x==2: return True if x==0 or x==1: return False while c&lt;x: if x%c==0: return False break else: c+=1 if c==x: return True def prime_divs(x): aux=2 nums=[] primes=[] i=0 while aux&lt;x/2: if x%aux==0: nums.append(aux) aux+=1 while i&lt;len(nums): if check_prime(nums[i])==True: primes.append(nums[i]) i+=1 return primes def k_prime(x): k=0 primes=prime_divs(x) if check_prime(x)==True: k=1 else: while x!=1: if x%max(primes)==0: x=int(x/max(primes)) k+=1 else: del primes[len(primes)-1] return k def count_Kprimes(k_lim, start, end): i=start nums=[] while i&lt;=end: if k_lim==k_prime(i): nums.append(i) i+=1 return nums After testing the last function, I get this error: line 38, in k_prime if x%max(primes)==0: ValueError: max() arg is an empty sequence All the other functions before count_Kprimes work properly. Why is the last one leading to this error?

http://stackoverflow.com/comment/123306734
has text: You might want to point out, that it is about the leading slash in the second line. Otherwise this is a little hard to read.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/69758153

http://stackoverflow.com/comment/84125399
type: Comment
type: QuestionComment
has text: Im using python 3.6 @IgnacioVergaraKausel
score: 0
comment on: http://stackoverflow.com/q/48564742

parsing
tags question: http://stackoverflow.com/q/48599866
tags question: http://stackoverflow.com/q/48537430
tags question: http://stackoverflow.com/q/48542738
tags question: http://stackoverflow.com/q/48602313
tags question: http://stackoverflow.com/q/48567205
tags question: http://stackoverflow.com/q/48549204
tags question: http://stackoverflow.com/q/48610824
tags question: http://stackoverflow.com/q/48531312
tags question: http://stackoverflow.com/q/48594405
tags question: http://stackoverflow.com/q/48639744
tags question: http://stackoverflow.com/q/48589706
tags question: http://stackoverflow.com/q/48546664
tags question: http://stackoverflow.com/q/48503568
tags question: http://stackoverflow.com/q/48625029
tags question: http://stackoverflow.com/q/48633982
tags question: http://stackoverflow.com/q/48603692
tag name: parsing
tags question: http://stackoverflow.com/q/48612813
tags question: http://stackoverflow.com/q/48569243
tags question: http://stackoverflow.com/q/48505891
tags question: http://stackoverflow.com/q/48588049
tags question: http://stackoverflow.com/q/48609484
tags question: http://stackoverflow.com/q/48537209
tags question: http://stackoverflow.com/q/48593656
tags question: http://stackoverflow.com/q/48560748
tags question: http://stackoverflow.com/q/48572558
tags question: http://stackoverflow.com/q/48584755
tags question: http://stackoverflow.com/q/48620892
tags question: http://stackoverflow.com/q/48567259
tags question: http://stackoverflow.com/q/48530336
tags question: http://stackoverflow.com/q/48590278
tags question: http://stackoverflow.com/q/48532723
tags question: http://stackoverflow.com/q/48500167
tags question: http://stackoverflow.com/q/48607163
tags question: http://stackoverflow.com/q/48594014
tags question: http://stackoverflow.com/q/48583906
tags question: http://stackoverflow.com/q/48518306
tags question: http://stackoverflow.com/q/48503665
tags question: http://stackoverflow.com/q/48627527
type: Tag

http://stackoverflow.com/q/48569618
possible better answer: http://stackoverflow.com/a/48570321
tagged with: python
tagged with: google-cloud-storage
has answer: http://stackoverflow.com/a/48570321
type: Question
has title: How do I use pandas.read_csv on Google Cloud ML?
has body: I'm trying to deploy a training script on Google Cloud ML. Of course, I've uploaded my datasets (CSV files) in a bucket on GCS. I used to import my data with read_csv from pandas, but it doesn't seem to work with a GCS path. How should I proceed (I would like to keep using pandas) ? import pandas as pd data = pd.read_csv("gs://bucket/folder/file.csv") output : ERROR 2018-02-01 18:43:34 +0100 master-replica-0 IOError: File gs://bucket/folder/file.csv does not exist
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/52503114
linked to: http://stackoverflow.com/q/42799117
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/48779805
favorite count: 0
has answer: http://stackoverflow.com/a/48779805
type: AnsweredQuestion
answer count: 3
tagged with: google-cloud-ml

http://stackoverflow.com/comment/84263305
comment on: http://stackoverflow.com/a/48615193
has text: And, here, what in any other language I've dealt with it's just function(arg), but in Python there's all this ... stuff ... that to me means nothing (other than convoluted begging for syntax errors). Anyone have a reference for a book, video, or course that can succinctly explain to me why we're saddled with all this verbosity - and how I can come to see it as anything useful? I'm not having luck finding anything USEFUL...
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48544597
has comment: http://stackoverflow.com/comment/84084587
answer count: 0
type: UnansweredQuestion
downvote count: 0
score: 6
linked to: http://stackoverflow.com/q/9172263
has body: I am trying to understand the following error in python: In []: tup = tuple(['foo', [1,2], True]) In []: tup[1]+=[2] This leads to the following error: TypeError: 'tuple' object does not support item assignment I understand this is because tuples are not mutable. However, the second element of the tuple is now mutated in the manner I desired. In []: tup Out[]: ('foo', [1, 2, 2], True) Can someone please explain what happened here. I got an error but the code did exactly what I wanted. What did the code fail to accomplish that is being shown by the error? Also, I understand that the append method can accomplish the same. In []: tup[1].append(2) In []: tup Out[]: ('foo', [1, 2, 2, 2], True) But I still want to understand what happened in the first case above.
has title: Mutating a list inside a tuple in Python
duplicate of: http://stackoverflow.com/q/9172263
tagged with: python
upvote count: 6
favorite count: 0
type: Question

http://stackoverflow.com/comment/84204091
has text: Great solution @steffen. Can you explain the line c,_ = .... (I am a python newbie, and not seen this before).
type: AnswerComment
comment on: http://stackoverflow.com/a/48598219
score: 0
type: Comment

http://stackoverflow.com/q/48635148
has answer: http://stackoverflow.com/a/48635209
accepted answer: http://stackoverflow.com/a/48635209
has comment: http://stackoverflow.com/comment/84267102
tagged with: dataframe
tagged with: python
has body: Currently, I am working with a pandas.DataFrame that I need to divide the entire dataframe by a certain value except for one row. It is easy to divide the entire dataframe by one value, however I would like to keep one of the rows the exact same. For example, if I had a dataframe like below: A B C D 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 1 1 1 1 10000 10000 10000 10000 10000 10000 10000 10000 I want to divide all of the rows by the value of 1000 except for the 5th row, which I would like all the values to stay the same of 1. So, the new dataframe would look like this: A B C D 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1 1 1 1 10 10 10 10 10 10 10 10 Is there a simple way to accomplish this? I feel like I am missing something very basic. I have tried using loc, iloc, mul, &amp; div but can not get them to work concurrently.
answer count: 2
score: 5
downvote count: 0
has title: How to divide all rows in a panda Dataframe except for one specific row?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48635265
possible better answer: http://stackoverflow.com/a/48635265
type: AnsweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/84268086
tagged with: pandas

http://stackoverflow.com/q/48528821
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/84052798
answer count: 1
accepted answer: http://stackoverflow.com/a/48529160
has title: What is the difference between these two functions in Python?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84053339
has answer: http://stackoverflow.com/a/48529160
tagged with: python
score: -1
has body: Can anyone explain to me the difference between the two functions here and what is the reason that I am getting two different values? 1. def longest_consec(starr, k): n = len(starr) if n == 0 or k &gt; n or k &lt;= 0 : return "" for i in range(n-k+1): lst = starr[i:i+k] return ''.join(lst) print(longest_consec(["zone", "abigail", "theta", "form", "libe", "zas"], 2)) Output: libezas 2. def longest_consec(strarr, k): n = len(strarr) if n == 0 or k &gt; n or k &lt;= 0 : return "" lst = [''.join(strarr[i:i+k]) for i in range(len(strarr)+1-k)] return lst print(longest_consec(["zone", "abigail", "theta", "form", "libe", "zas"], 2)) Ouput: ['zoneabigail', 'abigailtheta', 'thetaform', 'formlibe', 'libezas']
type: AnsweredQuestion

http://stackoverflow.com/comment/83981125
score: 0
has text: I've made the suggested changes, but still seem to be receiving the same error message. The xml files are definitely in my download folder, so I'm not sure why they can't be accessed.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48493911

http://stackoverflow.com/comment/84207962
type: QuestionComment
has text: I like that idea. Sadly though, this did not solve
comment on: http://stackoverflow.com/q/48604607
score: 0
type: Comment

http://stackoverflow.com/a/77869019
has body: You can add a complex formula using the math2docx library import math2docx from docx import Document document = Document() p = document.add_paragraph() #LaTex Math Formula latex_ = r"\cos (2\theta) = \cos^2 \theta - \sin^2 \theta" math2docx.add_math(p, latex_ ) document.save("new_file.docx") https://github.com/keh9mark/math2docx
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48589563
score: 1
type: Answer

http://stackoverflow.com/q/48509914
favorite count: 0
type: Question
has title: How to count the number of lines that start with the word 'the' in python
has comment: http://stackoverflow.com/comment/84014966
answer count: 2
upvote count: 0
type: UnansweredQuestion
has body: I'm trying to get the number of lines that starts with the word "the" in a file def count_the(file_url): r = requests.get(file_url, stream=True) pat = re.search(r'^the', file_url) count = 0 for line in r.iter_lines(): if line.startswith('the'):` return count += 1
score: -3
has answer: http://stackoverflow.com/a/48509984
has comment: http://stackoverflow.com/comment/84014993
has comment: http://stackoverflow.com/comment/84016136
has answer: http://stackoverflow.com/a/48509992
has comment: http://stackoverflow.com/comment/84014890
tagged with: file-io
downvote count: 3
tagged with: python

mysql
tags question: http://stackoverflow.com/q/48615728
tags question: http://stackoverflow.com/q/48642797
tags question: http://stackoverflow.com/q/48621588
tags question: http://stackoverflow.com/q/48601786
tags question: http://stackoverflow.com/q/48611560
tags question: http://stackoverflow.com/q/48505407
type: Tag
tags question: http://stackoverflow.com/q/48558431
tags question: http://stackoverflow.com/q/48616573
tags question: http://stackoverflow.com/q/48525626
tags question: http://stackoverflow.com/q/48532969
tag name: mysql
tags question: http://stackoverflow.com/q/48518568
tags question: http://stackoverflow.com/q/48623389
tags question: http://stackoverflow.com/q/48617779
tags question: http://stackoverflow.com/q/48543445
tags question: http://stackoverflow.com/q/48514361
tags question: http://stackoverflow.com/q/48532369
tags question: http://stackoverflow.com/q/48633194
tags question: http://stackoverflow.com/q/48640060
tags question: http://stackoverflow.com/q/48535757
tags question: http://stackoverflow.com/q/48561250
tags question: http://stackoverflow.com/q/48614244
tags question: http://stackoverflow.com/q/48558957
tags question: http://stackoverflow.com/q/48515037
tags question: http://stackoverflow.com/q/48526378
tags question: http://stackoverflow.com/q/48554886
tags question: http://stackoverflow.com/q/48634086
tags question: http://stackoverflow.com/q/48497795
tags question: http://stackoverflow.com/q/48519688
tags question: http://stackoverflow.com/q/48523469
tags question: http://stackoverflow.com/q/48613381
tags question: http://stackoverflow.com/q/48576822
tags question: http://stackoverflow.com/q/48600622
tags question: http://stackoverflow.com/q/48491445
tags question: http://stackoverflow.com/q/48608442
tags question: http://stackoverflow.com/q/48531942
tags question: http://stackoverflow.com/q/48523043
tags question: http://stackoverflow.com/q/48645166
tags question: http://stackoverflow.com/q/48509199
tags question: http://stackoverflow.com/q/48587748
tags question: http://stackoverflow.com/q/48511034
tags question: http://stackoverflow.com/q/48517060
tags question: http://stackoverflow.com/q/48644281
tags question: http://stackoverflow.com/q/48613887
tags question: http://stackoverflow.com/q/48584254
tags question: http://stackoverflow.com/q/48631362

http://stackoverflow.com/a/61198797
has comment: http://stackoverflow.com/comment/108287085
has comment: http://stackoverflow.com/comment/108329463
has comment: http://stackoverflow.com/comment/108271477
has comment: http://stackoverflow.com/comment/108329291
upvote count: 5
has comment: http://stackoverflow.com/comment/108327876
type: Answer
has comment: http://stackoverflow.com/comment/108287027
has comment: http://stackoverflow.com/comment/108270970
has comment: http://stackoverflow.com/comment/108325542
has comment: http://stackoverflow.com/comment/108286179
has comment: http://stackoverflow.com/comment/108291829
answers question: http://stackoverflow.com/q/48503344
has comment: http://stackoverflow.com/comment/108325622
has body: As Leon's answer points out, under standard conditions, it is unlikely that you will be able to detect any use of copied objects once you've released them into the wild. However, most modern OSes support something called "delayed rendering". Not only can the format of the selection be negotiated between host and destination, but it is not advisable to copy large pieces of memory without first knowing where they are going. Both Windows and X provide a way of doing exactly what you want through this mechanism. Rather than go into the details of how each OS implements their clipboard API, let's look at a fairly standard cross-plarform package: PyQt5. Clipboard access is implemented through the QtGui.QClipBoard class. You can trigger delayed rendering by avoiding the convenience methods and using setMimeData. In particular, you would create a custom QtCore.QMimeData subclass that implements retreiveData to fetch upon request rather than just storing the data in the clipboard. You will also have to set up your own implementations of hasFormat and formats, which should not be a problem. This will allow you to dynamically negotiate the available formats upon request, which is how delayed rendering is normally implemented. So now let's take a look at a small application. You mentioned in the question that you have a list of items that you would like to copy successively once the first one has been copied. Let's do exactly that. Our custom retrieveData implementation will convert the current selection to a string, encode it in UTF-8 or whatever, move the selection forward, and copy that into the clipboard: from PyQt5.QtCore import Qt, QMimeData, QStringListModel, QTimer, QVariant from PyQt5.QtGui import QClipboard from PyQt5.QtWidgets import QAbstractItemView, QApplication, QListView class MyMimeData(QMimeData): FORMATS = {'text/plain'} def __init__(self, item, hook=None): super().__init__() self.item = item self.hook = hook def hasFormat(self, fmt): return fmt in self.FORMA…
has comment: http://stackoverflow.com/comment/108288516
score: 5
has comment: http://stackoverflow.com/comment/108285951
has comment: http://stackoverflow.com/comment/108285412
has comment: http://stackoverflow.com/comment/108327763
downvote count: 0
has comment: http://stackoverflow.com/comment/108325242
has comment: http://stackoverflow.com/comment/108278764

http://stackoverflow.com/q/48598276
possible better answer: http://stackoverflow.com/a/48598298
linked to: http://stackoverflow.com/q/22365847
has answer: http://stackoverflow.com/a/48598298
has answer: http://stackoverflow.com/a/48598297
favorite count: 0
has comment: http://stackoverflow.com/comment/84193594
upvote count: 4
has title: Turn iterable of tuple into iterables of each element (Python)
tagged with: python-3.x
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48598297
tagged with: python
tagged with: iterable
score: 4
linked to: http://stackoverflow.com/q/11280536
tagged with: generator-expression
type: AnsweredQuestion
has body: I have an iterable delta that generates tuple of two numbers (dx, dy), and I want to compute the sum of each. The following doesn't work since delta is disposed after the first iteration. x = sum(dx for dx, dy in delta) y = sum(dy for dx, dy in delta) Any idea? I'm thinking in the direction of somehow turning delta into two iterables of dx and dy, but have reached nothing so far.
downvote count: 0

http://stackoverflow.com/q/48584876
has comment: http://stackoverflow.com/comment/84166400
has comment: http://stackoverflow.com/comment/84167283
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84166617
favorite count: 0
type: Question
has title: How to filter a date in Excel using pandas?
has comment: http://stackoverflow.com/comment/84167720
tagged with: python
has comment: http://stackoverflow.com/comment/84166375
has comment: http://stackoverflow.com/comment/84166585
score: 0
answer count: 0
tagged with: pandas
has body: In the code below, I denoted that I need to filter the date by using 'Tested on' column, but I couldn't get the correct result. And Date's datatype is Date-Time df = msft[msft.Tested On == '2018-01-11'] But I am getting an error on this code: msft['Tested On']dt.date
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84166895

http://stackoverflow.com/q/48511256
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48511329
tagged with: multidimensional-array
answer count: 3
possible better answer: http://stackoverflow.com/a/48511986
has answer: http://stackoverflow.com/a/48511329
tagged with: python
has title: How can I take a dot product along a particular dimension in numpy?
tagged with: linear-algebra
linked to: http://stackoverflow.com/q/47646789
type: Question
tagged with: numpy
tagged with: numpy-ndarray
linked to: http://stackoverflow.com/q/41870228
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48511986
has body: I have two arrays. One is n by p and the other is d by p by r. I would like my output to be d by n by r, which I can achieve easily as I construct the tensor B below. However, I would like to do this without that loop. import numpy X = numpy.array([[1,2,3],[3,4,5],[5,6,7],[7,8,9]]) # n x p betas = numpy.array([[[1,2],[1,2],[1,2]], [[5,6],[5,6],[5,6]]]) # d x p x r print X.shape print betas.shape B = numpy.zeros((betas.shape[0],X.shape[0],betas.shape[2])) print B.shape for i in range(B.shape[0]): B[i,:,:] = numpy.dot(X, betas[i]) print "B",B C = numpy.tensordot(X, betas, axes=([1],[0])) print C.shape I have tried in various ways to get C to match B, but so far I have been unsuccessful. Is there a way that does not involve a call to reshape?
has answer: http://stackoverflow.com/a/48512043
favorite count: 0
score: 2

http://stackoverflow.com/q/48544522
has comment: http://stackoverflow.com/comment/84086569
tagged with: numpy
has comment: http://stackoverflow.com/comment/84084636
answer count: 0
upvote count: 1
type: UnansweredQuestion
has body: I was trying to make a linear regression model for predicting the mileage offered by a car provided a few values. When I try to use dataframe.score, I'm getting a NaN error. My dataset doesn't contain any empty values. Please find the code and it's output attached. Any help is appreciated. Thanks in advance. import pandas as p import numpy as np` d=p.read_csv('cars.csv')` d=d.drop('Make', axis=1) d=d.drop('Model', axis=1) d=d.drop('Engine_Fuel_Type', axis=1) d=d.drop('Number_of_Doors', axis=1) d=d.drop('Market_Category', axis=1) d=d.drop('Vehicle_Size', axis=1) d=d.drop('Vehicle_Style', axis=1) d['Transmission_Type']=d['Transmission_Type'].replace({1: 'MANUAL', 2: 'AUTOMATIC', 3: 'AUTOMATED_MANUAL', 4: 'DIRECT_DRIVE', 5: 'UNKNOWN'}) d=p.get_dummies(d, columns=['Transmission_Type']) print(d.head()) X=d.drop('city_mpg', axis=1) y=d'city_mpg' from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1) from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) for idx, col_name in enumerate(X_train.columns): print("Co efficient for", col_name, " is ", model.coef_[0][idx]) intercept = model.intercept_[0] print("Intercept is", intercept) print(model.score(X_test, y_test)) output I got was: Year Engine_HP Engine_Cylinders highway_MPG city_mpg Popularity \ 0 2011 335 6.0 26 19 3916 1 2011 300 6.0 28 19 3916 2 2011 300 6.0 28 20 3916 3 2011 230 6.0 28 18 3916 4 2011 230 6.0 28 18 3916 MSRP Transmission_Type_AUTOMATED_MANUAL Transmission_Type_AUTOMATIC \ 0 46135 0 0 1 40650 0 0 2 36350 0 0 3 29450 0 0 4 34500 0 0 Transmission_Type_DIRECT_DRIVE Transmission_Type_MANUAL \ 0 0 1 1 0 1 2 0 1 3 0 1 4 0 1 Transmission_Type_UNKNOWN 0 0 1 0 2 0 3 0 4 0 Co efficient for Year is 0.12795086619034354 Co efficient for Engine_HP is -0.015142081226758822 Co efficient for Engine_Cylinders is -0.4874611334108649 Co efficient for highway_MPG is 0.4410894679555171…
downvote count: 1
tagged with: scikit-learn
has title: model.score in scikit returning NaN
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84086416
has comment: http://stackoverflow.com/comment/84085840
has comment: http://stackoverflow.com/comment/84084662
score: 0
has comment: http://stackoverflow.com/comment/84086048
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/84086265

http://stackoverflow.com/a/48572413
has comment: http://stackoverflow.com/comment/84167278
score: 0
has comment: http://stackoverflow.com/comment/84335570
has body: I cant comment but I think its cause of two possible issues. Do the saved workbooks in the folder only have a single sheet? typically with read_excel you also select a tab name to read from. also have you tried setting the following df.to_excel(writer, 'sheet%s' % i, index=False)
answers question: http://stackoverflow.com/q/48566522
has comment: http://stackoverflow.com/comment/84156369
type: Answer

http://stackoverflow.com/q/48599440
answer count: 1
has answer: http://stackoverflow.com/a/48611591
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
downvote count: 0
has body: Im working on the DSB problem in pytorch,I have my predictions but im not sure how to get those into the run length encoding format that is required for the submission,In short this is what it is =================================================================== In order to reduce the submission file size, our metric uses run-length encoding on the pixel values. Instead of submitting an exhaustive list of indices for your segmentation, you will submit pairs of values that contain a start position and a run length. E.g. '1 3' implies starting at pixel 1 and running a total of 3 pixels (1,2,3). The competition format requires a space delimited list of pairs. For example, '1 3 10 5' implies pixels 1,2,3,10,11,12,13,14 are to be included in the mask. The pixels are one-indexed and numbered from top to bottom, then left to right: 1 is pixel (1,1), 2 is pixel (2,1), etc. =================================================================== I get the predictions like this model = model.eval() for data in testdataloader: data = t.autograd.Variable(data.cuda(device = 1)) pred = model(data) but now that i have my prediction im not sure how to move forward, I found this script online,but im not sure how to modify this for my use case def rle_encoding(x): dots = np.where(x.T.flatten() == 1)[0] run_lengths = [] prev = -2 for b in dots: if (b&gt;prev+1): run_lengths.extend((b + 1, 0)) run_lengths[-1] += 1 prev = b return run_lengths def prob_to_rles(x, cutoff=0.5): lab_img = label(x &gt; cutoff) for i in range(1, lab_img.max() + 1): yield rle_encoding(lab_img == i) Any suggestions on how may i get started or how do i modify this would be really helpfull!
favorite count: 0
has title: Kaggle Pytorch run length encoding
type: Question
tagged with: pytorch
accepted answer: http://stackoverflow.com/a/48611591

http://stackoverflow.com/comment/84011528
comment on: http://stackoverflow.com/a/48508280
type: AnswerComment
has text: @user2357112 , give the correct input as OP asked. In your example there is no old string in sequence.
score: 0
type: Comment

http://stackoverflow.com/a/48610975
score: 3
has comment: http://stackoverflow.com/comment/84218402
type: Answer
has body: ./manage.py shell &gt; scraper/update_db.py When you execute this command referencing the file directly using the diple, what you are doing is assigning the output of the command "./manage.py shell" to the file "scraper / update_db.py" and that is why your code is replaced For what you want to do, you should do the following: ./manage.py shell &lt; scraper/update_db.py Updated: Comment: I expect you want &lt; rather than > by @Daniel Roseman
accepted answer of: http://stackoverflow.com/q/48610889
upvote count: 3
answers question: http://stackoverflow.com/q/48610889
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48590321
has comment: http://stackoverflow.com/comment/84181081
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84180382
downvote count: 1
has body: I am trying to find the center point of the green rectangle which is behind the fish, but my approach is not working. Here is my code: #Finding contours (almost always finds those 2 retangles + some noise): _, conts, hierarchy = cv2.findContours(img_green, cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE) for cnt in conts: area = cv2.contourArea(cnt) #filter noise if area &gt; 25: M = cv2.moments(cnt) x1, y1, w, h = cv2.boundingRect(cnt) x2 = x1 + w # (x1, y1) = top-left vertex y2 = y1 + h # (x2, y2) = bottom-right vertex cy = int(M['m01']/M['m00']) # (cx, cy) = rect center cx = int(M['m10']/M['m00']) rect = cv2.rectangle(green_bar_win, (x1, y1), (x2, y2), (255,0,0), 2) center = cv2.circle(green_bar_win, (cx, cy), 2, (0,0,255), 4) As you can see, it finds the rectangle's contour but divided where the fish is, making 2 different shapes. It also finds the center of this 2 shapes (the blue points), however I don't know how to find the middle of the big one. I thought about averaging all the found rectangle centers but I don't know how to write this out. I am finding the rectangles by hsv color. Help? EDIT: I have 'y1' from the top rectangle, but don't know how to get y2 from the bottom one while inside the for loop. I tried this: _, conts, hierarchy = cv2.findContours(img_green, cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE) for cnt in conts: area = cv2.contourArea(cnt) #filter noise if area &gt; 25: x1, y1, w, h = cv2.boundingRect(cnt) x2 = x1 + w # (x1, y1) = top-left vertex try: rect_center = np.average([y1, y2]) except: print("Failed to average") y2 = y1 + h # (x2, y2) = bottom-right vertex rect = cv2.rectangle(green_bar_win, (x1, y1), (x2, y2), (255,0,0), 2) But it still fails, because y2 is used before assigment. So, how could I get y2 from the second loop itineration before y1 is overwritten by the 'for' loop?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84178434
has comment: http://stackoverflow.com/comment/84178779
has title: How to find the center point of this rectangle
accepted answer: http://stackoverflow.com/a/48592340
has answer: http://stackoverflow.com/a/48592340
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/84179032
score: -1
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84179895
has comment: http://stackoverflow.com/comment/84178451
has comment: http://stackoverflow.com/comment/84179331
has comment: http://stackoverflow.com/comment/84179983

trigram
tag name: trigram
type: Tag
tags question: http://stackoverflow.com/q/48603190

http://stackoverflow.com/q/48509857
answer count: 1
linked to: http://stackoverflow.com/q/1060279
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84016948
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48427185
has comment: http://stackoverflow.com/comment/84014911
downvote count: 0
tagged with: pyspark
score: 6
tagged with: python
upvote count: 6
has body: Suppose I have a DataFrame called transactions with the following integer columns: year, month, day, timestamp, transaction_id. In [1]: transactions = ctx.createDataFrame([(2017, 12, 1, 10000, 1), (2017, 12, 2, 10001, 2), (2017, 12, 3, 10003, 3), (2017, 12, 4, 10004, 4), (2017, 12, 5, 10005, 5), (2017, 12, 6, 10006, 6)],('year', 'month', 'day', 'timestamp', 'transaction_id')) In [2]: transactions.show() +----+-----+---+---------+--------------+ |year|month|day|timestamp|transaction_id| +----+-----+---+---------+--------------+ |2017| 12| 1| 10000| 1| |2017| 12| 2| 10001| 2| |2017| 12| 3| 10003| 3| |2017| 12| 4| 10004| 4| |2017| 12| 5| 10005| 5| |2017| 12| 6| 10006| 6| +----+-----+---+---------+--------------+ I want to define a function filter_date_range that returns a DataFrame consisting of transaction rows that fall within some date-range. &gt;&gt;&gt; filter_date_range( df = transactions, start_date = datetime.date(2017, 12, 2), end_date = datetime.date(2017, 12, 4)).show() +----+-----+---+---------+--------------+ |year|month|day|timestamp|transaction_id| +----+-----+---+---------+--------------+ |2017| 12| 1| 10001| 2| |2017| 12| 1| 10003| 3| |2017| 12| 1| 10004| 4| +----+-----+---+---------+--------------+ Assuming the data is held in Hive partitions, partitioned by year, month, day, what is the most efficient way to perform a filter like this that involves date arithmetic? I am looking for a way of doing this in a purely DataFrame-ic way, without resorting to usage of transactions.rdd, so that Spark can infer that only a subset of partitions actually need to be read.
tagged with: apache-spark
has title: Filtering a spark DataFrame for an n-day window on data partitioned by day
has answer: http://stackoverflow.com/a/48511976

google-app-engine
tags question: http://stackoverflow.com/q/48509265
tags question: http://stackoverflow.com/q/48576731
tag name: google-app-engine
tags question: http://stackoverflow.com/q/48514422
type: Tag
tags question: http://stackoverflow.com/q/48612807
tags question: http://stackoverflow.com/q/48613205
tags question: http://stackoverflow.com/q/48514933
tags question: http://stackoverflow.com/q/48603903
tags question: http://stackoverflow.com/q/48490503
tags question: http://stackoverflow.com/q/48564834
tags question: http://stackoverflow.com/q/48629072
tags question: http://stackoverflow.com/q/48629258
tags question: http://stackoverflow.com/q/48509887
tags question: http://stackoverflow.com/q/48492341
tags question: http://stackoverflow.com/q/48566256
tags question: http://stackoverflow.com/q/48530293
tags question: http://stackoverflow.com/q/48539511
tags question: http://stackoverflow.com/q/48531954
tags question: http://stackoverflow.com/q/48570634

http://stackoverflow.com/comment/84219501
comment on: http://stackoverflow.com/a/48611462
has text: That's right, excuse me ... the update method is only applicable to QuerySet objects. You can change .get to .filter method or ... (wait a moment)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/114159766
type: Comment
has text: not sure, but I think you need to divide by the sum of the weights, right? da.rolling(dim_0=3, center=True).construct('window').dot(weight)/weight.sum()
type: AnswerComment
comment on: http://stackoverflow.com/a/48512802
score: 1

http://stackoverflow.com/comment/84097707
score: 0
has text: @HCPieck try specifying file name: `con = pyodbc.connect('DSN=MS Access Database;DBQ={}'.format(DBQ))`.
comment on: http://stackoverflow.com/q/48539500
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48577749
has title: How to use Python to extract packet information from hexdump?
has comment: http://stackoverflow.com/comment/84154834
has comment: http://stackoverflow.com/comment/84151812
favorite count: 0
type: Question
tagged with: hexdump
type: UnansweredQuestion
tagged with: python
tagged with: wireshark-dissector
has answer: http://stackoverflow.com/a/48588585
tagged with: pcap
downvote count: 0
score: 1
upvote count: 1
has body: I am working on a network project where I have hexdump of packets and I need to dissect that hexdump packet to display all the packet information. Example : Packet Information Fields - source address destination address encapsulation type frame number frame length FCS data epoch time We are not supposed to use file as input and output because it will increase memory utilization and might crash server. I tried with below code but this doesn't work in my case: # imports scapy Utility from scapy.all import * from scapy.utils import * # variable to store hexdump hexdump = '0000 49 47 87 95 4a 30 9e 9c f7 09 70 7f....' # Initialize a 802.11 structure from raw bytes packet = Dot11(bytearray.fromhex(hexdump)) #scapy function to view the info packet.summary() packet.show() Are there any suggestions to achieve this as I am new to this technology? I might lack some proper directions to solve this.
tagged with: scapy
answer count: 1

http://stackoverflow.com/comment/84026257
comment on: http://stackoverflow.com/q/48516013
has text: You are printing a list of ints
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84134758
score: 1
type: Comment
has text: @chenghuayang Correct, unless you can declare it `nonlocal`.
comment on: http://stackoverflow.com/a/48568915
type: AnswerComment

http://stackoverflow.com/a/48497076
has body: cell = tf.nn.rnn_cell.MultiRNNCell([drop for _ in range(num_layers)]) TO cell = tf.nn.rnn_cell.MultiRNNCell([drop]) because your given input tensor and produces tensor are not the same.
has comment: http://stackoverflow.com/comment/83999146
score: 0
answers question: http://stackoverflow.com/q/48494356
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48494356

http://stackoverflow.com/comment/84136574
comment on: http://stackoverflow.com/q/48570059
type: QuestionComment
has text: Looks like there is some shadows being simulated here.
type: Comment
score: 0

http://stackoverflow.com/comment/84265243
type: QuestionComment
comment on: http://stackoverflow.com/q/48618586
has text: @Elmex80s, there are a few hundred alike Price.xlsx so I need a quick way to process in batch.
score: 0
type: Comment

http://stackoverflow.com/a/48494938
has comment: http://stackoverflow.com/comment/83983167
has comment: http://stackoverflow.com/comment/84023887
has comment: http://stackoverflow.com/comment/83983075
type: Answer
answers question: http://stackoverflow.com/q/48494690
has comment: http://stackoverflow.com/comment/83983363
has comment: http://stackoverflow.com/comment/83983462
score: 3
accepted answer of: http://stackoverflow.com/q/48494690
has comment: http://stackoverflow.com/comment/83983347
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Say you have example.py and you want to run it N times. You can run the following seq 10 | parallel -N0 --jobs 0 example.py Breaking this down seq 10 will cause 10 jobs to be run. The -N0 flag tells us to ignore the input which would normally read in the input output by the seq 10 command. --jobs 0 will let as many run in parallel as you want. As far as I know parallel doesn't let you say run this program X times with no input so you must abuse piping into the command with seq and then ignoring it with the -N0 flag. Read this for further examples on commands: https://www.gnu.org/software/parallel/man.html
has comment: http://stackoverflow.com/comment/83983049

http://stackoverflow.com/q/48558652
answer count: 0
has body: In ROI pooling, you have a region of interest(ROI) and you want to pool it to a specific size. ROI gif I try to implement the same thing like in the gif. The whole image is image_pl = tf.placeholder(dtype=tf.float32) # the whole region the region of interest is x = 0 y = 3 w = 7 h = -1 roi = tf.slice(image_pl, [x, y, 0], [w, h, -1]) # region of interest Now I try to get the 4 parts, because every region of interest, no matter of their size, I want to crop to the size 2x2 w_roi = roi.get_shape()[0].value h_roi = roi.get_shape()[1].value roi_part1 = tf.slice(roi, [0, 0, 0], [w_roi // 2, h_roi // 2, -1]) # fisrt part from the gif roi_part2 = tf.slice(roi, [w_roi - w_roi // 2, 0, 0], [w_roi, h_roi // 2, -1]) # second part from the gif roi_part3 = tf.slice(roi, [0, h_roi - h_roi // 2, 0], [w_roi // 2, h_roi, -1]) roi_part4 = tf.slice(roi, [w_roi - w_roi // 2, h_roi - h_roi // 2, 0], [w_roi, h_roi, -1]) But here I get the error. TypeError: unsupported operand type(s) for //: 'NoneType' and 'int' Here is the whole code. How can I implement the idea of that gif? import numpy as np import tensorflow as tf image_pl = tf.placeholder(dtype=tf.float32) # the whole region x = 0 y = 3 w = 7 h = -1 roi = tf.slice(image_pl, [x, y, 0], [w, h, -1]) # region of interest w_roi = roi.get_shape()[0].value h_roi = roi.get_shape()[1].value roi_part1 = tf.slice(roi, [0, 0, 0], [w_roi // 2, h_roi // 2, -1]) # fisrt part from the gif roi_part2 = tf.slice(roi, [w_roi - w_roi // 2, 0, 0], [w_roi, h_roi // 2, -1]) # second part from the gif roi_part3 = tf.slice(roi, [0, h_roi - h_roi // 2, 0], [w_roi // 2, h_roi, -1]) roi_part4 = tf.slice(roi, [w_roi - w_roi // 2, h_roi - h_roi // 2, 0], [w_roi, h_roi, -1]) output1 = tf.reduce_max(roi_part1) # maximum of the region 1 in the region of interest output2 = tf.reduce_max(roi_part2) output3 = tf.reduce_max(roi_part3) output4 = tf.reduce_max(roi_part4) output = tf.concat([output1, output2, output3, output4], 0) config = tf.ConfigProto() config.gpu_optio…
has comment: http://stackoverflow.com/comment/84118657
tagged with: tensorflow
type: Question
has title: TypeError: unsupported operand type(s) for //: 'NoneType' and 'int'
type: UnansweredQuestion
tagged with: python
tagged with: object-detection
has comment: http://stackoverflow.com/comment/84119460
has comment: http://stackoverflow.com/comment/84393390
score: 0

http://stackoverflow.com/comment/84160724
comment on: http://stackoverflow.com/a/48576634
type: Comment
score: 0
type: AnswerComment
has text: Hmmm, if assign scalar, also error? `df1.loc[idx[:, datetime.time(0, 0, 0):datetime.time(2, 0, 0)],:] = 1` ?

http://stackoverflow.com/a/48581213
answers question: http://stackoverflow.com/q/48581116
type: Answer
accepted answer of: http://stackoverflow.com/q/48581116
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: You can do a check to see if the line starts with an "_". if it does skip that line from writing. with open("Path_to_txt", 'r') as infile: data = infile.readlines() with open("Path_to_txt", 'w') as outfile: for i in data: if not i.startswith("_"): outfile.write(i)
score: 1

http://stackoverflow.com/a/48594509
accepted answer of: http://stackoverflow.com/q/48593155
answers question: http://stackoverflow.com/q/48593155
type: AcceptedAnswer
has body: First, you are not passing context in render function. If that doesn't work use this approach to save the images. def function(request): if request.method == 'POST': form = UserImageForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') image2 = form.cleaned_data.get("image2") user = request.user Post.objects.create( User = request.user, image= image, image2= image2, ) return redirect('SOMEWHERE') else: form = UserImageForm() return render(request, 'registration/profile.html',{'form': form})
score: 0
type: Answer

http://stackoverflow.com/a/49659215
answers question: http://stackoverflow.com/q/48626313
score: 0
type: Answer
has body: You can use a trie for that and score then score the result by the length of the matched keys. You first index conjugation using the reverse string of the suffix: In [1]: import pygtrie In [2]: trie = pygtrie.CharTrie() In [3]: trie['re'] = 'v0' In [4]: trie['rec'] = 'v1' Then you can query for conjugation using the following code: In [22]: list(trie.prefixes(''.join(reversed('aimer')))) Out[22]: [('re', 'v0')] In [23]: list(trie.prefixes(''.join(reversed('balancer')))) Out[23]: [('re', 'v0'), ('rec', 'v1')] Then you can score the result using a simple function like this: In [24]: best = lambda candidates: sorted(candidates, key=lambda x: len(x[0]), reverse=True)[0] In [25]: best(trie.prefixes(''.join(reversed('balancer')))) Out[25]: ('rec', 'v1')

http://stackoverflow.com/q/48610288
has body: i-m trying to implement a function that convert numbers from Western numbers to Mandarin, I am having issues with REGEX. This is the logic: Numbers in Mandarin follow 3 simple rules. There are words for each of the digits from 0 to 10. For numbers 11-19, the number is pronounced as "ten digit", so for example, 16 would be pronounced (using Mandarin) as "ten six". For numbers between 20 and 99, the number is pronounced as “digit ten digit”, so for example, 37 would be pronounced (using Mandarin) as "three ten seven". If the digit is a zero, it is not included. Everything is OK from 20 to 89, with mean is not matching the pattern [11-19] but for some reason from 90 on it match the pattern [11-90] Here is the code so you can understand what i'm saying. import re def convert_to_mandarin(us_num): ''' us_num, a string representing a US number 0 to 99 returns the string mandarin representation of us_num ''' ans = None numbers0to9 = re.compile('\d') numbers11to19 = re.compile('[11-19]') trans = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4': 'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10': 'shi'} if len(us_num) == 1: if numbers0to9.match(us_num): ans = trans[us_num] print(us_num) else: if numbers11to19.match(us_num) and len(us_num) == 2: ans = trans['10'] +' ' + trans[us_num[1]] print(us_num) elif us_num[1] == '0' and len(us_num) == 2: ans = trans[us_num[0]] + ' ' + trans['10'] print(us_num) else: ans = trans[us_num[0]] + ' ' + trans['10'] +' ' + trans[us_num[1]] print(us_num) return ans print(convert_to_mandarin(str('3'))) print(convert_to_mandarin(str('15'))) print(convert_to_mandarin(str('71'))) print(convert_to_mandarin(str('81'))) print(convert_to_mandarin(str('91'))) So, why is every use case of 20-99 not matching numbers11to19 pattern and entering the intended branch and from 90 on it match that pattern? Thanks in advance!
downvote count: 1
has comment: http://stackoverflow.com/comment/84216921
favorite count: 0
has answer: http://stackoverflow.com/a/48610371
type: Question
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3148240
tagged with: python
tagged with: regex
score: 2
duplicate of: http://stackoverflow.com/q/3148240
has title: Match sequence of digits with regular expressions
upvote count: 3
answer count: 1

http://stackoverflow.com/q/48597758
has comment: http://stackoverflow.com/comment/84192261
downvote count: 2
tagged with: arrays
has comment: http://stackoverflow.com/comment/84192180
upvote count: 1
tagged with: python
score: -1
has body: How to remove an element from an item in a list? normally when I delete something from a list I do: df = [1,2,3,'name'] df.remove('name') #output is [1,2,3] but what if my entry isn't just a regular thing, for example: df = [1,2,3, 'name 123'] and I want to get rid of the "_123"?
answer count: 4
has answer: http://stackoverflow.com/a/48597970
has comment: http://stackoverflow.com/comment/84192197
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48597833
has comment: http://stackoverflow.com/comment/84192139
has answer: http://stackoverflow.com/a/48597833
has answer: http://stackoverflow.com/a/48597838
accepted answer: http://stackoverflow.com/a/48597885
has answer: http://stackoverflow.com/a/48597885
favorite count: 0
type: Question
has title: Remove an element from an item in a list

http://stackoverflow.com/comment/84058818
comment on: http://stackoverflow.com/a/48530384
type: AnswerComment
score: 0
type: Comment
has text: This is an excellent answer. Much more concise than the one I cooked up.

http://stackoverflow.com/comment/84057694
comment on: http://stackoverflow.com/q/48531008
score: 0
type: Comment
type: QuestionComment
has text: Those are unicode characters. If you're using Python2 open the file in binary mode, for Python3 set the encoding to 'utf-8'

http://stackoverflow.com/q/48618429
has body: I am trying to make a form for writing problem and providing choices for the problem. Correct choice for the problem is indicated by the selected radio button. Whether a choice is correct choice for a problem is indicated by boolean field Choice.is_correct_choice. In my templates, I have the following: {% for form in choice_form %} &lt;input type="radio" name="selected_choice_number" value="{{ forloop.counter }}"&gt; {{ form.as_p }} {% endfor %} choice_form is the formset containing choice. And, in views.py, I have: form = request.POST selected_choice_number = int(form['selected_choice_number']) print(form["selected_choice_number"]) for counter, form in enumerate(choice_form, start=1): choice = form.save(commit=False) choice.problem = problem choice.is_choice_correct = (selected_choice_number == counter) print(choice.choice_text, choice.is_choice_correct) choice.save() choice_form formset is instance of formset of following form: class MCQChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text'] labels = { 'choice_text': "", } widgets = { "choice_text": forms.Textarea(), } This is working fine but It looks ugly to me, specially the code in templates. How can I improve the code so that radio button logic is coded in Python (form/views) instead of templates?
score: 2
upvote count: 2
downvote count: 0
answer count: 0
tagged with: django-forms
favorite count: 0
has title: Django: How to properly display formsets as radio-button group
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/48612565
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84221946
downvote count: 0
type: Answer
upvote count: 1
has body: You have a list of dicts. So you can get the first item using the list index, and then you get the dict element using a key. So for example: item = geocode_result[0] item['address_components'] # Returns another list item['formatted_address'] # Returns a string 'Chesapeake, VA 23325, USA'
score: 1
accepted answer of: http://stackoverflow.com/q/48612067
answers question: http://stackoverflow.com/q/48612067

http://stackoverflow.com/q/48613725
has answer: http://stackoverflow.com/a/48648077
has answer: http://stackoverflow.com/a/48614549
has body: I'm running a jupyter notebook in google datalab running python 3. I'd like to use cv2 but am unable to import the module. I was able to install opencv using: !pip install opencv-python I got the following confirmation: Collecting opencv-python Using cached opencv_python-3.4.0.12-cp27-cp27mu-manylinux1_x86_64.whl Requirement already satisfied: numpy>=1.11.1 in /usr/local/lib/python2.7/dist-packages (from opencv-python) Installing collected packages: opencv-python Successfully installed opencv-python-3.4.0.12 When I try to "import cv2" I get the following error: importError Traceback (most recent call last) in () ----> 1 import cv2 ImportError: No module named 'cv2' When I list the modules using help("modules") neither opencv or cv2 are shown. Any help would be greatly appreciated.
answer count: 3
upvote count: 2
has answer: http://stackoverflow.com/a/48671719
type: UnansweredQuestion
has title: Can't install opencv or import cv2 in google datalab
score: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: opencv
tagged with: google-cloud-datalab
tagged with: python

http://stackoverflow.com/comment/84194801
comment on: http://stackoverflow.com/q/48597801
type: Comment
type: QuestionComment
score: 0
has text: when i type username and pass and when i click sign in, it send user and pass with device guid to the server in request payload, then if i have already that guid in my account or if i have a free slot i can log in. In short i get uuid before i login to site, now it seems that serial is not important, i think that's just something they use to make uuid

http://stackoverflow.com/comment/83993034
has text: @alessioferri20 Ah, then it needs to change 'post_id'(user id who posted) to user foreign key....
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48499551

http://stackoverflow.com/comment/84110316
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48557207
has text: what you mean by matching column 1 and 2 ?
score: 2

http://stackoverflow.com/comment/130698147
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48584999
has text: Thank you. what if the pub and sub are on different machines please? Also, what are some useful use cases for using pub-sub in the same machine over inproc please? Mostly, we use pub-sub over network to let clients receive updates from publishers. What is the point from this local pub-sub in the same machine?
type: Comment

http://stackoverflow.com/a/63989796
has comment: http://stackoverflow.com/comment/137130017
type: Answer
upvote count: 23
downvote count: 0
score: 23
answers question: http://stackoverflow.com/q/48588449
has body: For Python3: FROM ubuntu:latest WORKDIR /app ADD . /app RUN set -xe \ &amp;&amp; apt-get update \ &amp;&amp; apt-get install python3-pip RUN pip install --upgrade pip RUN pip install -r requirements.txt If you install python-pip for Python2 as well, you need to use pip3 for Python3 and pip for Python2. But with this setting, pip is the same as pip3. Check with pip -V. Thats it :-)

http://stackoverflow.com/a/48548908
accepted answer of: http://stackoverflow.com/q/48548817
has body: Although Guido van Rossum didn't much care for reduce(), enough of the community did want it, which is why it was moved to functools and not removed outright. It is performant, and ideally suited to your use case. Just use it. You can make your case faster and more readable by using operator.xor() to avoid the overhead of a new Python frame for a lambda: from functools import reduce from operator import xor reduce(xor, [1, 3, 2, 3, 4, 4, 5, 2, 1]) Both xor() and reduce() are implemented in C. Calling back to the Python interpreter loop for the lambda is quite slow compared to calling another C function. If you really must use a function, then use def xor_reduce(values): result = 0 for value in values: result ^= value return result using in-place XOR, and better variable names.
upvote count: 11
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/84093813
has comment: http://stackoverflow.com/comment/84093736
answers question: http://stackoverflow.com/q/48548817

http://stackoverflow.com/q/48551679
downvote count: 0
has body: By parametric I mean a lock that can be used with a parameter and lock only the threads that use the same parameter. The parameter can have thousands of different values, and it's impossible to create a dictionary of threading.Lock objects, one per parameter value. A function on my web server accepts two parameters, a group and something else. Every time the function is called it checks if a group file has changed (very fast), and if it has changed it does something with it (very slow). The slow process for each group is completely independent from the other groups and can happen at the same time, but two elements of each group cannot be processed at the same time, nor while the group is being processed. I was able to get it to work using a global list of groups being processed, but now that I'm done with it I think it's really ugly and there must be a better way. The snippet below shows what I'm looking for. It uses an imaginary LockWithGroup. Is there something similar in Python? process_lock = threading.LockWithGroup() def process_element(group, element): print('Start', group) with process_lock(group): if needs_update(group): print('Updating', group) update_group(group) print('Updated', group) with process_lock(group): retval = do_something_with(group, element) print('End', group) return retval process_element('g1', e1) # a process_element('g1', e2) # b process_element('g1', e3) # c process_element('g2', e4) # d process_element('g2', e5) # e Output: &gt; Start g1 # a &gt; Start g2 # d &gt; Updating g1 # a &gt; Updating g2 # d &gt; Updated g1 # a &gt; End g1 # a &gt; Start g1 # b &gt; End g1 # b &gt; Start g1 # c &gt; Updated g2 # d &gt; End g2 # d &gt; Start g2 # e &gt; End g1 # c &gt; End g2 # e
favorite count: 0
type: Question
has title: Is there a parametric locking mechanism in Python?
score: 3
tagged with: locking
tagged with: python-multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/84103228
linked to: http://stackoverflow.com/q/37624289
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48553188
upvote count: 3
has answer: http://stackoverflow.com/a/48553188
tagged with: multithreading
has comment: http://stackoverflow.com/comment/84099821
answer count: 1

http://stackoverflow.com/q/48536969
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48537149
score: 21
has answer: http://stackoverflow.com/a/48537149
has body: First I create my array myarray = np.random.random_integers(0,10, size=20) Then, I want to set 20% of the elements in the array to 0 (or some other number). How should I do this? Apply a mask?
possible better answer: http://stackoverflow.com/a/63261913
has answer: http://stackoverflow.com/a/48537178
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/63261913
has answer: http://stackoverflow.com/a/75130292
has title: How to randomly set elements in numpy array to 0
has answer: http://stackoverflow.com/a/48537101
answer count: 5
downvote count: 0
upvote count: 21
tagged with: python

http://stackoverflow.com/q/48547499
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48553255
has answer: http://stackoverflow.com/a/48553255
tagged with: arrays
tagged with: python
has body: I have the follwoing question. I have a numpy array with size 91x40x21 full of floats and I want to use the median filter. Unfortunatly when i trying to cast it back to an array i get this error: "cannot reshape array of size 76440 into shape (0,0,0)" This is my code: image_view = itk.GetImageViewFromArray(matrix.astype('float32')) medianImage = itk.MedianImageFilter.New(image_view, Radius = 3) matrix = itk.GetArrayViewFromImage(medianImage)
has title: Python ITK Rehsape error with median Filter
type: AnsweredQuestion
score: 0
tagged with: itk
answer count: 1
tagged with: scipy

http://stackoverflow.com/q/48640060
downvote count: 0
has comment: http://stackoverflow.com/comment/84276701
tagged with: mysql
has body: I am currently making an API in Django Rest Framework and in that I am filtering the dates which was given by the user(coming from frontend) and after then I am grouping it in months. The problem I am facing is what if the start date is lesser than min(createddate), then the data I am getting is filtered but instead of that I need the grouped time from start date to the end date(grouped in a range), if there is no data for some months then the database should return 0. I know SQL(I am using SQL as my DB) evaluates first where clause and after group by, is there a way to group the data first and then we could apply where clause. For example: Body - I am passing to the API { "StartDate":"2017-06-01", "EndDate":"2017-08-08" } Current Response - I am getting from my API "data": [ { "key": "Count", "bar": true, "values": [ [ "2017-08-01T00:00:00", 1501545600000, 1 ] ] } ] Correct Response - I wanted from data "data": [ { "key": "Count", "bar": true, "values": [ [ "2017-06-01T00:00:00", 1496255400000, 0 ], [ "2017-07-01T00:00:00", 1498847400000, 0 ], [ "2017-08-01T00:00:00", 1501545600000, 1 ] ] } ] Django ORM query: q=ConsumerServicerequestFeedback.objects.values_list('csrfrating').filter(status) if len(StartDate) != 0 and len(EndDate) == 0: StartDate = datetime.strptime(StartDate, '%Y-%m-%d') next_day = StartDate + timedelta(1) q = q.filter(csrfcreateddate__range=[StartDate, next_day]) elif len(StartDate) != 0 and len(EndDate) != 0: q = q.filter(csrfcreateddate__range=[StartDate, EndDate]) elif len(StartDate) == 0 and len(EndDate) != 0: EndDate = datetime.strptime(EndDate, '%Y-%m-%d') q = q.filter(csrfcreateddate__lte=EndDate) q.annotate(Time=TruncMonth('csrfcreateddate')).values('Time').annotate(Count=Count('csrfrating')).values('Time', 'Count')
upvote count: 1
favorite count: 0
type: Question
has title: Django: Group By between two range of Dates that are not present in Database
has answer: http://stackoverflow.com/a/48640426
has comment: http://stackoverflow.com/comment/84277575
has comment: http://stackoverflow.com/comment/84278394
tagged with: group-by
has comment: http://stackoverflow.com/comment/84277624
tagged with: django
tagged with: python
tagged with: date
has comment: http://stackoverflow.com/comment/84276950
has comment: http://stackoverflow.com/comment/84277727
type: UnansweredQuestion
score: 1
answer count: 1

http://stackoverflow.com/comment/84157797
type: QuestionComment
comment on: http://stackoverflow.com/q/48580361
type: Comment
has text: https://stackoverflow.com/questions/15512058/python-shuffle-such-that-position-will-never-repeat
score: 0

http://stackoverflow.com/q/48530336
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84131773
has comment: http://stackoverflow.com/comment/84171088
tagged with: python
has comment: http://stackoverflow.com/comment/84131626
has comment: http://stackoverflow.com/comment/84057137
answer count: 0
tagged with: firmware
upvote count: 2
has comment: http://stackoverflow.com/comment/84057190
has comment: http://stackoverflow.com/comment/84170594
has comment: http://stackoverflow.com/comment/84056775
has comment: http://stackoverflow.com/comment/84060567
has comment: http://stackoverflow.com/comment/84060688
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84122851
tagged with: parsing
favorite count: 0
has comment: http://stackoverflow.com/comment/84056663
has comment: http://stackoverflow.com/comment/84056929
type: Question
tagged with: binary
tagged with: ctypes
has title: Why are the values incorrect when parsing binary data using python ctype structures?
has body: This binary data is being parsed via a python parser file containing ctype structures. Unfortunately, it is not returning the proper values. Most likely this is because I am not 100% sure how to interpret this data. This spec outlines how the binary data is organized. I am not 100% sure how to interpret this spec. Here is what my python parser looks like: from binascii import unhexlify from ctypes import * data = 'FE A5 11 11 3F A5 A1 A3 FE 9A A5 A4 8E A6 A2 89 A1 FE A3 A5 8A FE A5 A4 A5 35 8A 31 04 3C 07 1E 31 31 7A 59 23 01 4D 5E 11 0E 70 0D 41 64 27 63 57 0F 3A 59 47 29 2A 43 3B 66 02 0A 70 5D 56 5B 01 FE 4E 57 34 65 94 2E 52 66 5A 63 03 50 53 98 4E 6C 35 71 10 7B 57 0F 64 8A 70 4B 61 1B 07 3C 55 7A 46 48 3D 3D 20 02 62 65 69 09 03 3F 40 1D 61 45 22 15 39 42 4E 4C 13 12 1A 6F 59 63 8C 5A 28 67 15 2E 55 2A 59 16 0B 3C 68 08 09 42 1B 2D 0D 4A 0A 2E 82 6A 37 1C 2C 11 54 4E 57 56 25 50 09 17 5F 5F 0C 1E 6A 1F 85 28 5A 08 3B 19 79 65 13 6C 39 15 05 14 23 FE 47 04 32 52 52 61 1B FE 13 2D 40 4C 43 9D 44 78 73 7E 43 35 06 15 5A 67 21 34 4B 58 8E 68 1A 81 4B 24 75 64 50 58 5F 6B 7E 42 5F 8B 56 77 62 05 57 2C 72 53 1E 4A 50 5C 4D 45 1C 63 23 58 53 03 06 34 5A 37 58 44 4A 6C 7A 55 1E 59 66 68 69 05 6E 35 16 35 6C 15 84 1A 72 5A 18 3F 1D 65 7C 38 52 53 43 32 40 2A 6C 4C 77 4D 37 1E 0F 45 19 66 38 21 3D 6B 63 6D 06 37 1E 18 44 32 45 24 05 6E 1E 5C 6B 0D 09 93 1E 30 6E 30 52 D5 1C 6B 63 15 53 27 24 16 1B 16 20 33 7B 40 23 00 38 17 09 68 38 8F 1B 32 75 5F 48 5A 5D 52 45 75 5E 92 15 A3 21 81 1F 51 27 42 93 59 63 44 1D 40 18 05 0E 6A 4D 39 52 6F 53 26 6C 73 0A 10 26 8F 77 30 24 59 1C 66 45 5E 6B 8F 34 73 2A 7B 1F 48 2A 18 54 55 89 6F 58 16 85 4B 07 59 68 2B 3E 89 32 40 5F 81 94 6E 4E 22 99 2C 73 B0 18 7D 2E 3C 49 01 3C 50 97 96 1F 5F 6F 21 67 51 91 3F 2C 61 51 2E 91 48 0D 5F 20 56 2F 20 7E FE FE FE 3E 39 4C 06 24 0F 02 16 47 7C 47 30 FE FE 69 18 17 58 FE 13 28 55 FE 60 01 FE 08 23 0D 23 FE FE FE FE FE FE FE FE 00 00 05 BD 00 00 6C A6' buffer = unhexlify(datahex.replace(' ','')) b…
has comment: http://stackoverflow.com/comment/84057092
has comment: http://stackoverflow.com/comment/84154954

http://stackoverflow.com/q/48621625
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84240483
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/xlsx
has comment: http://stackoverflow.com/comment/84240827
has body: I want to store my database information into xlsx file. I have created following program using python. import xlsxwriter def create_xlsx_file(): workbook = xlsxwriter.Workbook('/home/script/report.xlsx') worksheet = workbook.add_worksheet() data = ['DataBase Name', 'Total Images', 'Gallary Name', 'Subject Name'] r = 0 c = 0 for i in data: worksheet.set_column(c,c, 20) bold = workbook.add_format({'bold': True}) worksheet.write(r, c, i) c = c + 1 workbook.close() def add_info_into_file(DataBase_Name, Total_Images, Gallary_Name, Subject_Name): workbook = xlsxwriter.Workbook('/home/script/report.xlsx') worksheet = workbook.add_worksheet() data = [DataBase_Name, Total_Images, Gallary_Name, Subject_Name] r = 2 c = 0 for i in data: worksheet.set_column(c,c, 20) bold = workbook.add_format({'bold': True}) worksheet.write(r, c, i) c = c + 1 workbook.close() create_xlsx_file() add_info_into_file("msc", 100, "Mat", "rsp") In above program, If I call add_info_into_file() function, then existing data truncated. So, how to append some data into existing sheet? Please, someone help me. Thanks in advance.
tagged with: python
has answer: http://stackoverflow.com/a/48622412
has comment: http://stackoverflow.com/comment/84241016
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: read-write
answer count: 1
has title: How to append some data into existing xlsx sheet?

http://stackoverflow.com/q/48532361
has answer: http://stackoverflow.com/a/48532402
answer count: 2
downvote count: 0
duplicate of: http://stackoverflow.com/q/53645882
upvote count: 1
has title: pandas: merge dataframes and include index as a column
favorite count: 0
has body: I have two dataframes like the following: df1: dp value 0 d1 2 1 d1 3 2 d2 7 3 d2 8 4 d3 6 df2: fv_name dp value 0 x-1 d1 2 1 x-2 d1 2 2 x-3 d1 3 3 x-1 d2 7 4 x-2 d2 7 5 x-3 d2 8 6 x-1 d3 6 7 x-2 d3 6 8 x-3 d3 6 And I am trying to add the indices from df1 onto df2 to produce a dataframe that looks like the following: df3: fv_name dp value dp_id 0 x-1 d1 2 0 1 x-2 d1 2 0 2 x-3 d1 3 1 3 x-1 d2 7 2 4 x-2 d2 7 2 5 x-3 d2 8 3 6 x-1 d3 6 4 7 x-2 d3 6 4 8 x-3 d3 6 4 I was attempting some different types of merges like the following, but I am unable to achieve my desired dataframe. df3 = pd.merge(df1, df2, on=['dp', 'value'], how='outer') Thanks in advance for any help with this.
type: Question
tagged with: pandas
tagged with: python
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/53645882
has answer: http://stackoverflow.com/a/48532716

http://stackoverflow.com/q/48605945
has answer: http://stackoverflow.com/a/48609549
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: Dependency management with conda-build -- how to get rid of redundancy and duplication?
score: 4
upvote count: 4
has body: I have a conda-based project that contains an environment.yml file that lists project dependencies. I also want to use this project to build a conda package. For that, I created another file, meta.yaml, that also needs to list the dependencies. Moreover, in meta.yaml, one may specify separate dependencies for building, running and testing. My questions are: What is the difference between the build and run dependencies in meta.yaml? Is there a way to synchronize between the packages (names and versions) listed in environment.yml and those listed in meta.yaml?
tagged with: conda
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84225760
comment on: http://stackoverflow.com/q/48614280
has text: Is there anything called `CustomEncoder` within the file `CustomEncoder` at all?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84248379
comment on: http://stackoverflow.com/q/48625687
type: Comment
score: 0
type: QuestionComment
has text: You can do `getattr(sf.bulk, object).update(data)`

http://stackoverflow.com/comment/84097015
comment on: http://stackoverflow.com/a/48550270
type: Comment
has text: Not sure if that'll work. I'm looking at `df.where`, but it's returning the whole (demo) df. Will update if I find something better than what I posted.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48567012
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/62060202
answer count: 2
has body: Tried googling up, but could not find how to implement Sklearn metrics like cohen kappa, roc, f1score in keras as a metric for imbalanced data. How to implement Sklearn Metric in Keras as Metric?
has comment: http://stackoverflow.com/comment/84139931
tagged with: machine-learning
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48573176
tagged with: keras
favorite count: 0
type: Question
has title: How to implement Sklearn Metric in Keras as Metric?
tagged with: python
has comment: http://stackoverflow.com/comment/84146711
has answer: http://stackoverflow.com/a/48573176
upvote count: 4
possible better answer: http://stackoverflow.com/a/62060202
score: 2

http://stackoverflow.com/q/48577943
has title: Connecting python with Hortonworks Data Platform sandbox
tagged with: python
linked to: http://stackoverflow.com/q/22838752
has body: I want to use pyhive/phys2 library. I installed pyhive, but when I use it in a program I get an Import error:No sasl module found. So I pip installed sasl. Then I am getting: sasl/saslwrapper.cpp(247) : fatal error C1083: Cannot open include file: 'stdint.h': No such file or directory error: command 'C:\Users\Imdad\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe' failed with exit status 2 I tried finding a solution but nothing is helping. I am using Python 2.7 and HDP 2.5 sandbox on Windows 10. Any help?
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/53226873
favorite count: 0
tagged with: hortonworks-data-platform
tagged with: hive
type: Question
type: UnansweredQuestion
tagged with: hortonworks-sandbox

http://stackoverflow.com/comment/83979059
type: Comment
has text: Please show the columns you are deleting. Is one of them a datetime series?
type: QuestionComment
comment on: http://stackoverflow.com/q/48491925
score: 0

selenium
tags question: http://stackoverflow.com/q/48513472
tags question: http://stackoverflow.com/q/48591317
tags question: http://stackoverflow.com/q/48621628
tags question: http://stackoverflow.com/q/48588778
tags question: http://stackoverflow.com/q/48505405
tags question: http://stackoverflow.com/q/48491227
tags question: http://stackoverflow.com/q/48603339
tags question: http://stackoverflow.com/q/48636277
tags question: http://stackoverflow.com/q/48617624
tags question: http://stackoverflow.com/q/48509816
tags question: http://stackoverflow.com/q/48592144
tags question: http://stackoverflow.com/q/48645531
tags question: http://stackoverflow.com/q/48560342
tags question: http://stackoverflow.com/q/48552914
tags question: http://stackoverflow.com/q/48492265
tags question: http://stackoverflow.com/q/48551161
tags question: http://stackoverflow.com/q/48566232
tags question: http://stackoverflow.com/q/48597801
tags question: http://stackoverflow.com/q/48638400
tags question: http://stackoverflow.com/q/48599095
tags question: http://stackoverflow.com/q/48534965
tags question: http://stackoverflow.com/q/48541033
tags question: http://stackoverflow.com/q/48520690
tags question: http://stackoverflow.com/q/48620526
tags question: http://stackoverflow.com/q/48634632
tags question: http://stackoverflow.com/q/48614856
tags question: http://stackoverflow.com/q/48528881
tags question: http://stackoverflow.com/q/48555250
tags question: http://stackoverflow.com/q/48492530
tags question: http://stackoverflow.com/q/48503939
tags question: http://stackoverflow.com/q/48607868
tags question: http://stackoverflow.com/q/48499652
tags question: http://stackoverflow.com/q/48490437
tags question: http://stackoverflow.com/q/48577341
tags question: http://stackoverflow.com/q/48617746
tags question: http://stackoverflow.com/q/48542737
tags question: http://stackoverflow.com/q/48595792
tags question: http://stackoverflow.com/q/48581090
tags question: http://stackoverflow.com/q/48552268
tags question: http://stackoverflow.com/q/48493684
tags question: http://stackoverflow.com/q/48588008
tags question: http://stackoverflow.com/q/48588828
tags question: http://stackoverflow.com/q/48524014
tags question: http://stackoverflow.com/q/48624119
tags question: http://stackoverflow.com/q/48616051
tags question: http://stackoverflow.com/q/48549605
tags question: http://stackoverflow.com/q/48521762
tags question: http://stackoverflow.com/q/48622500
tags question: http://stackoverflow.com/q/48625138
tags question: http://stackoverflow.com/q/48540994
tags question: http://stackoverflow.com/q/48639117
tags question: http://stackoverflow.com/q/48512472
tags question: http://stackoverflow.com/q/48529032
tags question: http://stackoverflow.com/q/48538436
tags question: http://stackoverflow.com/q/48543737
tags question: http://stackoverflow.com/q/48557887
tags question: http://stackoverflow.com/q/48638595
tags question: http://stackoverflow.com/q/48603827
tags question: http://stackoverflow.com/q/48490272
tags question: http://stackoverflow.com/q/48641884
tags question: http://stackoverflow.com/q/48615638
tags question: http://stackoverflow.com/q/48552397
tags question: http://stackoverflow.com/q/48533101
tags question: http://stackoverflow.com/q/48612376
type: Tag
tags question: http://stackoverflow.com/q/48537028
tags question: http://stackoverflow.com/q/48533882
tags question: http://stackoverflow.com/q/48510411
tags question: http://stackoverflow.com/q/48604607
tags question: http://stackoverflow.com/q/48641654
tags question: http://stackoverflow.com/q/48586203
tags question: http://stackoverflow.com/q/48573402
tags question: http://stackoverflow.com/q/48547739
tags question: http://stackoverflow.com/q/48505979
tags question: http://stackoverflow.com/q/48559795
tags question: http://stackoverflow.com/q/48498349
tag name: selenium
tags question: http://stackoverflow.com/q/48506074
tags question: http://stackoverflow.com/q/48533134
tags question: http://stackoverflow.com/q/48603376

http://stackoverflow.com/q/48506931
type: Question
has title: Django - {{ MEDIA_URL }} not working as expected
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84008375
score: 0
linked to: http://stackoverflow.com/q/35288793
answer count: 1
has answer: http://stackoverflow.com/a/48507537
accepted answer: http://stackoverflow.com/a/48507537
tagged with: django
has body: I'm having a slight problem where my Django media tag isn't working properly. This doesn't return the path I expect - which would be '/media/uploads/image_name_goes_here/', and instead I get '/uploads/image_name_goes_here/' even though I have specified in my settings.py that the MEDIA_URL = '/media/'. My upload_to path in the models for the Image is the following function.. def img_path(instance, filename): return ('uploads/%s' % (filename)) class Image(models.Model): ... image_url=models.ImageField(upload_to=img_path,null=True) ... My html: &lt;img src='{{ MEDIA_URL }}/{{ Image.img_path }}'/&gt; Any ideas on why the 'media/' bit of the URL does not show up?

http://stackoverflow.com/comment/84297688
type: AnswerComment
comment on: http://stackoverflow.com/a/48644170
type: Comment
has text: Where can I get SSL certificates?
score: 0

http://stackoverflow.com/a/49145702
has body: The answer is no, at this moment there is no conditional execution in CNTK. The general case is that flag is a vector/tensor and some of its elements would be 0 and others would be 1. There's an obvious optimization when all the elements have the same value but it is not implemented. However even if it were implemented the signature of sel_branch would still be that it requires 3 arguments, because that is a "compile-time" property, while the aforementioned optimization can only be determined at runtime. Even in your case when flag is a scalar, it might be 0 in one batch and 1 for the other and the signature of sel_branch cannot change from batch to batch.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48642726
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48642726

http://stackoverflow.com/comment/84072025
type: QuestionComment
comment on: http://stackoverflow.com/q/48537714
has text: Is it just the `customized_process_000()` step which needs to be selected by a commans-line argument?
score: 0
type: Comment

http://stackoverflow.com/comment/84145543
score: 0
comment on: http://stackoverflow.com/q/48574375
type: Comment
type: QuestionComment
has text: @patrick Oh sorry, I probably did that to make it more readable for humans. Forgetting that it's not how I handle the actual numbers in the script. I'll edit for clarity.

http://stackoverflow.com/comment/84254910
type: Comment
type: AnswerComment
has text: This is a completely different compression algorithm and data format than the OP asked for, and for no benefit whatsoever: zlib itself is a format designed with the explicit intent of letting two compressed streams be concatenated and decompressed to yield the same result as concatenating the decompressed contents.
comment on: http://stackoverflow.com/a/48628889
score: 0

http://stackoverflow.com/q/48566181
favorite count: 0
score: 8
upvote count: 8
type: Question
has body: I want to build an app with many plots. It will have some tabs, and one gridplot within the tabs with some plots. In addition, I need to update the plots layout dynamically when the server is running. Remove or add some plots Remove or add some tabs I have read this thread, where Bryan (@bigreddot) says: The most well-used and understood (as well as more efficient) method is to create your plots once, up front, then update only their data when they need to change. Bokeh's layout capability is ambitious and complicated. It works well in a number of situations but I can easily believe there are update bugs that might be exposed when replacing complicated composite models like entire plots deep in a nested layout. I have written the following example where I update the layout in four different ways: Replacing the old plot by the children attribute on the layout object. Replacing the layout with curdoc() Replacing the plot using remove() and append() Inserting a new plot using insert() from bokeh.models import Button, ColumnDataSource from bokeh.layouts import column from bokeh.plotting import curdoc, figure # ------------------- PLOT 1 --------------------------- # plot_1 = figure( width=400, height=400, ) x = [1, 2, 3, 4] y = [4, 3, 2, 1] source = ColumnDataSource(data=dict(x=x, y=y)) plot_1.circle( x='x', y='y', source=source, radius=0.5, fill_alpha=0.6, fill_color='green', ) # ------------------- PLOT 2 --------------------------- # plot_2 = figure( width=400, height=400, ) plot_2.circle( x='x', y='y', source=source, radius=0.5, fill_alpha=0.6, fill_color='red', ) # ------------------- PLOT 3 --------------------------- # plot_3 = figure( width=400, height=400, ) plot_3.circle( x='x', y='y', source=source, radius=0.5, fill_alpha=0.6, fill_color='yellow', ) # ------------------- BUTTONS --------------------------- # def replace_by_children_attr(): column_1.children = buttons + [plot_2] def replace_by_curdoc(): column_2 = column(buttons + [plot_2]) curdoc().clear() cu…
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47820780
has comment: http://stackoverflow.com/comment/84256788
type: UnansweredQuestion
tagged with: layout
has comment: http://stackoverflow.com/comment/84259931
has comment: http://stackoverflow.com/comment/84245324
has comment: http://stackoverflow.com/comment/84788727
tagged with: python
has comment: http://stackoverflow.com/comment/84211041
tagged with: plot
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/84200202
has comment: http://stackoverflow.com/comment/84243588
tagged with: bokeh
has title: How to change the layout dynamically? How to add and remove layout objects properly?
has comment: http://stackoverflow.com/comment/84787463

http://stackoverflow.com/comment/84264377
type: QuestionComment
comment on: http://stackoverflow.com/q/48633650
score: 2
has text: Why are you nesting try/excepts?
type: Comment

http://stackoverflow.com/a/48556156
type: Answer
answers question: http://stackoverflow.com/q/48556045
downvote count: 0
has body: You can do as was intimated in your example: RenamerSTD(replaceClean(text)) In which case it is the responsibilty of the caller to make the sub-call. Or you can simply have RenamerSTD call replaceClean like: def replaceClean(text): ... return text def RenamerSTD(text1): text1 = replaceClean(text1) ....
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84108451
accepted answer of: http://stackoverflow.com/q/48556045
has comment: http://stackoverflow.com/comment/84110072

http://stackoverflow.com/comment/84363382
type: AnswerComment
has text: Thanks, @2ps we will check it.
comment on: http://stackoverflow.com/a/48644788
type: Comment
score: 0

http://stackoverflow.com/q/48505498
duplicate of: http://stackoverflow.com/q/45621722
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84005707
answer count: 2
has answer: http://stackoverflow.com/a/48505632
has title: every time i run an program i get error: there is an error in your program: expected an indented bloak
linked to: http://stackoverflow.com/q/45621722
type: UnansweredQuestion
tagged with: python
score: -10
has comment: http://stackoverflow.com/comment/84004988
has comment: http://stackoverflow.com/comment/84005097
has comment: http://stackoverflow.com/comment/84005010
has body: # import swampy from swampy.TurtleWorld import * world = TurtleWorld() bob = Turtle() def polygon(t, n, length): angle = 360.0 / n for i in range(n): fd(t, length) lt(t, angle) polygon(bob, 7, 70) expected an indented bloak every time i run program i get this error
upvote count: 0
has comment: http://stackoverflow.com/comment/84005118
has comment: http://stackoverflow.com/comment/84005032
has answer: http://stackoverflow.com/a/48505593
downvote count: 10

http://stackoverflow.com/comment/84178307
score: 0
type: Comment
type: AnswerComment
has text: Thanks, I'm using python 2.7. This is a bot, or should be, a bot learning the conversation accordingly with the given training. In this case, "talk" was the data entry that he should recognize, "hi", and answer with the other options, but I do not know why it's giving error, I've already researched these problems here, until I try some solutions but not It worked. I wanted to make the same video on youtube: https://www.youtube.com/watch?v=VtF-Ucj4aAM&t=278s
comment on: http://stackoverflow.com/a/48587617

http://stackoverflow.com/comment/83975583
type: QuestionComment
has text: @DavisHerring please write your suggestion as answer, I am curious about how to do it with subprocess. I was only familiar with the os package, but I assume it was not the most efficient way of doing it.
score: 0
comment on: http://stackoverflow.com/q/48490382
type: Comment

http://stackoverflow.com/comment/84123965
score: 1
has text: Exactly that, yes :)
comment on: http://stackoverflow.com/a/48562053
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48581558
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/84159567
has body: I have this JSON file where the amount of id's sometimes changes (more id's will be added): { "maps": [ { "id": "blabla1", "iscategorical": "0" }, { "id": "blabla2", "iscategorical": "0" }, { "id": "blabla3", "iscategorical": "0" }, { "id": "blabla4", "iscategorical": "0" } ] } I have this python code that has to print all the values of ids: import json data = json.load(open('data.json')) variable1 = data["maps"][0]["id"] print(variable1) variable2 = data["maps"][1]["id"] print(variable2) variable3 = data["maps"][2]["id"] print(variable3) variable4 = data["maps"][3]["id"] print(variable4) I have to use variables, because i want to show the values in a dropdown menu. Is it possible to save the values of the id's in a more efficient way? How do you know the max amount of id's of this json file (in de example 4)?
score: 1
has answer: http://stackoverflow.com/a/48581764
possible better answer: http://stackoverflow.com/a/48581764
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48581621
has comment: http://stackoverflow.com/comment/84159421
favorite count: 0
type: Question
has title: Parse Json file and save specific values
linked to: http://stackoverflow.com/q/7271482
duplicate of: http://stackoverflow.com/q/7271482
tagged with: python
accepted answer: http://stackoverflow.com/a/48581621

http://stackoverflow.com/q/48633847
downvote count: 0
linked to: http://stackoverflow.com/q/29935283
has comment: http://stackoverflow.com/comment/84264983
tagged with: logging
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84264936
has answer: http://stackoverflow.com/a/48633940
has body: I am trying to make a script that takes all errors and logs them to a log file. I want to include any argparse errors to this file. I already use the logging package and a sys.excepthook to drive unexpected exceptions to the log file. Here's an example code: import argparse import logging import sys import traceback def log_uncaught_exceptions(ex_cls, ex, tb): logging.critical(''.join(traceback.format_tb(tb))) logging.critical('{0}: {1}'.format(ex_cls, ex)) logging.basicConfig( level=logging.DEBUG, filename='foo.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s') sys.excepthook = log_uncaught_exceptions logging.debug('This is a typical debug line') parser = argparse.ArgumentParser(description='Foo String') parser.add_argument('foo',type=int) args = parser.parse_args() logging.debug('Input was %i'%(args.foo)) When I run it with python logger_argparse.py 1 everything works great. If I run python logger_argparse.py a I get the output in the console and not the log file: usage: logger_argparse.py [-h] foo logger_argparse.py: error: argument foo: invalid int value: 'a' How do I get that information to go to the log file?
has title: Python argparse errors to file
tagged with: argparse
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48653668
has comment: http://stackoverflow.com/comment/84265531
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84265455
answer count: 2

http://stackoverflow.com/a/48489897
type: Answer
has comment: http://stackoverflow.com/comment/83973622
has comment: http://stackoverflow.com/comment/83972959
answers question: http://stackoverflow.com/q/48489753
score: 5
upvote count: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83972824
has comment: http://stackoverflow.com/comment/83972852
accepted answer of: http://stackoverflow.com/q/48489753
has comment: http://stackoverflow.com/comment/84005418
has comment: http://stackoverflow.com/comment/83972727
downvote count: 0
has body: The problem is in the result transfer. Consider that with multiprocessing the arrays you create inside the child processes need to be transferred back to the main process.. and this is an overhead. I checked this modifying the AddNoise function in this way, which preserve the computation time, but discard the transfer time: def AddNoise(sample): sample + numpy.random.randint(0,9,sample.shape) return None
has comment: http://stackoverflow.com/comment/83973010

http://stackoverflow.com/comment/83989037
type: QuestionComment
comment on: http://stackoverflow.com/q/48496552
has text: Ok, the matching Tensorflow model for that checkpoint is defined in the [python file](https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_v3.py) that goes with the checkpoint. I assume you already downloaded that (if not, do so and put it in the same folder as your script)
score: 1
type: Comment

http://stackoverflow.com/a/48672858
has comment: http://stackoverflow.com/comment/84505106
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48505458
downvote count: 0
has comment: http://stackoverflow.com/comment/133516027
has comment: http://stackoverflow.com/comment/84537256
has comment: http://stackoverflow.com/comment/84501414
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/84494537
accepted answer of: http://stackoverflow.com/q/48505458
has comment: http://stackoverflow.com/comment/84503588
type: Answer
has comment: http://stackoverflow.com/comment/115221585
has body: The current answer here has two parts: pytest configuration coverage.py configuration Let's start with the pytest configuration. Currently on your coverage branch there is the .travis.yml file with the following line: py.test --cov tests, this tells pytest-cov to show you the coverage for the tests directory, which you don't want. You can run py.test tests --cov instead or change your setup.cfg and not pass the tests at all. You would then have the setup.cfg file with: [tool:pytest] testpaths = tests In the .coverage file you need: [run] plugins = Cython.Coverage source = src/pyscipopt omit = tests *__init__.py Specifying the paths separately is obsolete and I have removed it. This way coverage.py knows that it should only check coverage for the src/pyscipopt directory. After these changes the output I got is: ---------- coverage: platform darwin, python 3.6.4-final-0 ----------- Name Stmts Miss Branch BrPart Cover --------------------------------------------------------------- src/pyscipopt/Multidict.py 17 17 10 0 0% src/pyscipopt/conshdlr.pxi 301 129 0 0 57% src/pyscipopt/expr.pxi 168 57 0 0 66% src/pyscipopt/heuristic.pxi 44 18 0 0 59% src/pyscipopt/lp.pxi 235 177 0 0 25% src/pyscipopt/pricer.pxi 52 24 0 0 54% --------------------------------------------------------------- TOTAL 817 422 10 0 48% This looks like the proper output you want, but I do see the scip.pyx file is missing. You can also look at a related issue on github. I am not investigating further because it answers your question and I think you will be able to go from here with whatever is missing.

http://stackoverflow.com/a/48543659
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48543554
has comment: http://stackoverflow.com/comment/84082557
type: Answer
has body: If I understand well your question, you want to append a new value to your dictionary if the key already exists. If so, I would use a defaultdict for a simple reason. With a defaultdict you can use the method += to create (if does not exist) or add (if exist) an element : from collections import defaultdict # Your dictionaries mydict = { 'a': [[2,4], [5,6]], 'b': [[1,1], [1,7,9], [6,2,3]], 'c': [['a'], [4,5]], } plus_min_dict = {'a': [[3,3]]} # d is a DefaultDict containing mydict values d=defaultdict(list,mydict) # d_new is a DefaultDict containing plus_min_dict dict d_new = defaultdict(list, plus_min_dict) # Add all key,values of d in d_new for k, v in d.items(): d_new[k] += d[k] print(d_new) Results : defaultdict(&lt;class 'list'&gt;, {'c': [['a'], [4, 5]], 'a': [[3, 3], [2, 4], [5, 6]], 'b': [[1, 1], [1, 7, 9], [6, 2, 3]]})
score: 1

http://stackoverflow.com/a/48641333
has comment: http://stackoverflow.com/comment/84279678
has comment: http://stackoverflow.com/comment/84281125
score: 2
has comment: http://stackoverflow.com/comment/84279551
type: Answer
has comment: http://stackoverflow.com/comment/84279631
has comment: http://stackoverflow.com/comment/84280002
has body: So your loop body looks broadly ok, it's a nice use of zip. The main issue is that each time round the loop, you're creating a new new_data dict, and updating request.data with it. It sounds like what you actually want to do is build up a list of those new_dicts, and then after the loop completes, add that list to your request data. So the structure would be more like: samples = [] for param, time, value in zip(parameters, time_stamps, values): new_data = { "sensor": dataDict["source"], "parameter": param, "parameter_value": value, "time": time } # Note you don't need the extra () around the dict here # You don't need this at all - new_data will only have the 4 keys you defined above as it's a brand new dict # Clean the lists I don't need # removeKeys = ('parameters', 'data_array', 'datasource') # for k in removeKeys: # new_data.pop(k, None) samples.append(new_data) # You'll need to work out how the request data needs to be sent back request.data['???'] = samples
upvote count: 2
answers question: http://stackoverflow.com/q/48641000
downvote count: 0

http://stackoverflow.com/q/48561247
type: UnansweredQuestion
downvote count: 0
has body: For a tutorial, I want to implement manually what the TfidfVectorizer is doing, just to show what's going on in the background. In this Stack Overflow article I found how the TfidfVectorizer works. With this, it was straightforward to implement it in a naive manner, and with the correct parameter settings for the vectorizer, the output is indeed the same. All good. However, now I'm a bit confused: The TfidfVectorizer calculates the term frequency tf using the CountVevtorizer. That means tf is just an integer representing the number of occurrences of a term in a document. But usually the term frequency tf(t,d) of term t in a document d is defined as: tf(t,d) = (#occurrences of t in d) / (#terms in d) So the term frequency is a value between 0 and 1. How does this fit together? Why is using the TfidfVectorizer the term count and not the (normalized) frequency according to the definition. I assume it's no a big deal but I would to understand it.
has title: TfidfVectorizer vs. definition of tf-idf
tagged with: scikit-learn
tagged with: python
score: 4
answer count: 1
linked to: http://stackoverflow.com/q/36966019
has answer: http://stackoverflow.com/a/48564625
favorite count: 0
type: Question
upvote count: 4
tagged with: tf-idf

http://stackoverflow.com/q/48578339
tagged with: pandas
has comment: http://stackoverflow.com/comment/84170103
downvote count: 1
tagged with: sklearn-pandas
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48581551
has body: I'm trying to do some classification problems using sklearn for the first time in Python, and was wondering what was the best way to go about calculating the error of my classifier (like a SVM) solely on the training data. My sample code for calculating accuracy and rmse are as follows: svc = svm.SVC(kernel='rbf', C=C, decision_function_shape='ovr').fit(X_train, y_train.ravel()) prediction = svc.predict(X_test) svm_in_accuracy.append(svc.score(X_train,y_train)) svm_out_rmse.append(sqrt(mean_squared_error(prediction, np.array(list(y_test))))) svm_out_accuracy.append((np.array(list(y_test)) == prediction).sum()/(np.array(list(y_test)) == prediction).size) I know from 'sklearn.metrics import mean_squared_error' can pretty much get me the MSE for an out-of-sample comparison. What can I do in sklearn to give me an error metric on how my well/not well my model misclassified on the training data? I ask this because I know my data is not perfectly linearly separable (which means the classifier will misclassify some items), and I want to know the best way to get an error metric on how much it was off. Any help would be appreciated!
answer count: 1
upvote count: 1
tagged with: scikit-learn
tagged with: python
has title: Sklearn: how to get mean squared error on classifying training data
has comment: http://stackoverflow.com/comment/84153733
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48581551

http://stackoverflow.com/q/48510055
tagged with: python
has comment: http://stackoverflow.com/comment/84016987
has comment: http://stackoverflow.com/comment/84015405
has comment: http://stackoverflow.com/comment/84015644
has title: global functions dont work with tkinter
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84015362
accepted answer: http://stackoverflow.com/a/48523092
has comment: http://stackoverflow.com/comment/84015253
has answer: http://stackoverflow.com/a/48523092
type: AnsweredQuestion
score: 0
has body: I wrote a basic script in Python3 to create a basic function that would display then close a window. I would like to have a function to close the window, so I could import the script into a different file I have without cluttering it up too much. I tried this, however the compiler returns with name tkdel() is not defined. def tkdisp(t): import tkinter as tk class disp(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.distk = tk.Label(self) self.distk["text"] = t self.distk.pack(side="top") root = tk.Tk() disp(master=root).mainloop() def tkdel(): global tkdel root.destroy tkdisp('nice') tkdel()
has comment: http://stackoverflow.com/comment/84015429
answer count: 1

http://stackoverflow.com/q/48511411
has comment: http://stackoverflow.com/comment/84018088
has title: Huge list on memory and file ( append, sort and write) without DB only flat file
type: Question
tagged with: indexing
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84017829
tagged with: python
has comment: http://stackoverflow.com/comment/84017966
has comment: http://stackoverflow.com/comment/84017957
has comment: http://stackoverflow.com/comment/84017784
has comment: http://stackoverflow.com/comment/84017810
has comment: http://stackoverflow.com/comment/84017719
tagged with: list
score: 0
answer count: 0
has body: I have a huge list made of names ( in hexa ) every names lengh is from 2 to 40 lengh. After checking this thread on SO I could not manage to get it work. The idea is to store the name every time I call the script ( easy append ) . to Be able to provide this list at will And finally to check ( either the name is on memory or in the file) a name is on that list. any thought ?
has comment: http://stackoverflow.com/comment/84017666
linked to: http://stackoverflow.com/q/1989251

http://stackoverflow.com/a/48519005
type: Answer
score: 2
downvote count: 0
has body: I had the same problem. For whatever reason on Windows 10 it doesn't want to find graphviz even if I added to path. So finally I solved by adding os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/' to my project.
upvote count: 2
answers question: http://stackoverflow.com/q/48507679

http://stackoverflow.com/q/48514222
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/48514302
has comment: http://stackoverflow.com/comment/84422349
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/48703155
score: 9
has body: I tried on google but I did not found the solution. In Django admin side, I'm displaying start date and end date with time. But time is in 24 hr format and I want to display it in 12 hr format class CompanyEvent(models.Model): title = models.CharField(max_length=255) date_start = models.DateTimeField('Start Date') date_end = models.DateTimeField('End Date') notes = models.CharField(max_length=255) class Meta: verbose_name = u'Company Event' verbose_name_plural = u'Company Events' def __unicode__(self): return "%s (%s : %s)" % (self.title, self.date_start.strftime('%m/%d/%Y'), self.date_end) I also found out this but it isn't helping me. I am new to python and django. Please help.
tagged with: time-format
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34639280
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48703155
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/48521723
has title: Django Admin DateTimeField Showing 24hr format time
has answer: http://stackoverflow.com/a/48521723
tagged with: django
favorite count: 0

http://stackoverflow.com/comment/84130265
comment on: http://stackoverflow.com/q/48567031
type: Comment
has text: I am not sure what this code is for, but you could also just do `new_list = [2 * xi for xi in Number]`
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84076871
type: Comment
comment on: http://stackoverflow.com/a/48540826
type: AnswerComment
has text: You should use the csv module instead of splitting on commas.
score: 1

http://stackoverflow.com/comment/84167403
type: Comment
type: QuestionComment
score: 0
has text: I am a newbie to things AWS so I am trying to realize the best development framework that particularly fits AWS IOT Greengrass development and also catches MEAN development with AWS, How many languages must I know and use? What languages can only do? AWS lists many SDKs for most the popular languages but what our the differences in capability being these offerings, hard to know because Amazon folk do not give a spreadsheet or such to show you.
comment on: http://stackoverflow.com/q/48571995

http://stackoverflow.com/q/48538847
has comment: http://stackoverflow.com/comment/84079081
upvote count: 1
tagged with: php
has comment: http://stackoverflow.com/comment/84084146
downvote count: 1
favorite count: 0
has title: Unusual high number of exclusive locks in PostgreSQL database
type: AnsweredQuestion
tagged with: postgresql
has body: I am pretty new to database design and PostgreSQL in general, but I am aware of the general concept behind row versioning, transactions and exclusive locks in Postgres (e.g. this article gives a pretty good overview). My current problem is that a) I am not sure why I get so many exclusive locks show up in my PG database log files and b) why these locks are happening at all. I run PostgreSQL 10 (+ PostGIS extension) with about 300 Million rows over 5 tables (200GB). I have about 5 scripts (4x PHP and 1x Python Psycopg2) running 24/7 that make a lot of inserts (and DO UPDATE with COALESCE, in case the entry already exist). However, as far as I understand, PHP Postgres extension commits automatically after each SQL Query and in my Python Script, increasing commits does not significantly reduce locks. I have a couple of triggers that dynamically update rows, but as far as I can tell from the log files they are not the cause of locks. It should generally be very rare that two or more of my scripts insert/update the same row at the same time. This is an example log entry: 2018-01-31 01:04:02 CET [808]: [258-1] user=user1,db=maindb,app=[unknown],client=::1 LOG: process 808 still waiting for ExclusiveLock on page 0 of relation 26889 of database 16387 after 1015.576 ms 2018-01-31 01:04:02 CET [808]: [259-1] user=user1,db=maindb,app=[unknown],client=::1 DETAIL: Process holding the lock: 680. Wait queue: 1728, 152, 808. 2018-01-31 01:04:02 CET [808]: [260-1] user=user1,db=maindb,app=[unknown],client=::1 STATEMENT: INSERT INTO "table1" (...) VALUES (...) ON CONFLICT (...) DO UPDATE SET ...; I have similar log entries about every 2-3 Minutes. Are they problematic? What do they mean exactly, are the locks finally resolved or is the data of the transaction lost? There is no log entry that states that locks are resolved or updates are finally committed to the database. The second type of frequent log entry is similar to this: 2018-01-31 07:22:16 CET [2504]: [16384-1] user=,db=,app=…
has comment: http://stackoverflow.com/comment/84084355
tagged with: python
accepted answer: http://stackoverflow.com/a/48605194
has comment: http://stackoverflow.com/comment/84084245
type: Question
has answer: http://stackoverflow.com/a/48605194
tagged with: locking
has comment: http://stackoverflow.com/comment/84073063
tagged with: plpgsql
score: 0
answer count: 1

http://stackoverflow.com/comment/84149379
score: 0
comment on: http://stackoverflow.com/q/48574997
has text: I didn't realize this library was using WebHDFS, so yes it'll need to be HTTP. But on port 50700
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84107269
type: Comment
comment on: http://stackoverflow.com/a/48519769
has text: Thanks @dsesto, Okay, the scripts that I'm running are pre-processing scripts (so they need to be run only once). I want the cleaned/modified data to be query-able so we decided to go ahead with BigQuery.
type: AnswerComment
score: 0

character-encoding
tags question: http://stackoverflow.com/q/48537305
tags question: http://stackoverflow.com/q/48506352
tag name: character-encoding
tags question: http://stackoverflow.com/q/48532369
tags question: http://stackoverflow.com/q/48544059
tags question: http://stackoverflow.com/q/48593614
tags question: http://stackoverflow.com/q/48529256
type: Tag
tags question: http://stackoverflow.com/q/48622262

xgboost
tags question: http://stackoverflow.com/q/48541671
tags question: http://stackoverflow.com/q/48645846
tags question: http://stackoverflow.com/q/48511008
tags question: http://stackoverflow.com/q/48513591
tag name: xgboost
type: Tag

http://stackoverflow.com/comment/84239978
has text: i didn't get you.Are you sayng you have to tap the button 15 times?
type: AnswerComment
comment on: http://stackoverflow.com/a/48618850
score: 0
type: Comment

http://stackoverflow.com/q/48626492
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Error when running Python in VS Code
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/84603740
has comment: http://stackoverflow.com/comment/84250286
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/97084958
has answer: http://stackoverflow.com/a/65530522
linked to: http://stackoverflow.com/q/11813435
tagged with: python
has comment: http://stackoverflow.com/comment/84249848
score: 1
has body: python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. I have downloaded Python 3 and the extension. I have shut down VScode and restarted. Can anyone help with this?
has comment: http://stackoverflow.com/comment/84309085

http://stackoverflow.com/comment/84308146
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48626736
has text: @SunBear: the data is simply stored internally by the widget. The listbox itself is the object that holds the data.

http://stackoverflow.com/a/48570955
has comment: http://stackoverflow.com/comment/84139002
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48570320
downvote count: 0
has body: This looks like a string-vs-bytes encoding issue. To decode a byte string: str = byte_string.decode('UTF-8') # turns b'123' into '123' To encode the string to bytes: byte_string = str.encode('UTF-8') # turns '123' into b'123' You probably need to encode the incoming string to bytes before you pass it to jwt.decode() like so: jwt.decode(token.encode('UTF-8'), SECRET_KEY) There are other encodings besides UTF-8, but that will probably be what you need.
answers question: http://stackoverflow.com/q/48570320
has comment: http://stackoverflow.com/comment/84138989
has comment: http://stackoverflow.com/comment/84138877

http://stackoverflow.com/q/48551823
type: Question
answer count: 2
tagged with: python
has body: I would like to perform an aggregation on a multi-index pandas series that looks like so: revenue = date person shift 2017-10-19 Adams A 298.70 Smith B 593.46 B_Overtime 77.71 2017-10-20 Conner A 473.08 Adams B 441.35 Smith C 392.97 2017-10-21 Adams A 374.79 Smith B 169.02 Conner C 124.63 Where the series is for revenue by date, person and shift. I would like to find the mean of revenue by person and shift, then revenue mean by shift. If I do something like revenue.mean() it just gives me one number since it is a series and can't us groupy again. I looked at unstacking the Series but that seems to make things worse, since I have a bunch of 0's. Which I suppose are ok,since they won't contribute to a mean value. I am stuck on this one.
has answer: http://stackoverflow.com/a/48551978
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48551959
tagged with: pandas-groupby
tagged with: pandas
score: 0
has title: Perform Aggregation on MultiIndex Pandas Series

http://stackoverflow.com/a/48495742
has body: We want to use what we get from training data, apply it to test data, in the previous piece of code, the loop doesn't work, the first column is a column of numbers, so it will fill all the NaNs in the test data as the mean of the first column of training data. Instead, if I use fillna with values, here values is a dictionary, test data will match training data according to categories. values = {} #declare dict for c in x_train: if x_train[c].dtype==np.dtype('O'): values[c]=x_train[c].value_counts().index[0] else: values[c]=x_train[c].mean() values.update({c:values[c]}) x_test_new = x_test.fillna(value=values)
has comment: http://stackoverflow.com/comment/84010561
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/84013017
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48495372

http://stackoverflow.com/comment/84058171
comment on: http://stackoverflow.com/q/48526884
score: 0
type: Comment
type: QuestionComment
has text: I did solve it. I had to put the virtual environment and the app directory in the same folder. Previous I had the app folder inside the httpdocs folder with the environment folder a level up. I also switched some nginx switches to stop Apache being involved. Thanks for the suggestions though.

http://stackoverflow.com/a/48550307
answers question: http://stackoverflow.com/q/48549018
downvote count: 0
type: Answer
has body: Most but perhaps not all signatures you can get using the numpydoc module: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import inspect &gt;&gt;&gt; import numpydoc &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; # inspect doesn't work &gt;&gt;&gt; inspect.signature(np.ndarray.transpose) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/paul/local/lib/python3.6/inspect.py", line 3002, in signature return Signature.from_callable(obj, follow_wrapped=follow_wrapped) File "/home/paul/local/lib/python3.6/inspect.py", line 2752, in from_callable follow_wrapper_chains=follow_wrapped) File "/home/paul/local/lib/python3.6/inspect.py", line 2231, in _signature_from_callable skip_bound_arg=skip_bound_arg) File "/home/paul/local/lib/python3.6/inspect.py", line 2061, in _signature_from_builtin raise ValueError("no signature found for builtin {!r}".format(func)) ValueError: no signature found for builtin &lt;method 'transpose' of 'numpy.ndarray' objects&gt; &gt;&gt;&gt; &gt;&gt;&gt; info = numpydoc.docscrape.FunctionDoc(np.ndarray.transpose) &gt;&gt;&gt; info['Signature'] 'a.transpose(*axes)' &gt;&gt;&gt; pprint(info['Parameters']) [('axes', 'None, tuple of ints, or `n` ints', ['', '* None or no argument: reverses the order of the axes.', '', "* tuple of ints: `i` in the `j`-th place in the tuple means `a`'s", " `i`-th axis becomes `a.transpose()`'s `j`-th axis.", '', '* `n` ints: same as an n-tuple of the same ints (this form is', ' intended simply as a "convenience" alternative to the tuple form)'])] &gt;&gt;&gt; &gt;&gt;&gt; info = numpydoc.docscrape.FunctionDoc(np.ndarray.std) &gt;&gt;&gt; info['Signature'] 'a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False)' # sometimes info is incomplete &gt;&gt;&gt; pprint(info['Parameters']) []
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84167998

http://stackoverflow.com/a/48549861
has comment: http://stackoverflow.com/comment/91463144
has comment: http://stackoverflow.com/comment/84095752
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84096523
has comment: http://stackoverflow.com/comment/91491126
has comment: http://stackoverflow.com/comment/84095715
has comment: http://stackoverflow.com/comment/91505729
has body: You need to read for secret_word in loop, and use break to exit when it matches wanted : secret_word = "" while True: secret_word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop.") if secret_word == "chupacabra": print("You've successfully left the loop.") break
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48549798

http://stackoverflow.com/comment/84056864
score: 0
type: AnswerComment
has text: I tried df.columnWithInts.astype(int) and it generates "ValueError: cannot convert float NaN to integer" so there must be some observation in that set that doesn't look like an integer
comment on: http://stackoverflow.com/a/48530372
type: Comment

http://stackoverflow.com/q/48622002
tagged with: windows
has body: I want to make my script run on startup automatically after converting it to EXE by pyinstaller tool , *once clicking on SPEED.EXE 'name of program' ,It copies itself to particular path on computer then makes a bat file in startup folder 'it contains code to start SPPED.EXE' but my problem that bat file doesnot run on start * import os import ftplib import sys import shutil import getpass ##################copy script into startup####################### def copy_script(): USER_NAME = getpass.getuser() src=sys.argv[0] dst = r'C:\Users\%s\AppData' % USER_NAME shutil.copy2(src,dst) dst='C:\Users\\"%s"\AppData\SPEED.exe' % USER_NAME ######name of script after making EXE add_to_startup(USER_NAME,file_path=dst) return None ######################################make a bat file to run on startup###### def add_to_startup(USER_NAME,file_path): if file_path == "": file_path = os.path.dirname(os.path.realpath(__file__)) bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME with open(bat_path + '\\' + "open.bat", "w") as bat_file: bat_file.write(r'@echo off'+ os.linesep) ## to hide console batch file when it run bat_file.write(r'start "" %s' % file_path) if __name__=='__main__': copy_script() start() ##it is function that i make it
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/84244431
has comment: http://stackoverflow.com/comment/84244136
has comment: http://stackoverflow.com/comment/84243500
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/84245129
linked to: http://stackoverflow.com/q/674628
has comment: http://stackoverflow.com/comment/84241694
downvote count: 1
has answer: http://stackoverflow.com/a/48643061
has comment: http://stackoverflow.com/comment/84282565
favorite count: 0
tagged with: startup
type: Question
has title: how to make script in python run at startup after converting it to exe by py installer
tagged with: batch-file
tagged with: pyinstaller
type: UnansweredQuestion

http://stackoverflow.com/comment/84249440
comment on: http://stackoverflow.com/q/48625470
has text: If there might be settings, then those should be module-level global variables. There is no need to define a class here.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84188837
type: AnswerComment
comment on: http://stackoverflow.com/a/48595940
score: 0
type: Comment
has text: Thanks for the answer, my data is already normalized, but I'll try your other remarks as soon as my current training process is done

http://stackoverflow.com/comment/84017522
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48511307
has text: [Round](https://docs.scipy.org/doc/numpy/reference/generated/numpy.round_.html) allows you to round to any decimal you want. No need for multiplication of input or any other similar tricks, otherwise useful 20 years ago.
type: Comment

http://stackoverflow.com/comment/136545328
comment on: http://stackoverflow.com/a/48565216
type: AnswerComment
has text: @pinty Would you maybe have any update on your answer given PEP-668 is out in 2023 and now the system basically blocks non-venv `pip install`?
score: 0
type: Comment

http://stackoverflow.com/comment/84222069
has text: Question updated! Code with text without pictures.
comment on: http://stackoverflow.com/q/48609484
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84040609
comment on: http://stackoverflow.com/a/48522969
score: 1
type: Comment
has text: I checked, but I didn't use range anywhere before. And where should I add the `del range` ?
type: AnswerComment

http://stackoverflow.com/a/48640815
has comment: http://stackoverflow.com/comment/84278138
answers question: http://stackoverflow.com/q/48640747
score: 0
has body: Not unless you can read the original page. The browser isn't sending you all possible values.
has comment: http://stackoverflow.com/comment/84278703
type: Answer

http://stackoverflow.com/q/48604845
has comment: http://stackoverflow.com/comment/84206352
tagged with: scikit-image
tagged with: python
accepted answer: http://stackoverflow.com/a/48605596
type: Question
has body: I have three images in three numpy arrays a,c,s. The values are between [0,0.99] (the probabilities). The following shows the vertical arrangement of images. I stacked them by this command x=np.dstack([a,c,s]) and the shape becomes (256, 256, 3), the following image is obtained: I wanted to get the maximum value among three stacked arrays, to maximum intersection area of images, for example for each point, we have three values: print x[200,100,:] out: [0.99662614 0.98577976 0.99949038] after getting argmax, I am getting the following output: maxIndex= np.argmax(x, axis=2) print np.shape(maxIndex) plt.imshow(maxIndex) plt.show() which is not what I want. Could you please guide me how to get the maximum value of three values in a way that I can get maximum intersection area of three?
tagged with: numpy
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/48605596
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/84206502
has title: How to get the maximum value of three stacked numpy arrays (representing images) to get the intersection area?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84206443

http://stackoverflow.com/q/48643445
answer count: 1
accepted answer: http://stackoverflow.com/a/48644022
linked to: http://stackoverflow.com/q/30332908
has answer: http://stackoverflow.com/a/48644022
favorite count: 0
type: Question
tagged with: numpy
upvote count: 0
score: -2
tagged with: python
has body: I have a following 2 dimensional numpy array: [[2,3,1,5], [4,3,6,5], [7,10,8,9]] For each array on axis=1 I'd like to get indexes of N items with highest values. Example: response for N=2 should look like this: [[3,1], [2,3], [1,3]]
has title: Indexes of top N values in 2 dimensional array
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84285924
downvote count: 2

http://stackoverflow.com/a/48646731
score: 1
answers question: http://stackoverflow.com/q/48644166
type: Answer
upvote count: 1
has body: To submit you zip folder to python spark, you need to send the files using : spark-submit --py-files your_zip your_code.py While using it inside your code, you will have to use below statement: sc.addPyFile("your_zip") import your_zip Hope this will help!!
has comment: http://stackoverflow.com/comment/85264291
downvote count: 0

http://stackoverflow.com/q/48522640
tagged with: psycopg2
tagged with: docker
has answer: http://stackoverflow.com/a/48565404
has title: Failure to connect to Docker Postgresql instance from Python
type: AnsweredQuestion
score: 20
downvote count: 0
has answer: http://stackoverflow.com/a/48648959
accepted answer: http://stackoverflow.com/a/48648959
has answer: http://stackoverflow.com/a/48566272
has comment: http://stackoverflow.com/comment/84137091
has answer: http://stackoverflow.com/a/77033949
favorite count: 0
type: Question
upvote count: 20
possible better answer: http://stackoverflow.com/a/48565404
tagged with: postgresql
has body: I am using Docker to "containerize" a PostgreSQL deployment. I can spin up the container and connect to PostgreSQL via the command line as shown below: minime2@CEBERUS:~/Projects/skunkworks$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES dc176901052a df:pg "docker-entrypoint..." About an hour ago Up About an hour 5432/tcp vigilant_agnesi minime2@CEBERUS:~/Projects/skunkworks$ CONTAINER_ID=dc176901052a minime2@CEBERUS:~/Projects/skunkworks$ IP=$(docker inspect -f '{{.NetworkSettings.Networks.bridge.IPAddress}}' $CONTAINER_ID) minime2@CEBERUS:~/Projects/skunkworks$ echo $IP 172.17.0.2 minime2@CEBERUS:~/Projects/skunkworks$ docker exec -it vigilant_agnesi psql -U postgres -W cookiebox Passwod for user postgres: psql (9.6.5) Type "help" for help cookiebox# Now attempting connection with Python: Python 3.5.2 (default, Sep 14 2017, 22:51:06) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import psycopg2 &gt;&gt;&gt; conn = psycopg2.connect("dbname='cookiebox' user='postgres' host='172.17.0.2' password='nunyabiznes'") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/minime2/Projects/skunkworks/archivers/env/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "172.17.0.2" and accepting TCP/IP connections on port 5432? &gt;&gt;&gt; Can anyone explain why I can't connect to PostgreSQL using Python - even though I'm using the same arguments/parameters that enable a successful connection at the command line (using docker exec?). Additional Info As suggested by @Itvhillo, I tried to use a desktop application to connect to the PG service. I run the docker service using the following command: docker run -i -p 5432:5432 --name $CONTAINER_NAME $DOCKER_IMAGE I…
answer count: 5
has comment: http://stackoverflow.com/comment/84126486
has answer: http://stackoverflow.com/a/48647227
tagged with: python

http://stackoverflow.com/comment/84281122
type: AnswerComment
score: 0
has text: I know it's reading the whole file and creating dataframe. The dataframe exists. It's just that I can't choose specific columns
type: Comment
comment on: http://stackoverflow.com/a/48641912

http://stackoverflow.com/comment/83999556
has text: @AdamBarnes if I understand correctly I would simply add .annotate(currentstanding='academicstanding__standing') to the queryset in the filter. However I now get 'str' object has no attribute 'resolve_expression' - what am I doing incorrectly here?
type: QuestionComment
comment on: http://stackoverflow.com/q/48500712
score: 0
type: Comment

http://stackoverflow.com/comment/84264879
has text: What _exactly_ columns does your dataframe have?
comment on: http://stackoverflow.com/q/48630182
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84057735
has text: You can refer to AWS EC@ SDK here: https://github.com/aws/aws-sdk-android/tree/master/aws-android-sdk-ec2 and for load balancing, here: https://github.com/aws/aws-sdk-android/tree/master/aws-android-sdk-elb. Please feel free to open an issue in github when you face a roadblock in using the APIs: https://github.com/aws/aws-sdk-android/issues
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48509364

http://stackoverflow.com/a/48606040
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48605961
has comment: http://stackoverflow.com/comment/107376954
has comment: http://stackoverflow.com/comment/84208479
answers question: http://stackoverflow.com/q/48605961
has comment: http://stackoverflow.com/comment/84208443
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84208415
upvote count: 2
has body: If you want to generate random int, use np.random.randint(). If you want to convert float to int, use np.int32(something).
type: AcceptedAnswer

http://stackoverflow.com/q/48640667
answer count: 1
type: Question
tagged with: python
tagged with: plot
has body: I tried to plot multiple line on bokeh server and it almost work find. But there is one problem of colors for lines. My code is like below and when I operate in on bokeh server, it raise 'Runtime error' , why? how can i fix it? p.multi_line('year', 'area', alpha=0.6, color=BuGn8, source=source) RuntimeError: Supplying a user-defined data source AND iterable values to glyph methods is not possibe. Either: Pass all data directly as literals: p.circe(x=a_list, y=an_array, ...) Or, put all data in a ColumnDataSource and pass column names: source = ColumnDataSource(data=dict(x=a_list, y=an_array)) p.circe(x='x', y='x', source=source, ...)
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48648029
tagged with: bokeh
has answer: http://stackoverflow.com/a/48648029
has title: Bokeh Server doesn't show proper color for Multiple line plot

http://stackoverflow.com/comment/84266292
score: 0
has text: John: You're welcome. The "extra arguments trick" is exactly what one would expect from it's name: i.e. "tricky", so don't worry too much about not knowing it. At least now you'll be able to recognize when it's needed as well as how to do it. Motivated Reading's great, but only useful if there's some material to be read...
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48615193

http://stackoverflow.com/comment/84349373
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48589051
has text: @jpaugh thanks, I posted this and honestly, I’m in the same boat as you. I like it but I don’t
type: Comment

http://stackoverflow.com/q/48631638
tagged with: list
has title: Convert a Python List to an Array
accepted answer: http://stackoverflow.com/a/48631685
has answer: http://stackoverflow.com/a/48631685
score: 1
has comment: http://stackoverflow.com/comment/84260362
favorite count: 0
type: Question
tagged with: numpy
has body: I'm trying to convert a list to a numpy array. My list's length is 64, each element of the list is an numpy array(8 x 8). My output should be a numpy array of (8,8,1,64). How can I convert list to numpy array. type(dct) &gt;&gt;&gt;list len(dct) &gt;&gt;&gt;64 type(dct[0]) &gt;&gt;&gt;numpy.ndarray dct[0].shape &gt;&gt;&gt;(8,8)
tagged with: arrays
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48519768
tagged with: odoo-10
has answer: http://stackoverflow.com/a/48528280
type: Question
has answer: http://stackoverflow.com/a/48538519
answer count: 2
type: UnansweredQuestion
tagged with: python
has title: Automatically create one2many fields
has body: I hope I'll be clear enough to explain my problem. In account module we have account.payment.term and account.payment.term.line model that are related with one2many relation: class AccountPaymentTerm(models.Model): _name = "account.payment.term" _description = "Payment Term" line_ids = fields.One2many('account.payment.term.line', 'payment_id', string='Terms', copy=True, default=_default_line_ids) period = fields.Selection([('month', '1 Month'),], string='Period', required=True, default='month', help="Select here the period between payments") how_much = fields.Float() fixed_amount = fields.Float() class AccountPaymentTermLine(models.Model): _name = "account.payment.term.line" _description = "Payment Term Line" payment_id = fields.Many2one('account.payment.term', string='Payment Terms', required=True, index=True, ondelete='cascade') I want to create a method in account.payment.term that creates automatically the payment term lines. This method should determine the number of slices number_of_slices = (self.how_much/self.fixed_amount) which will be the number of payment term lines. I tried this code for now: @api.onchange('fixed_amount') def automate_creation(self): terms = self.line_ids.browse([]) self.number_of_slices = (self.how_much/self.fixed_amount) i = 0 while i&lt;10: terms+=terms.new({'value': 'fixed', 'value_amount':100, 'days':30, 'option':'day_after_invoice_date', 'payment_id':self._origin.id}) i=i+1 This method doesn't seem to work. I don't get my lines in account.payment.term.line.
score: 0

http://stackoverflow.com/comment/84173330
type: Comment
comment on: http://stackoverflow.com/q/48588103
score: 0
has text: The for loop *is* inserting the keys. Why do you think it isn't?
type: QuestionComment

spyder
tags question: http://stackoverflow.com/q/48603866
tag name: spyder
tags question: http://stackoverflow.com/q/48641632
tags question: http://stackoverflow.com/q/48523078
tags question: http://stackoverflow.com/q/48547573
tags question: http://stackoverflow.com/q/48643017
tags question: http://stackoverflow.com/q/48608858
tags question: http://stackoverflow.com/q/48589185
tags question: http://stackoverflow.com/q/48558677
tags question: http://stackoverflow.com/q/48568283
tags question: http://stackoverflow.com/q/48516018
type: Tag
tags question: http://stackoverflow.com/q/48620524
tags question: http://stackoverflow.com/q/48581973
tags question: http://stackoverflow.com/q/48490276
tags question: http://stackoverflow.com/q/48547818
tags question: http://stackoverflow.com/q/48514027
tags question: http://stackoverflow.com/q/48513473

http://stackoverflow.com/a/48552899
has comment: http://stackoverflow.com/comment/84103513
has comment: http://stackoverflow.com/comment/84142667
has comment: http://stackoverflow.com/comment/84143551
accepted answer of: http://stackoverflow.com/q/48552860
has body: It looks like the url for 'givethanks' doesn't take any kwargs. The view function does, but the url pattern itself doesn't have a placeholder for 'thanks_for'. You may want to modify it to path('thankyou/&lt;thanks_for&gt;/', views.ThankYou, name="givethanks"), or something of the like. Then your view can be: def ThankYou(request, **kwargs): print(kwargs['thanks_for'])
has comment: http://stackoverflow.com/comment/84149318
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48552860
has comment: http://stackoverflow.com/comment/84142484
has comment: http://stackoverflow.com/comment/84142275
type: Answer

http://stackoverflow.com/comment/84182007
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48592259
has text: Sure, I have run
score: 0

http://stackoverflow.com/a/48498975
type: Answer
answers question: http://stackoverflow.com/q/48496073
has body: Why don't you use simple for loop instead of while loop for match in matches: bar = match if match == 'bar' else foo = match print("foo:", foo) print("bar:", bar) You don't have to remove the element from the set every time. Since your set only contains 2 or fewer elements :P. Maybe for larger sets you can delete the entire set after use by del matches # will help in garbage collection. In our case, this is not needed.
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/108329291
has text: @AdamGriffiths. How does the error manifest itself if not a printout?
type: Comment
comment on: http://stackoverflow.com/a/61198797
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84142696
has text: That's the answer i was looking for and thank you so much, plotting everything on 1 axes is what i wanted. How about if we have to add two legends for the plots and plot in lines instead of circles. I tried `p, = ax.plot(data, 'b-')` but it is making all the plots in blue line.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48572768
type: AnswerComment

http://stackoverflow.com/q/48519363
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84042333
has body: Trying to minimize the sigmoid-curve f(x)=1/(1+exp(-x)) (which converges to zero at minus infinity and to one at infinity) with scipy.optimize.minimize(lambda x: 1/(1+np.exp(-x)),100,hess=lambda x:-(np.exp(x)*(np.exp(x)-1))/(np.exp(x)+1)**3,jac = lambda x:1/(np.exp(-x/2)+np.exp(x/2))**2,method = 'Newton-CG') I get the following output: fun: array([ 1.]) jac: array([ 3.72007598e-44]) message: 'Warning: Desired error not necessarily achieved due to precision loss.' nfev: 19 nhev: 1 nit: 0 njev: 7 status: 2 success: False x: array([ 100.]) This means, the algorihtm simply stops where it is and claims the minimum is f(100)=1, when it really is f(-infinity)=0. This answer would be reasonable looking at just the tiny derivative at x=100 (and considering that the minimum can only be found up to a certain error tolerance), but the negative second derivative (hessian) implies that x=100 is not even near a local minimum. How can I avoid the warning message, and how can I force the algorithm to continue until it finds at least a point where hess(x)&gt;0? Note that neither the Jacobian nor the Hessian actually run into numerical stability issues; indeed jac(100)&gt;0 and hess(100)&lt;0, from which the minimizer should be able to conclude that the optimum hasn't been reached yet. PS: This is of course only a toy problem, but I believe it captures the essentials why my real application fails. Also, I'm not set on using Newton-CG, but any method that does not use the second derivative cannot be expected to continue when the jacobian is as small as in the above example, so I do want to use a method that exploits second derivative information I am using Python3.6.3 and scipy0.19.1
answer count: 1
tagged with: scipy
tagged with: minimization
type: Question
has title: scipy.optimize.minimize Newton-CG stops even when second derivative is negative
accepted answer: http://stackoverflow.com/a/48523908
tagged with: python
has answer: http://stackoverflow.com/a/48523908
has comment: http://stackoverflow.com/comment/84039701

http://stackoverflow.com/comment/84101263
score: 0
type: Comment
type: QuestionComment
has text: `collections` is built-in with any Python installation. So, why can't you use it?
comment on: http://stackoverflow.com/q/48552370

http://stackoverflow.com/a/48562426
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48558791
type: Answer
answers question: http://stackoverflow.com/q/48558791
has body: Ah solved it. This is my solution: import pyodbc #conda install -c anaconda pyodbc import pandas as pd import os db_path=os.path.realpath("test01.accdb") conn_str = ( r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};" f"DBQ={db_path};" ) sql_str='''SELECT Table1.* FROM Table1 WHERE Table1.Column01=?''' with pyodbc.connect(conn_str) as conn: df=pd.read_sql(sql_str, conn, params=("CCC",)) print(df.head())

http://stackoverflow.com/comment/84103401
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48553316
has text: Uh... ok... sorry I don't know numpy/scipy/cylp enough to understand whether that's what that value means.

http://stackoverflow.com/comment/115443289
type: AnswerComment
comment on: http://stackoverflow.com/a/48622736
has text: Doesn't GPU only do linear interpolation?
score: 0
type: Comment

http://stackoverflow.com/comment/84249219
type: AnswerComment
comment on: http://stackoverflow.com/a/48626176
score: 0
has text: I don't think from his post that his loop should sleep 20 seconds each iteration, from what he posted it sounds as if it is to wait 20 seconds one time, then wait until temp_x == 0
type: Comment

plot
tags question: http://stackoverflow.com/q/48623332
tags question: http://stackoverflow.com/q/48633654
tags question: http://stackoverflow.com/q/48639369
tags question: http://stackoverflow.com/q/48566181
tags question: http://stackoverflow.com/q/48572562
tags question: http://stackoverflow.com/q/48602330
tags question: http://stackoverflow.com/q/48626567
type: Tag
tags question: http://stackoverflow.com/q/48618992
tags question: http://stackoverflow.com/q/48590354
tags question: http://stackoverflow.com/q/48544925
tags question: http://stackoverflow.com/q/48519327
tags question: http://stackoverflow.com/q/48608453
tags question: http://stackoverflow.com/q/48639028
tags question: http://stackoverflow.com/q/48529905
tags question: http://stackoverflow.com/q/48558679
tag name: plot
tags question: http://stackoverflow.com/q/48566747
tags question: http://stackoverflow.com/q/48511036
tags question: http://stackoverflow.com/q/48550643
tags question: http://stackoverflow.com/q/48542805
tags question: http://stackoverflow.com/q/48579733
tags question: http://stackoverflow.com/q/48594447
tags question: http://stackoverflow.com/q/48640667
tags question: http://stackoverflow.com/q/48615377
tags question: http://stackoverflow.com/q/48609095
tags question: http://stackoverflow.com/q/48525770
tags question: http://stackoverflow.com/q/48645409
tags question: http://stackoverflow.com/q/48613920
tags question: http://stackoverflow.com/q/48627202
tags question: http://stackoverflow.com/q/48530936
tags question: http://stackoverflow.com/q/48630246
tags question: http://stackoverflow.com/q/48636157
tags question: http://stackoverflow.com/q/48629208
tags question: http://stackoverflow.com/q/48588538
tags question: http://stackoverflow.com/q/48610996
tags question: http://stackoverflow.com/q/48626328
tags question: http://stackoverflow.com/q/48613584
tags question: http://stackoverflow.com/q/48604944
tags question: http://stackoverflow.com/q/48594619
tags question: http://stackoverflow.com/q/48570596

http://stackoverflow.com/a/48604445
has body: This is what melt will achieve this df1=df.melt('CODE') df1'New','New2'=df1.variable.str.split('_',expand=True) df1.set_index(['CODE','New2','New']).value.unstack() Out[492]: New END MEANING START CODE New2 AA 1 1990-02-14 SOMETHING 1990-01-01 2 1990-06-14 ELSE 1990-02-15 BB 1 2000-03-01 OR 2000-01-01 2 None None None CC 1 2005-12-31 OTHER 2005-01-01 2 2006-12-31 ANOTHER 2006-01-01
upvote count: 3
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84205516
has comment: http://stackoverflow.com/comment/84205532
answers question: http://stackoverflow.com/q/48603552
type: Answer

recurrent-neural-network
tags question: http://stackoverflow.com/q/48492613
tags question: http://stackoverflow.com/q/48527153
tags question: http://stackoverflow.com/q/48494356
tags question: http://stackoverflow.com/q/48491737
tags question: http://stackoverflow.com/q/48562099
tags question: http://stackoverflow.com/q/48506422
tags question: http://stackoverflow.com/q/48639348
type: Tag
tag name: recurrent-neural-network
tags question: http://stackoverflow.com/q/48628502

http://stackoverflow.com/q/48613669
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84238649
has title: Run Fenics in Maya (Python)
tagged with: docker
tagged with: fenics
has comment: http://stackoverflow.com/comment/84224729
has body: I need to use a script in Maya that uses the Fenics Project libraries. Is there a way to do it? Now I'm using Docker (out of Maya) and import the results in Maya, but I'd want to run the script from Maya itself
score: 0
tagged with: maya
type: Question

http://stackoverflow.com/q/48560955
accepted answer: http://stackoverflow.com/a/48562753
has answer: http://stackoverflow.com/a/48562753
has body: i have a python class Wiresharking.py from subprocess import Popen, CREATE_NEW_CONSOLE,PIPE,STDOUT import time import subprocess import datetime import os #import envSI class Wiresharking: """Wireshark Server subclass""" def __init__(self,**kwargs): self.filters='' self.window_ip = kwargs.get('ip') print type(self.window_ip) self.window_user= kwargs.get('username') self.window_password= kwargs.get('password') self.dest_path= kwargs.get('Target_path') self.interface= kwargs.get('interface') self.terminal='cmd' self.home=kwargs.get('Home_path') def test(self): print 'hi' return self.window_ip i can call it from another python file (env.py) like below SERVER_01 = Wiresharking( name='WIRESHARK_ENV91', ip='192.168.1.16', username=r'INTRA\pmmm', #always prepend r , before giving your username and password password='jan@2018', prompt='$ ', autostart=False, unzip_capture=True, filter='', #interface=['ens2f0'], interface='Ethernet', Target_path=r'D:\Users\pankaj-m\Desktop\Test' ) print SERVER_01.test() output : &lt;type 'str'&gt; hi 192.168.1.16 however , the problem arises when i use env.py file as --variable file with robotframework command pybot -V env.py Check.robot Check.robot file is below *** Settings *** Library Wiresharking.py *** Test Cases *** Test check *** Keywords *** check ${abc} = test log ${abc} the output i here getting is 'None' 16:13:37.279 INFO None can anyone point out what wrong i am doing here.
has answer: http://stackoverflow.com/a/48577900
type: AnsweredQuestion
tagged with: robotframework
tagged with: python
has title: Robotframework treats variables passed from python class as 'None'
possible better answer: http://stackoverflow.com/a/48577900
type: Question
score: 0
answer count: 2

http://stackoverflow.com/comment/84285427
type: QuestionComment
comment on: http://stackoverflow.com/q/48644272
has text: What do you mean by "then back" ? 256 numbers can't represent faithfully 500 numbers.
score: 3
type: Comment

http://stackoverflow.com/comment/84204331
has text: Removing an element while enumerating a collection will interfere with the enumeration.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48603827
type: Comment

http://stackoverflow.com/a/48652507
score: 0
answers question: http://stackoverflow.com/q/48628521
type: Answer
has body: It turned out that my refactoring had caused a problem, once I realized that, I deleted the newly created db and the migrations folder and reran: python manage.py db init python manage.py db migrate This worked , creating a new db and migrations for all the tables were created.

http://stackoverflow.com/comment/83981711
type: Comment
type: QuestionComment
score: 0
has text: In your code, when form is invalid, you pass `context_dict` which is not defined yet. Is that the code you are using?
comment on: http://stackoverflow.com/q/48492914

http://stackoverflow.com/a/48585093
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48584949
has body: Try to install the package with pip3 (sudo pip3 install pytube), in some operating systems pip refers to python2 and pip3 refers to python3.
answers question: http://stackoverflow.com/q/48584949
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84217793
type: Comment
type: QuestionComment
has text: Ionnis, thanks for the reply. First, it is all intended to be done by an algorithm (as opposed by h and). Second, the dual can be found from the information given (without me having to define a second problem myself). Third, if I had to type in two problems, I might as well find another method (other than Pulp) that will let me directly translate the formulae and constraint to the matrix variables (C, X, A, B, etc.). That would defeat the purpose of using the library. Post-optimality analysis is a crucial piece of the puzzle.
comment on: http://stackoverflow.com/q/48606094
score: 0

http://stackoverflow.com/a/48610834
downvote count: 0
has comment: http://stackoverflow.com/comment/84223353
has body: You can simply eval these expressions as they are valid Python &gt;&gt;&gt; eval("(True &amp; False) | True") True &gt;&gt;&gt; eval("((False | False) &amp; (True | False)) &amp; (False | True)") False
score: 3
has comment: http://stackoverflow.com/comment/84220419
has comment: http://stackoverflow.com/comment/84220257
answers question: http://stackoverflow.com/q/48610818
type: Answer
accepted answer of: http://stackoverflow.com/q/48610818
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/123457047
type: AnswerComment
has text: What is the PPI of 72 based on? Can this be changed?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48643217

http://stackoverflow.com/q/48615190
tagged with: regex
has comment: http://stackoverflow.com/comment/84227503
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84227915
score: 1
answer count: 1
downvote count: 0
has body: As the title, I'm supposed to get some sub-strings from a string which looks like this: "-23/45 + 14/9". What I need to get from that string is the four numbers and the operator in the middle. What has confused me is that how to use only one regular expression pattern to do this. Below is the requirement: Write a regular expression patt that can be used to extract (numerator,denominator,operator,numerator,denominator) from a string containing a fraction, an arithmetic operator, and a fraction. You may assume there is a space before and after the arithmetic operator and no spaces surrounding the / character in a fraction. And all fractions will have a numerator and denominator. Example: &gt;&gt;&gt; s = "-23/45 + 14/9" &gt;&gt;&gt; re.findall(patt,s) [( "-23","45","+","14","49")] &gt;&gt;&gt; s = "-23/45 * 14/9" &gt;&gt;&gt; re.findall(patt,s) [( "-23","45","*","14","49")] In general, your code should handle any of the operators +, -, * and /. Note: the operator module for the two argument function equivalents of the arithmetic (and other) operators My problem here is that how to use only one regular expression to do this. I have thought about getting the sub strings contain numbers and stop at any character which is not a number, but this will miss the operator in the middle. Another idea is to include all the operators( + - * /) and stop at white space, but this will make first and last two numbers become together. Can anybody give me a direction how to solve this problem with only one regular expression pattern? Thanks a lot!
upvote count: 1
favorite count: 0
type: Question
has title: How to extract different types of sub-strings from a string in python using regular expression?
accepted answer: http://stackoverflow.com/a/48615587
has answer: http://stackoverflow.com/a/48615587
tagged with: python

http://stackoverflow.com/a/48568915
upvote count: 5
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48568283
has comment: http://stackoverflow.com/comment/84134733
answers question: http://stackoverflow.com/q/48568283
has comment: http://stackoverflow.com/comment/84134696
has body: The Problem: When trying to resolve a variable reference, Python first checks in the local scope and then in the local scope of any enclosing functions. For example this code: def foo(): x=23 def bar(): return x +1 return bar print(foo()()) Will run and print out 24 because when x is referenced inside of bar, since there is no x in the local scope it finds it in the scope of the enclosing function (foo). However, as soon as you try to assign to a variable, Python assumes it is defined in the local scope. So this: def foo(): x=23 def bar(): x = x + 1 return x return bar print(foo()()) Will throw an UnboundLocalError because I am trying to assign to x which means it is going to be looked up in the local scope, but the value I'm trying to assign to it is based on the x from the enclosing scope. Since the assignment limits the search for x to the local scope, it can't be found and I get the error. So your error is coming up because of the testerNum -= 1 line in your else clause, it is limiting the search for testerNum to the local scope where it doesn't exist. The Fix: The global declaration isn't right since, as you noted, testerNum isn't defined in the global scope. I'm not familiar with Spyder and don't know why it worked there but it seems like it somehow got a testerNum variable in its global scope. If you're using Python3 you can get around this by changing your global testerNum line to nonlocal testerNum which just tells Python that, despite being assigned to, testerNum isn't defined in the local scope and to keep searching outwards. def foo(): x=23 def bar(): nonlocal x x = x + 1 return x return bar &gt;&gt;&gt; print(foo()()) 24 Another option that would work in Python 2 or 3 is to pass around testerNum as Brambor outlined in their answer.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84135453
has comment: http://stackoverflow.com/comment/84135257
has comment: http://stackoverflow.com/comment/84134758

http://stackoverflow.com/q/48554577
tagged with: python
tagged with: hyperparameters
favorite count: 0
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Hyperparameter tuning Random Forest Classifier with GridSearchCV based on probability
has comment: http://stackoverflow.com/comment/84105757
has comment: http://stackoverflow.com/comment/103301659
has comment: http://stackoverflow.com/comment/84105871
has comment: http://stackoverflow.com/comment/84105632
has answer: http://stackoverflow.com/a/58513885
accepted answer: http://stackoverflow.com/a/58513885
has comment: http://stackoverflow.com/comment/84137319
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/103354897
has body: Just starting in on hyperparameter tuning for a Random Forest binary classification, and I was wondering if anyone knew/could advise on how to set the scoring to be based off predicted probabilities rather than the predicted classification. Ideally I'd want something that would consider for roc_auc in the below the probabilities (i.e. [0.2,0.6,0.7,0.1,0.0]) rather than classifications (i.e. [0,1,1,0,0]). from sklearn.metrics import roc_auc_score from sklearn.ensemble import RandomForestClassifier as rfc from sklearn.grid_search import GridSearchCV rfbase = rfc(n_jobs = 3, max_features = 'auto', n_estimators = 100, bootstrap=False) param_grid = { 'n_estimators': [200,500], 'max_features': [.5,.7], 'bootstrap': [False, True], 'max_depth':[3,6] } rf_fit = GridSearchCV(estimator=rfbase, param_grid=param_grid , scoring = 'roc_auc') I figure currently the roc_auc is going off the actual classifications . Wanted to check if there was a more efficient way before I charged off into creating a custom scoring function, thanks in advance for the help here!
tagged with: random-forest
has comment: http://stackoverflow.com/comment/103312800
answer count: 1

http://stackoverflow.com/comment/84101487
type: QuestionComment
has text: I figured it out, i didn't understand how sys.path worked, now i know that what i wanted to do was useless
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48546018

http://stackoverflow.com/comment/84126028
type: AnswerComment
has text: I didn't downvote your answer. Also, I didn't know who downvote my Question. No one asked me to explain my question. My question here is that how to shorten my code in the if statement, I don't want to do it 200 times.
comment on: http://stackoverflow.com/a/48555005
type: Comment
score: 0

http://stackoverflow.com/a/48630616
has body: Here is my solution which uses recursion: import re def text2dict(text): def f(ls, i): d = {} while i &lt; len(ls): if ls[i]=="}": return d, i m = re.match(r"(.*)=(.*)", ls[i]) k = m.group(1).strip() v = m.group(2).strip() if not len(v): v, i = f(ls, i+2) d[k] = v i += 1 return d return f([l.strip() for l in text.split("\n")], 0) with open("file.txt") as f: text = f.read() print(text2dict(text))
upvote count: 1
answers question: http://stackoverflow.com/q/48628213
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/48558007
has answer: http://stackoverflow.com/a/68141511
type: Question
score: 12
has answer: http://stackoverflow.com/a/66797709
has body: When I wrote this code in google colab: import pickle x=10; output = open('data.pkl', 'wb') pickle.dump(x,output) x is saved and also in another window in Google Colab I can access this file and read it but I don't know where is the file. Does anybody know where is it?
upvote count: 12
downvote count: 0
answer count: 7
tagged with: file
possible better answer: http://stackoverflow.com/a/48571146
accepted answer: http://stackoverflow.com/a/48682646
favorite count: 0
has answer: http://stackoverflow.com/a/48682646
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/71828871
has answer: http://stackoverflow.com/a/66494946
has answer: http://stackoverflow.com/a/63622997
has title: Where is dumped file in Google Colab?
tagged with: python
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/48571146

timer
tag name: timer
tags question: http://stackoverflow.com/q/48495288
type: Tag

http://stackoverflow.com/comment/84196269
comment on: http://stackoverflow.com/a/48599842
score: 1
type: Comment
type: AnswerComment
has text: though still it has `i` unlike the OPs desired result (+1 as it is the closest result achievable I guess)

http://stackoverflow.com/q/48540589
has title: sigmoid RuntimeWarning: overflow encountered in exp
has comment: http://stackoverflow.com/comment/84076951
has comment: http://stackoverflow.com/comment/84076545
linked to: http://stackoverflow.com/q/21106134
has answer: http://stackoverflow.com/a/48541786
tagged with: python-2.7
has body: I'm trying to create a sigmoid function in Python, however, I get the following error: RuntimeWarning: overflow encountered in exp Here my code: def sigmoid(self, value): a = np.exp(-value) return 1.0/ (1.0 + a) I searched for previous answers, but they didn't solve my problem. The problem is on calculating the value of a. I also tried using: a = np.float128(np.exp(-value)) but I got the same error, and using: a = np.float256(np.exp(-value)) I got the following error: AttributeError: 'module' object has no attribute 'float256' I thought that if I have an overflow I could return 0, and if I have an underflow I could return 1
downvote count: 0
upvote count: 7
score: 7
answer count: 1
tagged with: python
tagged with: floating-point
favorite count: 0
has comment: http://stackoverflow.com/comment/84078840
type: Question
tagged with: numpy
type: UnansweredQuestion

http://stackoverflow.com/comment/84016136
type: QuestionComment
has text: but theology is a single word, it's not treating the word 'the' as three different characters, it's treating it as a single string
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48509914

http://stackoverflow.com/comment/84063152
comment on: http://stackoverflow.com/q/48530293
type: Comment
score: 0
type: QuestionComment
has text: How do you define and use checkAuthenticationInProgress? More detail on the code fragment will surely prove useful.

http://stackoverflow.com/a/48501948
type: AcceptedAnswer
score: 1
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/48501832
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48501832
has body: If the question is actually on deployment model, I suggest to take a look at django docs on deployment. Depending on load, uWSGI/Gunicorn [+ nginx] will be good choice. Independent of tools you use, no need to leave running terminal on your server. There's a lot of tools to "daemonize" processes. Simplest would be supervisor

http://stackoverflow.com/q/48588490
has body: So I have a challenge I'm working on - find the longest string of alphabetical characters in a string. For example, "abcghiijkyxz" should result in "ghiijk" (Yes the i is doubled). I've been doing quite a bit with loops to solve the problem - iterating over the entire string, then for each character, starting a second loop using lower and ord. No help needed writing that loop. However, it was suggested to me that Regex would be great for this sort of thing. My regex is weak (I know how to grab a static set, my look-forwards knowledge extends to knowing they exist). How would I write a Regex to look forward, and check future characters for being next in alphabetical order? Or is the suggestion to use Regex not practical for this type of thing? Edit: The general consensus seems to be that Regex is indeed terrible for this type of thing.
score: 12
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84174241
has comment: http://stackoverflow.com/comment/84174232
has answer: http://stackoverflow.com/a/48591004
accepted answer: http://stackoverflow.com/a/48589051
has answer: http://stackoverflow.com/a/48589051
downvote count: 0
has comment: http://stackoverflow.com/comment/84175008
has answer: http://stackoverflow.com/a/48602113
possible better answer: http://stackoverflow.com/a/48589029
has comment: http://stackoverflow.com/comment/84174951
favorite count: 0
has comment: http://stackoverflow.com/comment/84175085
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48589029
has answer: http://stackoverflow.com/a/48970690
upvote count: 12
has answer: http://stackoverflow.com/a/48594508
tagged with: python
answer count: 6
tagged with: regex
has title: How can I use Regex to find a string of characters in alphabetical order using Python?

http://stackoverflow.com/comment/84192921
has text: If you are certain of what you're looking for, you could always use `df.index()`, then `split()` the array position it returns. Furthermore, if you're worried about calling type on an int, you could check its type, or encapsulate the split operation in a try-except statement.
comment on: http://stackoverflow.com/a/48597885
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48623615
has comment: http://stackoverflow.com/comment/84246330
tagged with: http://stackoverflow.com/tag/json
has body: Task: Convert Google Vision API response to JSON Problem: The return value from the API call is not in a JSON format Python Function def detect_logos(path): """Detects logos in the file.""" client = vision.ImageAnnotatorClient() # [START migration_logo_detection] with io.open(path, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) response = client.logo_detection(image=image) logos = response.logo_annotations print('Logos:') print(logos) print(type(logos)) Google online JSON "logoAnnotations": [ { "mid": "/m/02wwnh", "description": "Maxwell House", "score": 0.41142157, "boundingPoly": { "vertices": [ { "x": 74, "y": 129 }, { "x": 161, "y": 129 }, { "x": 161, "y": 180 }, { "x": 74, "y": 180 } ] } } Google Response (List) [mid: "/m/02wwnh" description: "Maxwell House" score: 0.4114215672016144 bounding_poly { vertices { x: 74 y: 129 } vertices { x: 161 y: 129 } vertices { x: 161 y: 180 } vertices { x: 74 y: 180 } } ] Type: google.protobuf.internal.containers.RepeatedCompositeFieldContainer Tried: Protobuf to json in python
possible better answer: http://stackoverflow.com/a/65728068
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84269129
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65728068
score: 9
tagged with: google-api
linked to: http://stackoverflow.com/q/19734617
accepted answer: http://stackoverflow.com/a/48636894
linked to: http://stackoverflow.com/q/64403737
tagged with: python
has title: Convert Google Vision API response to JSON
has comment: http://stackoverflow.com/comment/84245348
has answer: http://stackoverflow.com/a/48636894
has comment: http://stackoverflow.com/comment/84245404
upvote count: 10
has answer: http://stackoverflow.com/a/48781812
linked to: http://stackoverflow.com/q/15178105
answer count: 3

http://stackoverflow.com/comment/84136813
has text: Fair enough, I retracted the vote.
type: QuestionComment
comment on: http://stackoverflow.com/q/48569731
type: Comment
score: 0

http://stackoverflow.com/q/48518055
has title: Cross-compile extension on Linux for Windows
has body: I've managed to build some DLLs on Linux that are necessary for my Python extension using MinGW. Something along these lines: from setuptools.command.build_py import build_py class BuildGo(build_py): def run(self): if # need to build windows binaries self.build_win() build_py.run(self) def build_win(self): if # compilers and toolchain available try: # builds extra libraries necessary for this extension except subprocess.CalledProcessError as e: print(e.stderr) raise try: result = subprocess.check_output([ 'x86_64-w64-mingw32-gcc-win32', '-shared', '-pthread', '-o', EXTRA_DLL, FAKE_WIN_BINDINGS, ARCHIVE_GENERATED_IN_PREVIOUS_STEP, '-lwinmm', '-lntdll', '-lws2_32', ]) print(result) except subprocess.CalledProcessError as e: print(e.stderr) raise I was now hoping I could avoid extending build_ext in the same painful way to get it to cross-compile Cython code for Windows... I looked into the abyss of "elegant interplay of setuptools, distutils and cython", and before the abyss has a chance to look back into me... Isn't there a way to just specify some flag... like a name of compiler and Python binary for desired platform and... it would just do it? I've read this article: http://whatschrisdoing.com/blog/2009/10/16/cross-compiling-python-extensions/ - it's almost 10 years old. And it just made me want to cry... did anything change since it was written? Or are these steps more or less what I'll have to do to compile for the platform other than the one I'm running on? Or, is there an example project on the web which does it? Goal My ultimate goal is to produce an egg package which will contain both PE and ELF binaries in it and will install them in the correct location on either platform when installed by pip or pipenv. It should compile on Linux (compiling it on MS Windows isn't necessary).
upvote count: 6
linked to: http://stackoverflow.com/q/32361119
has answer: http://stackoverflow.com/a/48528339
has comment: http://stackoverflow.com/comment/84119051
answer count: 4
has comment: http://stackoverflow.com/comment/84040024
linked to: http://stackoverflow.com/q/70654722
linked to: http://stackoverflow.com/q/62390978
has comment: http://stackoverflow.com/comment/84118817
tagged with: cross-compiling
downvote count: 0
has comment: http://stackoverflow.com/comment/84067852
linked to: http://stackoverflow.com/q/11480430
has comment: http://stackoverflow.com/comment/84033350
has comment: http://stackoverflow.com/comment/84047933
linked to: http://stackoverflow.com/q/43311621
tagged with: python
has answer: http://stackoverflow.com/a/70474888
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/45479617
score: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/84070457
linked to: http://stackoverflow.com/q/58324230
type: Question
has answer: http://stackoverflow.com/a/52142063
has comment: http://stackoverflow.com/comment/84071019
has comment: http://stackoverflow.com/comment/84117308
has answer: http://stackoverflow.com/a/52141964
tagged with: cython

pycharm
tags question: http://stackoverflow.com/q/48593824
tags question: http://stackoverflow.com/q/48549938
tags question: http://stackoverflow.com/q/48614151
tags question: http://stackoverflow.com/q/48579140
tags question: http://stackoverflow.com/q/48572166
tags question: http://stackoverflow.com/q/48606131
tags question: http://stackoverflow.com/q/48569315
tags question: http://stackoverflow.com/q/48578512
tags question: http://stackoverflow.com/q/48610659
tags question: http://stackoverflow.com/q/48627632
tag name: pycharm
tags question: http://stackoverflow.com/q/48504563
tags question: http://stackoverflow.com/q/48532248
tags question: http://stackoverflow.com/q/48535847
type: Tag
tags question: http://stackoverflow.com/q/48597756
tags question: http://stackoverflow.com/q/48513575
tags question: http://stackoverflow.com/q/48502380
tags question: http://stackoverflow.com/q/48637431
tags question: http://stackoverflow.com/q/48554990
tags question: http://stackoverflow.com/q/48636840
tags question: http://stackoverflow.com/q/48535479
tags question: http://stackoverflow.com/q/48619709
tags question: http://stackoverflow.com/q/48545725
tags question: http://stackoverflow.com/q/48533269
tags question: http://stackoverflow.com/q/48573443
tags question: http://stackoverflow.com/q/48554693
tags question: http://stackoverflow.com/q/48522997

http://stackoverflow.com/a/48571899
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48533216
has body: The class Deconv3D has to match Keras 2 architecture. class Deconvolution3D(Layer): def __init__(self, nb_filter, kernel_dims, output_shape, subsample, **kwargs): self.nb_filter = nb_filter self.kernel_dims = kernel_dims self.strides = (1, ) + subsample + (1, ) self.output_shape_ = output_shape assert K.backend() == 'tensorflow' super(Deconvolution3D, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 5 self.W = self.add_weight(shape=self.kernel_dims + (self.nb_filter, input_shape[4], ), initializer='glorot_uniform', name='{}_W'.format(self.name), trainable=True) self.b = self.add_weight(shape=(1, 1, 1, self.nb_filter,), initializer='zero', name='{}_b'.format(self.name), trainable=True) super(Deconvolution3D, self).build(input_shape) def call(self, x, mask=None): return tf.nn.conv3d_transpose(x, self.W, output_shape=self.output_shape_, strides=self.strides, padding='SAME', name=self.name) + self.b def compute_output_shape(self, input_shape): return (input_shape[0], ) + self.output_shape_[1:]
accepted answer of: http://stackoverflow.com/q/48533216

http://stackoverflow.com/comment/84019133
score: 2
has text: If the value of a byte in the buffer corresponds to a printable character, Python shows it as that character when printing the buffer as a string. If the value does not match a printable character, Python shows the byte as two hex digits after a `\x` prefix. So your `\x00o` represents a byte with value zero followed by a byte whose value is the value of the character 'o'. The numeric value of that byte is `ord('o')` which is 111 decimal, 6f hexadecimal.
comment on: http://stackoverflow.com/q/48508018
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83976411
has text: thanks @WillemVanOnsem but can i pass a query string to it? if not and I should parse the query string before passing to the `df.query(..)` do you have any idea on how to do it?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48491525

http://stackoverflow.com/comment/83998427
type: Comment
comment on: http://stackoverflow.com/a/48502524
has text: Ok, I was expecting something like this, Thanks jez
type: AnswerComment
score: 1

http://stackoverflow.com/q/48533058
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84061866
has comment: http://stackoverflow.com/comment/84061727
has comment: http://stackoverflow.com/comment/84061840
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84061929
has title: TypeError: 'NoneType' object is not iterable in python function
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84061859
score: -2
tagged with: counter
has comment: http://stackoverflow.com/comment/84061861
tagged with: dataframe
tagged with: python
has body: I have written the following codes: def summarize_withoutStations(path, month): calculate_withoutStations(getFiles(path, month)) def calculate_stations (allFiles): result = pd.DataFrame(columns = ['Date','Mid Ebb Total','Mid Flood Total','Mid Ebb Control','Mid Flood Control']) Mid_Ebb_unique_stations = [] Mid_Flood_unique_stations = [] for file_ in allFiles: print('Checking' +str(file_)) xls = pd.ExcelFile(file_) df = xls.parse('General Impact') if len(df) &gt; 300: print('Please check if there are more than one month data in the excel') cont = input('Please type Y to continue, N to exit') if cont == 'Y': continue if cont == 'N': break Mid_Ebb = df[df['Tidal Mode'] == "Mid-Ebb"] #filter Mid_Flood = df[df['Tidal Mode'] == "Mid-Flood"] #filter Mid_Ebb_stations = Mid_Ebb['Station'].unique() Mid_Flood_stations = Mid_Flood['Station'].unique() Mid_Ebb_unique_stations.extend(list(Mid_Ebb_stations)) Mid_Flood_unique_stations.extend(list(Mid_Flood_stations)) Ebb_list = Counter(Mid_Ebb_unique_stations) Flood_list = Counter(Mid_Flood_unique_stations) total_Mid_Ebb = sum(Ebb_list.values()) total_Mid_Flood = sum(Flood_list.values()) print('Ebb tide list: ' + str(Ebb_list)) print('Flood tide list:' + str(Flood_list)) print('Ebb tide total: {} Flood totaltide: {}'.format(total_Mid_Ebb, total_Mid_Flood)) df_Ebb_list = pd.DataFrame.from_dict(Ebb_list, orient='index') df_Flood_list = pd.DataFrame.from_dict(Flood_list, orient='index') print(df_Ebb_list) print(df_Flood_list) return df_Ebb_list, df_Flood_list when I call a,b = func.summarize_withStations(path, month), it gives TypeError: 'NoneType' object is not iterable. Dataframes are not printed too.
has answer: http://stackoverflow.com/a/48533221
has comment: http://stackoverflow.com/comment/84061902

http://stackoverflow.com/q/48574003
type: Question
has answer: http://stackoverflow.com/a/48574289
has body: I have a dictionary where the keys are dates formatted '%m/%d/%y' and I want to parse this apart so I can graph the values by month. So the objective is just to transform the keys from m/d/y to just m and keep the same values in the dictionary. months = dict.keys() for i in months: i = dt.datetime.strptime(i[months],'%m/%d/%y').month I get this error: TypeError: string indices must be integers Thanks for any suggestions.
type: AnsweredQuestion
score: 0
tagged with: datetime
has comment: http://stackoverflow.com/comment/84144874
has comment: http://stackoverflow.com/comment/84145165
has comment: http://stackoverflow.com/comment/84144998
has comment: http://stackoverflow.com/comment/84145025
has comment: http://stackoverflow.com/comment/84145046
has title: Convert dictionary keys from dates to months using datetime
has comment: http://stackoverflow.com/comment/84145001
answer count: 2
has comment: http://stackoverflow.com/comment/84145026
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/48574262
linked to: http://stackoverflow.com/q/3489071
accepted answer: http://stackoverflow.com/a/48574289
has answer: http://stackoverflow.com/a/48574262

http://stackoverflow.com/a/48501854
type: Answer
score: 4
upvote count: 4
has body: Relying on memory location - which is not garanteed to be monotonic (the Python runtime handles it's own memory pool and quite often reuses already allocated memory) - is certainly not going to work in a reliable way (it can seem to work sometimes - specially in a quick test script - but you can consider this as an accident). A simpler solution (assuming your property objects are hashable) would be to use a collections.OrderedDict with dummy values: from collections import OrderedDict PROPERTIES = list(OrderedDict(n.properties, None) for n in NETWORKS)) This solution is garanteed to work.
downvote count: 0
answers question: http://stackoverflow.com/q/48500764

http://stackoverflow.com/comment/84250236
score: 0
comment on: http://stackoverflow.com/a/48625043
type: Comment
type: AnswerComment
has text: which is a distribution, that just means that the network is sure its the first one. There are other functions like "log-softmax" which give less confident probabilities as output but i think softmax si the only one provided by keras

http://stackoverflow.com/comment/84007667
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48505255
type: Comment
has text: First of all, if it's so many lightyears away from correct, then why does it work? Second, it's not that I don't want to hear your advice, it's just that you've given literally no justification for what you're saying. Actually explain why it's so morally reprehensible to refer to globals in classes and maybe you won't sound so ridiculous to me. Third, it was you who called it unpythonic, not me.

http://stackoverflow.com/a/48554119
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48552474
downvote count: 0
type: Answer
has body: Thanks to @Jerdog, I've constructed the required piece of code: import json import requests # testing user password database: testingUsers = { 'testingUser2@funnymail.com': 'BuQ3tUS3 :jbFAL', 'testingUser3w@funnymail.com': 'y(1726854(b(-KY' } def getUserToken(userName): # client id and secret come from LogIn (Test Client)! which has password enabled under "Client &gt; Advanced &gt; Grant Types &gt; Tick Password" url = 'https://YOUR_AUTH0_DOMAIN/oauth/token' headers = {'content-type': 'application/json'} password = testingUsers[userName] parameter = { "client_id":"Jfjrl12w55uqcJswWmMhSm5IG2Qov8w2e", "client_secret": "3E5ZnqLFbPUppBLQiGDjB0H2GtXaLyaD26sdk2HmHrBXQaDYE453UCUoUHmt5nWWh", "audience": 'AUTH0_AUDIENCE', "grant_type": "password", "username": userName, "password": password, "scope": "openid" } # do the equivalent of a CURL request from https://auth0.com/docs/quickstart/backend/python/02-using#obtaining-an-access-token-for-testing responseDICT = json.loads(requests.post(url, json=parameter, headers=headers).text) return responseDICT['access_token'] @memoize # memoize code from: https://stackoverflow.com/a/815160 def getUserTokenHeaders(userName='testingUser2@funnymail.com'): return { 'authorization': "Bearer " + getUserToken(userName)} The @memoize decorator is to avoid multiple calls to get a token over many tests. The tenant has to have a default database specified for the above call to work (see this answer). It was a bit cryptic as to what the database name was supposed to be (the default_directory), but for me, with only Auth0 users, the database was Username-Password-Authentication, which seems to be the default for new accounts.

http://stackoverflow.com/a/48601493
score: 2
accepted answer of: http://stackoverflow.com/q/48601420
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48601420
has body: sklearn.preprocessing.normalize scales each sample vector to unit norm. (The default axis is 1, not 0.) Here's proof of that: from sklearn.preprocessing import normalize np.random.seed(444) data = np.random.normal(loc=5, scale=2, size=(15, 2)) np.linalg.norm(normalize(data), axis=1) # array([ 1., 1., 1., 1., 1., 1., ... It sounds like you're looking for sklearn.preprocessing.scale to scale each feature vector to ~N(0, 1). from sklearn.preprocessing import scale # Are the scaled column-wise means approx. 0.? np.allclose(scale(data).mean(axis=0), 0.) # True # Are the scaled column-wise stdevs. approx. 1.? np.allclose(scale(data).std(axis=0), 1.) # True
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/48591451
downvote count: 0
accepted answer: http://stackoverflow.com/a/48591649
has answer: http://stackoverflow.com/a/48591649
favorite count: 0
type: Question
score: 9
upvote count: 9
has answer: http://stackoverflow.com/a/48592009
tagged with: python
has body: I have a large numpy file saved to disk, I would like to determine the shape without reading in the entire file. I can get the shape using np.load(filename), but when I try the same using np.memmap appears to require that I know the shape in advance, otherwise it defaults to reading the file in a flat array of uint8 values. Is this possible to do?
has title: Can I get the shape of a numpy save file without reading the entire contents (e.g. memmap)
tagged with: numpy
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/48592009

home-automation
tag name: home-automation
type: Tag
tags question: http://stackoverflow.com/q/48610634

http://stackoverflow.com/q/48526580
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84050297
tagged with: pickle
tagged with: python
has body: I have a command to load data from a npy file: utable = numpy.load('utable.npy') But this results in EOFError: File "/home/divyat/anaconda2/lib/python2.7/site-packages/numpy/lib/npyio.py", line 419, in load pickle_kwargs=pickle_kwargs) File "/home/divyat/anaconda2/lib/python2.7/site-packages/numpy/lib/format.py", line 640, in read_array array = pickle.load(fp, **pickle_kwargs) EOFError I don't understand the error. What is happening exactly? The numpy.load() method calls a pickle.load() function, which causes error. The file utable.npy is a file used for generating text embeddings using skipthoughts. I downloaded the files from here: https://github.com/ryankiros/skip-thoughts#getting-started
score: 2
has title: EOFError using numpy.load()
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48526709
upvote count: 2
has comment: http://stackoverflow.com/comment/84048834
has comment: http://stackoverflow.com/comment/92466559
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/84283035
score: 0
comment on: http://stackoverflow.com/a/48622174
type: Comment
has text: I can't have a table with only one relationship.I need to have a primary key column and columns with foreign keys too.
type: AnswerComment

http://stackoverflow.com/a/76858783
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48637178
has body: The other answers suggest one of the following: creating the range in the view, then passing it into the template context creating a custom template filter (or tag) that returns the range iterating over a fixed-length string However, we could also emulate range() directly in the template by iterating over a variable-length string, using one of the built-in template filters, viz. ljust, rjust, or center: {% for _ in ''|ljust:number %} {{ forloop.counter }} {% endfor %} This iterates over a dummy string of length number. The actual loop index, i.e. the OP's i, can be obtained using forloop.counter or forloop.counter0. For start indices other than 1 or 0, you can use an if condition inside the loop. EDIT: It turns out there already are lots of similar solutions here: Numeric for loop in Django templates
type: Answer

http://stackoverflow.com/q/48505597
tagged with: python
has body: I am trying to index to elasticsearch using a python 2.7 script as follows: from __future__ import print_function import urllib, urllib2 #FORMDATA is a json format string that has been taken from a file ELASTIC_URL = 'http://1.2.3.9:9200/indexname/entry/ req = urllib2.Request(ELASTIC_URL) req.add_header('contentType', 'application/x-www-form-urlencoded') response = urllib2.urlopen(req, FORMDATA, timeout=4).read() print(response) I keep getting the error HTTP Error 406: Not Acceptable: HTTPError i have also tried formatting the data with urllib.quote(FORMDATA) and get the same error. The data is not a dictionary it is a string that when converted to json is multi dimensional. I think this is something to do with the fact the req header needs to specify the contentType to be the correct format but i'm struggling to workout what this is. I managed to do this import on elasticsearch 5.x but now on 3.x it doesn't seem to be working. Any ideas??
accepted answer: http://stackoverflow.com/a/48505794
type: AnsweredQuestion
upvote count: 1
answer count: 1
downvote count: 0
has title: Indexing to elasticsearch 6.1 with python script
has answer: http://stackoverflow.com/a/48505794
favorite count: 0
type: Question
score: 1
tagged with: elasticsearch

http://stackoverflow.com/a/48567447
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84131790
has comment: http://stackoverflow.com/comment/84132037
upvote count: 1
has comment: http://stackoverflow.com/comment/84132681
has comment: http://stackoverflow.com/comment/84132346
has comment: http://stackoverflow.com/comment/84131676
has comment: http://stackoverflow.com/comment/84132788
has comment: http://stackoverflow.com/comment/84131562
score: 1
has comment: http://stackoverflow.com/comment/84131716
has comment: http://stackoverflow.com/comment/84132603
has comment: http://stackoverflow.com/comment/84133568
has comment: http://stackoverflow.com/comment/84131496
has body: div.find('a')['story-title'] won't give you the story title, since the &lt;a&gt; tag doesn't have that attribute. That's the reason you're getting KeyError. Use .text for the &lt;a&gt; tag as the title is located here: &lt;a&gt; ... &lt;/a&gt;. for h2 in cric_info_items: cricinfo_article_dict[h2.find('a').text] = h2.find('a')['href'] for item in cricinfo_article_dict.items(): print(item) Output: ('Bell-Drummond leads MCC in curtain-raiser', '/ci/content/story/1135157.html') ('Scotland pick Brad Wheal, Chris Sole for World Cup qualifiers', '/scotland/content/story/1135152.html') ('Newlands working to be water independent', '/southafrica/content/story/1135120.html') ('Scorchers bow out after Hurricanes pile up 210', '/australia/content/story/1135117.html') ("'Strong evidence' of corruption in Ajman All Stars League - ICC ", '/ci/content/story/1135108.html') ('Du Plessis 120 powers South Africa to 269', '/south-africa-v-india-2018/content/story/1135099.html') ("Plan is to expose India's middle, lower order - Harris", '/australia/content/story/1135091.html') ('Top order, King fire Scorchers into WBBL final', '/australia/content/story/1135084.html') ('Technical change brings prolific run for Mominul', '/bangladesh/content/story/1135077.html') ('Dhananjaya, Mendis lead strong Sri Lanka reply', '/bangladesh/content/story/1135075.html') Also, calling the same method (here, h2.find('a')) multiple times is not a good idea as it will take more time. In this case, it won't show any difference in run time as the &lt;h2&gt; tag has only one child - &lt;a&gt;. But in other cases where the parent has many children, it is a good idea to save the tag you find in a variable and then use it. Something like this: a = h2.find('a') cricinfo_article_dict[a.text] = a['href'] EDIT: To get the title, link, and the image link, you can create a list of dictionaries for individual news items with title, link, image as its items. Try this: cricinfo_article_list = [] for item in cric_info_items: i…
answers question: http://stackoverflow.com/q/48567205
has comment: http://stackoverflow.com/comment/84132130

http://stackoverflow.com/q/48561819
tagged with: session-cookies
tagged with: python-requests
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/48562334
has answer: http://stackoverflow.com/a/48562334
tagged with: python
has title: Scrapy - Pass session on to requests
type: AnsweredQuestion
has body: Got this code: from scrapy.http import Request, FormRequest from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from scrapy.selector import HtmlXPathSelector from scrapy.http import FormRequest from retrieve_image import retrieve_image class LoginSpider(CrawlSpider): name = 'loginspider' login_page = 'http://145.100.108.148/login5/login.php' start_urls = ['http://145.100.108.148/login5/index.php'] username = 'test@hotmail.com' password = 'test' def init_request(self): return Request(url=self.login_page, callback=self.start_requests) def start_requests(self): print ("\n start_request is here \n") yield Request( url = self.login_page, callback = self.login, cookies={'PHPSESSID': 'something'}, dont_filter = True ) def login(self, response): captcha = execute.split('\n')[0] print(captcha) print ("\n Login is here! \n") retrieve_image(response, self.login_page) On this page there is a captcha image which is tied to a session. I am trying to download the CAPTCHA image from the url via retrieve_image.py. I should do this with using the same session, but when running the scraper, it downloads an empty image, meaning it is not the same session. I thought the session would be equal because the PHPSESSID is equal. Here is retrieve_image.py: import bs4 import lxml import requests import io import urllib2 def retrieve_image(page, server): for i in range(1): cookies = dict(PHPSESSID='something') soup = bs4.BeautifulSoup(page.body, "lxml") samples = soup.find(id="captcha", src=True)['src'] another = soup.find('div', {'class:', 'test'}) #print(page.body) #print("Another text -&gt; " + another.text) image_url = str(server + samples) print(image_url) print('\n HERE IS I \n') print(requests.get(image_url, cookies=cookies)) print('\n') img_data = requests.get(image_url, cookies=cookies).content # print("doe ff image data\n" +img_data) myString = '_num' + str(i) + '.png' print(another.text + myString) with open(another.text + myString, 'wb') as h…
score: 0
answer count: 1

http://stackoverflow.com/q/48597254
tagged with: constructor
has body: Open to suggestions for a better title... If I remember this correctly, in Visual Basic you could assign multiple variables in a tree of some object with a 'with' constructor like this With Foo_Object.Foo_method .Bar_var1='foo' .Bar_var2='bar' End With Is there a similar construct in Python ?
accepted answer: http://stackoverflow.com/a/48597348
tagged with: python
has answer: http://stackoverflow.com/a/48597348
tagged with: class
has title: assign multiple values to variables in a subclass of the same class
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/48562670
tagged with: django
tagged with: python
tagged with: django-rest-framework
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
type: Question
has title: can not remove field from serializer with .pop('field') in create() method - DRF
has body: I'm using Django rest framework. I want to create admin endpoint where the user can add the member with project permission. following is the data coming from the user. { "email" : "name@yopmail.com", "first_name" : "asd", "last_name" : "asd", "projects":[{ "project_id" : 1, "project_role" : 1 }, { "project_id" : 1, "project_role" : 1 }], "position" : "something something" } following is serializer I created to validate and save the data. class ProjectPermissionSerializer(serializers.Serializer): """ Serialiser to hold permissions pair of project_id and role """ project_id = serializers.IntegerField(allow_null=False) project_role = serializers.ChoiceField(PROJECT_ROLES) def create(self, validated_data): print(validated_data) def update(self, instance, validated_data): pass class ProjectMemberSerializer(serializers.ModelSerializer): """ serializer to add new member with projects """ projects = ProjectPermissionSerializer(many=True) email = serializers.EmailField() class Meta: model = User fields = ('first_name', 'last_name', 'email', 'position', 'projects') def create(self, validated_data): permission_data = validated_data.pop('projects') emailstatus = {"email_id": validated_data.pop('email')} emailobj, created = EmailStatus.objects.get_or_create(**emailstatus) validated_data['email'] = emailobj project_member = User.objects.create(**validated_data) return project_member still, after popping the projects from validated_data, I'm getting following error. AttributeError: Got AttributeError when attempting to get a value for field `projects` on serializer `ProjectMemberSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'projects'.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48562720

http://stackoverflow.com/comment/84076161
type: QuestionComment
comment on: http://stackoverflow.com/q/48538404
score: 1
has text: That link is also outdated (it's about version 1.0). Check how to read data for the current version (1.5 as of now)
type: Comment

rss
type: Tag
tags question: http://stackoverflow.com/q/48526378
tag name: rss

http://stackoverflow.com/comment/84119952
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48561120
has text: where should I see that

http://stackoverflow.com/comment/84168079
comment on: http://stackoverflow.com/a/48585463
type: Comment
score: 0
type: AnswerComment
has text: Still get the warning though, but it worked. Does it cause any problems?

http://stackoverflow.com/comment/84278550
has text: thanks for you advice..I have clicked a new page which url is "https://www.tripadvisor.in/ShowUserReviews-g304558-d1312478-r557236838-Park_Prime_Kolkata-Kolkata_Calcutta_Kolkata_District_West_Bengal.html#CHECK_RATES_CONT"....Now while clicked on the next page, "/ShowUserReviews-g304558-d1312478-r557236838"...This ids got changed..How to automate that?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48640723
type: Comment

http://stackoverflow.com/a/48499909
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83994977
has body: This might be what you are looking for: mainset = {1, 2, 3, 4} subsets = [{1, 2}, {3, 2, 1}, {1}] max(map(len, map(mainset.intersection, subsets))) # 3 Sometimes nested map can get confusing, in which case there are some alternatives. Compose functions: from toolz import compose max(map(compose(len mainset.intersection), subsets)) # 3 List comprehension: max(len(mainset.intersection(subset)) for subset in subsets) # 3
type: Answer
answers question: http://stackoverflow.com/q/48499357
has comment: http://stackoverflow.com/comment/83995076

http://stackoverflow.com/comment/84002470
has text: Exactly what do you mean by the results of writing the new lines? The method has no results. You mean write whether the operation failed or succeeded?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48504285

http://stackoverflow.com/comment/84027710
type: Comment
has text: "How do I dynamically create variables" is a very common beginner question, but the sane answer is almost always "use a dict" or "use a list". Search for duplicates.
score: 0
comment on: http://stackoverflow.com/q/48515893
type: QuestionComment

http://stackoverflow.com/comment/84094634
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48542674
score: 1
has text: An earlier SO question with `MatlabOpaque` objects, https://stackoverflow.com/questions/32913301/matlab-date-string-results-in-java-lang-string-in-python-scipy-io

http://stackoverflow.com/a/48628442
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48628417
upvote count: 46
answers question: http://stackoverflow.com/q/48628417
type: Answer
has body: You can use value_counts + isin - v = df.Parameter.value_counts() df[df.Parameter.isin(v.index[v.gt(5)])] For example, where K = 2 (get all items which have more than 2 readings) - df ID Parameter Value 0 0 A 4.3 1 1 B 3.1 2 2 C 8.9 3 3 A 2.1 4 4 A 3.9 5 5 B 4.5 v = df.Parameter.value_counts() v A 3 B 2 C 1 Name: Parameter, dtype: int64 df[df.Parameter.isin(v.index[v.gt(2)])] ID Parameter Value 0 0 A 4.3 3 3 A 2.1 4 4 A 3.9
score: 46

http://stackoverflow.com/comment/84195378
comment on: http://stackoverflow.com/q/48598829
has text: ... and to add, of course code needs to be a [mcve].
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84375057
score: 0
comment on: http://stackoverflow.com/q/48526468
has text: Ok just read your comment about it failing after 1029 files: I suspect it could have to do with the file descriptor never being closed for some reason
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84210916
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48607288
has text: Nice one ! +1 :-)

http://stackoverflow.com/a/48597147
has comment: http://stackoverflow.com/comment/84191219
has comment: http://stackoverflow.com/comment/84191281
has body: You have quoting problems in your assignment to cmd. You're using " as the delimiter around the Pythong string, and also around the argument to -F in the shell command. That's ending the Python string. Use single quotes around the shell argument. cmd = "vcgencmd measure_temp | awk -F'=|' '{print $2}'" Yuo're also missing colons and indentation in your if statement. And Python is case-sensitive, so If should be if. if Temp &gt;= 40: print ("40+") elif Temp &gt;=35: print ("35+") else: print ("Below 35")
has comment: http://stackoverflow.com/comment/84191568
score: 0
has comment: http://stackoverflow.com/comment/84191634
type: Answer
has comment: http://stackoverflow.com/comment/84191649
answers question: http://stackoverflow.com/q/48597110
has comment: http://stackoverflow.com/comment/84191366

http://stackoverflow.com/comment/84229667
has text: Windows limits paths to 260 characters, and some of your paths are probably too long. There are workarounds for this: for example, by assigning a drive letter to some intermediate folder using `subst`.
comment on: http://stackoverflow.com/q/48616330
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84257912
has text: @KevinL. Yes, I did
type: QuestionComment
comment on: http://stackoverflow.com/q/48630276
type: Comment
score: 0

http://stackoverflow.com/q/48626841
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has body: I have the three dataframes show below: primarydf is a dataframe showing a book TitleCode, Type (digital/physical), WeekEnding (meaning that the unit data is for the week ending in this date), and TotalUnits (how many units were sold). attachdf is a dataframe showing a product, related to each book, that was released after the book had been in the market. expecteddf is a verbose version of what I am trying to achieve with some extra columns for the sake of clarity. The actual columns I want are TitleCode, Type, Week 1 Attach Rate, 4 Week Attach Rate, LTD Attach Rate, and Total Attached Units. Week1A= Attached products sold on week 1. Week1U= Books sold up to and including week 1 of the release of the attached product. Week4A= Attached products sold up to and including week 4. Week4U= Books sold up to and including week 4 of the release of the attached product. LTDA= Attached products sold up to the most recent date. LTDU= Books sold up to the most recent date. For example, ['Week 1 Attach Rate'] = ['Week1A']/['Week1U'], ['Week 4 Attach Rate'] = ['Week4A']/['Week4U'], ['LTD Attach Rate'] = ['LTDA']/['LTD1U'], Dataframes import pandas as pd from io import StringIO attachproduct = StringIO("""TitleCode,Type,WeekEnding,TotalUnits A,1,12/16/2017 0:00,548 A,1,12/23/2017 0:00,74 A,1,12/30/2017 0:00,87 A,1,1/6/2018 0:00,4 A,1,1/13/2018 0:00,878 A,2,12/16/2017 0:00,49 A,2,12/23/2017 0:00,8498 A,2,12/30/2017 0:00,84 A,2,1/6/2018 0:00,74 A,2,1/13/2018 0:00,453 B,1,12/23/2017 0:00,68 B,1,12/30/2017 0:00,573 B,1,1/6/2018 0:00,75 B,1,1/13/2018 0:00,752 B,1,1/20/2018 0:00,75 B,2,12/23/2017 0:00,17 B,2,12/30/2017 0:00,98 B,2,1/6/2018 0:00,7875 B,2,1/13/2018 0:00,73 B,2,1/20/2018 0:00,75 C,1,12/23/2017 0:00,79 C,1,12/30/2017 0:00,75727 C,1,1/6/2018 0:00,77 C,1,1/13/2018 0:00,3727 C,1,1/20/2018 0:00,72 C,1,1/27/2018 0:00,7275 C,1,2/3/2018 0:00,27 """) primaryproduct = StringIO("""TitleCode,Type,WeekEnding,TotalUnits A,1,11/11/2017 0:00,830 A,1,11/18/2017 0:00,830 A,1,11/25/2017 0:00,…
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48630873
has title: Constraining groupby operations
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48630873

http://stackoverflow.com/q/48515904
type: Question
accepted answer: http://stackoverflow.com/a/48516380
has answer: http://stackoverflow.com/a/48516380
has body: I have a *DataFrame* like that: ID_client l date l contact -------------------------------------- 1 2017/01/01 email 1 2017/01/02 mail 1 2017/01/03 email 1 ......... 1 2017/06/06 sms 2 ...... tel 2 tel 3 . etc until 2017/31/31 etc and I would like to have 2 DataFrames, the first only one line for year with the sum of each contact split in different columns and the last same per month: 1) id l email l sms l tel l mail ---------------------------- 1 40 20 30 50 2 20 30 40 50 2 ........................ 3 ..............etc 2) id l date_month l email l sms l tel l email -------------------------------------------------- 1 2017/01 20 10 5 2 1 2017/02 .............. . 2 2017/01 ............. 2 2017/02 ................ . etc I tried Df.set_index("date") Df["contact"].resample("m") Df.groupby(df["date", "I'd_client"])["contact"].Count() Df.groupby(df["date", "I'd_client"]). Agg({"contact" :" count"}) Or I tried to create another dataframe df2=Df.groupby(df.index) Df2="contact" df2.apply(lambda x : x.count()) But it didnt give me what I wanted!!
tagged with: aggregate-functions
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 0
has title: How to split into columns the count of a categorical variable
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/48492530
tagged with: python
has title: Selenium response differs from browser view
tagged with: caching
has body: I am try to use Selenium with python. Here is my snippet from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--incognito') driver = webdriver.Chrome(options=options) driver.get('https://www.google.com') element = driver.switch_to_active_element() element.send_keys('Donald Trump') element.send_keys(Keys.RETURN) Here is two screenshot both made in incognito mode. Left one is controlled by selenium. And to see right one i just copy the link from left and paste it to incognito chrome window. Not hard to see that both windows are in incognito mode, but results are different. any idea why this can be possible? Mb i mess smthng? I am stuck with this. Looking for somebody help.
score: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/48492609
tagged with: google-chrome
has answer: http://stackoverflow.com/a/48501205
type: Question
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/84252652
comment on: http://stackoverflow.com/q/48624104
score: 0
type: Comment
has text: @eyllanesc I don't want to zoom. I want to use the "count" variable to scroll through the images.
type: QuestionComment

http://stackoverflow.com/q/48637407
has comment: http://stackoverflow.com/comment/95713210
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89089800
tagged with: pre-trained-model
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47194449
has body: I was wondering how I can change the optimizer for inception v3 from SGD to Adam Optimizer. I would like to keep the weights in pre-trained, but not the default SGD Optimizer. If I add Adam optimizer, it will throw an error saying it cannot find Adam optimizer in pre-trained checkpoint file: NotFoundError (see above for traceback): Key OptimizeLoss/InceptionV3/Mixed_6b/Branch_2/Conv2d_0d_7x1/BatchNorm/beta/Adam_1 not found in checkpoint [[Node: save_1/RestoreV2_525 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2_525/tensor_names, save_1/RestoreV2_525/shape_and_slices)]] [[Node: save_1/Assign_758/_1522 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_3805_save_1/Assign_758", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]] Training only the top layer of the neural network without training inception works fine. Below is the code used to implement inception v3 (from im2xt): from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.contrib.slim.python.slim.nets.inception_v3 import inception_v3_base slim = tf.contrib.slim def inception_v3(images, trainable=True, is_training=True, weight_decay=0.00004, stddev=0.1, dropout_keep_prob=0.8, use_batch_norm=True, batch_norm_params=None, add_summaries=True, scope="InceptionV3"): """Builds an Inception V3 subgraph for image embeddings. Args: images: A float32 Tensor of shape [batch, height, width, channels]. trainable: Whether the inception submodel should be trainable or not. is_training: Boolean indicating training mode or not. weight_decay: Coefficient for weight regularization. stddev: The standard deviation of the trunctated normal weight initializer. dropout_keep_prob: Dropout k…
score: 0
answer count: 0
has title: Change optimizer for pre-trained inception v3
upvote count: 1

http://stackoverflow.com/comment/84162860
comment on: http://stackoverflow.com/a/48572741
type: Comment
score: 0
type: AnswerComment
has text: @B.Gees Environment variables and command line arguments are "two big differences", as Odessites say. The difference is neither PHP nor Linux specific, this is how programs are executed in any OS. Please see here for a discussion: https://stackoverflow.com/questions/7443366/argument-passing-strategy-environment-variables-vs-command-line --- If you need to access environment variables with `os.getenv()`, use `$env` parameter to `proc_open` (this is the only way in PHP, afaik). If you only need command line arguments, call `exec('your whole command line here')`. Hope this helps.

http://stackoverflow.com/comment/83973774
type: QuestionComment
has text: @LaurynasTamulevičius that won't work because those properties will try to create the student or teacher object regardless.
comment on: http://stackoverflow.com/q/48490192
score: 0
type: Comment

http://stackoverflow.com/q/48575912
score: 1
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48717280
favorite count: 0
type: Question
has title: Duplicate -tpl.c~ files when created a new project in Django (Atom Text Editor)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84234862
has comment: http://stackoverflow.com/comment/84185786
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84148464
tagged with: atom-editor
has comment: http://stackoverflow.com/comment/84433558
has body: I created a new project with django-admin startproject basicform And then created a new application django-admin startapp basicapp But, when i started my server, python manage.py runserver It made duplicated files, like this https://drive.google.com/open?id=1MTvpHf7pACsp9o_b129g5wPsKqwbbZDp Is this an ERROR? Should i delete the files? I am working on django-1.11 and Python 3.6.4 :: Anaconda, Inc. Also, when i tried running the server, it worked fine. python manage.py runserver https://drive.google.com/open?id=1arjf3U8Mm8ggwLTbSk5Gc9bd_FDl5lJj EDIT: I have deleted the duplicate -tpl.c~ files and the project is working fine.

http://stackoverflow.com/comment/84188653
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48595728
has text: did you install it as `pip install nlgserv` ?
type: Comment

http://stackoverflow.com/comment/83976878
type: Comment
has text: Thanks for your response @Riptide34, I have updated my issue to reflect the "str:", however this does not fix the issue.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48491741

http://stackoverflow.com/q/48575601
has title: Add lists of lists together in numpy
has comment: http://stackoverflow.com/comment/84147799
has comment: http://stackoverflow.com/comment/84148007
type: Question
has comment: http://stackoverflow.com/comment/84147913
has comment: http://stackoverflow.com/comment/84147778
type: UnansweredQuestion
tagged with: python
has body: I have this tmp0 = np.array([[a,b],[c,d],[e,f],...,[...]]) I want to take out a value, say [a,b] and compare it to [c,d] to make stuff simple, than add those two to the end of a new array as a 3D list tmp1 = np.array([[[...],[...]],[[a,b],[c,d]]]) This have been proven to be a real horror show... How do I achieve this..? In just a regular array it would be append, but not in numpy for some odd reason
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/84147885
answer count: 0

http://stackoverflow.com/comment/84250784
has text: Think about it, if `bisect` lets you find the insertion point, how you could check if the value is in the list at that point..
comment on: http://stackoverflow.com/q/48626954
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48627450
favorite count: 0
has body: I use Anaconda's Python 3.6.3 distribution and it comes with NLTK installed, but not with NLTK DATA, which I need for a project, the problem is, when I try to install with nltk.download() I get PermissionError: [Errno 13] Permission denied: '/usr/share/nltk_data' So, I did some research, and I see people suggesting to run Python as sudo python but if I do that, it will launch the base Linux's Python, not Anaconda's. tl;dr I need some way to do something like sudo conda python If you have other suggestions that might work, I'll take it too. Thanks!
type: Question
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84263928
tagged with: nltk
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48627577
score: 2
has comment: http://stackoverflow.com/comment/84277746
tagged with: anaconda
has title: PermissionError when downloading NLTK data
downvote count: 0
tagged with: shell
has answer: http://stackoverflow.com/a/48634212

http://stackoverflow.com/a/71068225
answers question: http://stackoverflow.com/q/48519972
score: 2
has comment: http://stackoverflow.com/comment/136193613
type: Answer
upvote count: 2
has body: Just visit a page that shows it like the one Loïc showed. Then after that, you go on to visit Amazon, or whatever website you want, knowing you are using the correct IP address. from selenium.webdriver.common.by import By driver.get('https://api.ipify.org/') ip_address = navigator.driver.find_element(By.TAG_NAME, "body").text print(ip_address)
downvote count: 0

http://stackoverflow.com/q/48634933
type: UnansweredQuestion
has body: I was trying to write script using ColorBar module following the official document. However,I got error below. ImportError: cannot import name 'ColorBar' Also, when I look at the bokeh github page, module ColorBar is not provided anymore. Does anyone know how following code should be revised to be compatible with v0.12.13? def heatmap(df,colstr): from math import pi from bokeh.io import show from bokeh.models import ( ColorBar, ColumnDataSource, HoverTool, LinearColorMapper, BasicTicker, PrintfTickFormatter, ) from bokeh.plotting import figure def preprocess(df,colstr): #temp=pd.DataFrame(df[colstr]) df["Hour"]=df.index.hour.astype(str) df["Date"]=df.index.date.astype(str) temp=df"Hour","Date",colstr return temp #add hour column and day column df1=preprocess(df,colstr) colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1", "#cc7878", "#933b41", "#550b1d"] mapper = LinearColorMapper(palette=colors, low=df[colstr].min(), high=df[colstr].max()) source = ColumnDataSource(df1) #hard cord. better to be flexiable hours = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'] #assuming summerdesign day and winter design day is included #dates = list(df1["Date"])[48:] dates = list(df1["Date"].drop_duplicates())[4:] TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom" p = figure(title=colstr, x_range=hours, y_range=list(reversed(dates)), x_axis_location="above", plot_width=1200, plot_height=1200, tools=TOOLS, toolbar_location='below') p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_text_font_size = "5pt" p.axis.major_label_standoff = 0 p.xaxis.major_label_orientation = pi / 3 p.rect(x="Hour", y="Date", width=1, height=1, source=source, fill_color={'field': colstr, 'transform': mapper}, line_color=None) color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size="5pt", ticker=BasicTicker(desired_num_t…
answer count: 1
has answer: http://stackoverflow.com/a/48648193
has title: What module I can use instead of ColorBar in Bokeh v0.12.13
score: 0
tagged with: python
tagged with: bokeh
type: Question

http://stackoverflow.com/comment/84013014
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48508702
has text: @L.jakob If you've resolved your issue please share the answer.

http://stackoverflow.com/a/48625892
type: Answer
has body: PIL is used to create or manipulate static images. It looks like you want to do some animation. For this, other libraries are more useful, such as PyGame. (if you want to use Python) or the JavaScript Canvas in a browser, if you are OK with JavaScript. Also, your wish to 'calculate the time taken for one point to move from one coordinate to another' is a bit vague. As the programmer, you can determine yourself how fast a point should move across the screen ;-)
answers question: http://stackoverflow.com/q/48563045
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/84132754
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48568058
type: AnswerComment
has text: @AndrewL I must be misunderstanding something. What does this not address?

boto3
tags question: http://stackoverflow.com/q/48516175
tag name: boto3
tags question: http://stackoverflow.com/q/48639401
tags question: http://stackoverflow.com/q/48564598
tags question: http://stackoverflow.com/q/48521255
tags question: http://stackoverflow.com/q/48517407
tags question: http://stackoverflow.com/q/48491839
tags question: http://stackoverflow.com/q/48608570
tags question: http://stackoverflow.com/q/48525338
type: Tag
tags question: http://stackoverflow.com/q/48601038
tags question: http://stackoverflow.com/q/48494089

http://stackoverflow.com/a/48600846
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48600299
has comment: http://stackoverflow.com/comment/84198336
has body: When you call any of the above (subprocess.* or os.system()) you create a new (child) process if you run cd this way, you change current working directory only for the cd itself, but it does not affect your running python code and any command you execute afterwords. You'd need to use os.chdir() or just hold that information and pass it into newly created children processing with cwd keyword of subprocess.Popen().
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/48600299

http://stackoverflow.com/comment/84338580
comment on: http://stackoverflow.com/q/48548639
score: 0
type: Comment
type: QuestionComment
has text: Hi, I found where the problem was, somewhere else in my code, a time.sleep was slowing the whole process... ^^ So struct was working fine :) But thanks for that link, i'll use that...

http://stackoverflow.com/comment/84155266
type: AnswerComment
has text: Is there a way to do this without invoking pandas?
type: Comment
comment on: http://stackoverflow.com/a/48579013
score: 0

http://stackoverflow.com/comment/83972263
type: AnswerComment
type: Comment
has text: maybe there is ```nohup.out``` file that all printed lines get redirected to, and is located in the same folder where you were when you run this command
comment on: http://stackoverflow.com/a/48489570
score: 0

http://stackoverflow.com/q/48546091
answer count: 2
accepted answer: http://stackoverflow.com/a/48546828
has comment: http://stackoverflow.com/comment/84088452
possible better answer: http://stackoverflow.com/a/48547168
has answer: http://stackoverflow.com/a/48546828
tagged with: python
has comment: http://stackoverflow.com/comment/84087942
score: 4
has title: How to filter a pandas DatetimeIndex by day of week and hour in the day
type: AnsweredQuestion
tagged with: datetimeindex
tagged with: filter
tagged with: pandas
has body: I have a pandas DatetimeIndex and I would like to filter the index by the criterion that the day of the week and hour of the day matches a list. For example, I have of list of tuples indicating valid (day of week, hour, minute) for each TimeStamp: [(4, 6), (5, 7)] The final index should only contain date times that are Friday(day_of_week = 4) hour 6 or Saturday(day_of_week = 5) hour 7. Lets say the input data frame is like: 2016-04-02 06:30:00 1 2016-04-02 06:45:00 2 2016-04-02 07:00:00 3 2016-04-02 07:15:00 4 2016-04-03 07:30:00 5 2016-04-03 07:45:00 6 2016-04-03 08:00:00 7 After the filter, it should be like: 2016-04-02 06:30:00 1 2016-04-02 06:45:00 2 2016-04-03 07:30:00 5 Because I only keep indices whose day of week and hour of the day in the list [(4, 6), (5, 7)]
downvote count: 0
has answer: http://stackoverflow.com/a/48547168
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/q/48629230
has body: I have an image file called "test.png" I want to be able to read the image file as follows: with open("test.png", "rb") as f: input = f.read() #Do some pre-processing on "input" input_array = #some operation on the variable "input" to convert it to a numpy array #processing "input_array" output_dat = #some operation to convert input_array into the same format as variable "input" Now, I want to be able to turn this input data into a numpy array. How would I go about doing this, and vice-versa i.e., I also want to be able to convert it back to the format as input is in. Convert input to a numpy array format Convert numpy array back to the same format as input
has comment: http://stackoverflow.com/comment/84255828
score: 0
answer count: 0
has title: Python - Using f.open to read an image file -> Convert to numpy array
has comment: http://stackoverflow.com/comment/84255315
type: Question
has comment: http://stackoverflow.com/comment/84255988
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84255368
linked to: http://stackoverflow.com/q/31386096
tagged with: arrays
tagged with: python

http://stackoverflow.com/comment/84215979
comment on: http://stackoverflow.com/a/48609721
type: Comment
score: 1
type: AnswerComment
has text: @AntonvBR maybe OP is trying to learn how to use `while` loops. Even if this is not the case it is helpful to explain why code is not working.

http://stackoverflow.com/q/48596897
possible better answer: http://stackoverflow.com/a/48597272
tagged with: python
has title: I want to get multiple repeating lines from a long txt file (~20k lines)
tagged with: line
tagged with: text
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48597127
accepted answer: http://stackoverflow.com/a/48597127
has answer: http://stackoverflow.com/a/48597272
has body: I have a long text file with 20k+ lines. There are four distinct patterns which identify the beginning of the lines I want to write to a file. These lines are repeated in the entry file. There are lines which don't start with one of those patterns, these lines shall be skipped. I want to grab the lines starting with the four patterns in order and write them to a file-output in the same order as in the base file. For example: random text specific start of the first line, random text A random text B specific start of the second line, random text C random text D etc. I want the output seems like: specific start of the first line, random text A specific start of the second line, random text C I was thinking about reg-exp, but I'm quite unfamiliar with them. I thought maybe a line-by-line executed function could be better, and maybe even faster. The important thing is, I must retain the original line order.
type: Question

http://stackoverflow.com/q/48502444
type: Question
has body: My program blocked, and the Client never went out of the loop, what's wrong? '''Client, send hello,world''' import socket s = socket.socket() s.connect(('localhost', 6969)) s.send(b'hello, world') while True: data = s.recv(1024) if data: print(data) else: break #never gets here '''Server, first receive, then send''' import socket, threading def tr(sock, addr): while True: data = sock.recv(1024) if data: print(data) else: break #never gets here sock.send(b'get it') # sock.close() s = socket.socket() s.bind(('localhost', 6969)) s.listen(5) while True: sock, addr = s.accept() t = threading.Thread(target=tr,args=(sock, addr)) t.start()
has title: Python socket , why would the program blocked?
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/83999031
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83998376
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48503368
upvote count: 1
has answer: http://stackoverflow.com/a/48503368
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/78536556
answers question: http://stackoverflow.com/q/48535827
score: 0
type: Answer
has body: I'm not using Canari but maltego-trx, but I think it will be similar, consider what I do is base on a little clue from maltego documentation at the bottom of the page in "Reversing Entity Links" section with that short explanation I success to create reverse link from output to input direction. the conclution is to set the link setting in entity properties. example code: from maltego import TRX m = TRX.MaltegoTransform() a = m.addEntity('maltego.Phrase', 'test') #here is how you set the link: a.addProperty('link#maltego.link.direction','link#maltego.link.direction','','output-to-input') print(m.returnOutput()) and this is the image of the result if I use your code, using maltego-trx, it should be like this: from maltego import TRX def do_transform(request, response, config): return '74.207.243.85' m = TRX.MaltegoTransform() request='give requests here' response='give response here' config='give config here' result = do_transform(request, response, config) a = m.addEntity('maltego.IPv4Address', result) #here is how you set the link: a.addProperty('link#maltego.link.direction','link#maltego.link.direction','','output-to-input') print(m.returnOutput()) and this is the image of the result

http://stackoverflow.com/a/48531455
has body: Your error message gives: Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8891/?token=dcf34cac4a27f8b92397fcec424b228b308a4588f0473fd6 So try that first in your browser and see if the error persist.
accepted answer of: http://stackoverflow.com/q/48530749
has comment: http://stackoverflow.com/comment/84060215
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84058907
has comment: http://stackoverflow.com/comment/84060106
answers question: http://stackoverflow.com/q/48530749
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84058788
has comment: http://stackoverflow.com/comment/84059819
has comment: http://stackoverflow.com/comment/84060022

http://stackoverflow.com/comment/84279718
type: Comment
comment on: http://stackoverflow.com/a/48637135
type: AnswerComment
score: 1
has text: This _is_ the answer.

http://stackoverflow.com/q/48535543
has comment: http://stackoverflow.com/comment/84066387
answer count: 1
has body: Views.py def form_name_view(request): form = FormName() if request.method == "POST": form = FormName(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect('/') # return index(request) else: print('INVALID FORM INPUTS') return render(request, 'first_app/form_page.html', {'form': form}) When I use HttpResponseRedirect to get back to my index page, then everything works correct, but the concern is if I use calling index method instead of HttpResponseRedirect then the behavior is a little bit insane: After reaching index page if I hit refresh then alert appears says: The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you want to continue? If i want to get back to the same form page, by calling that same method again like return form_name_view(request) The new form is already filled with previous inserted data, with the message on the form Topic with this Topic name already exists. The question is what is the reason, calling method results like this?
has comment: http://stackoverflow.com/comment/84072446
tagged with: django-forms
has comment: http://stackoverflow.com/comment/84066956
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48535747
has answer: http://stackoverflow.com/a/48535747
has comment: http://stackoverflow.com/comment/84066457
tagged with: django
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84092019
has comment: http://stackoverflow.com/comment/84067081
has title: Why calling method inside views.py after successful submission of forms doesn't clear the form?
type: AnsweredQuestion
tagged with: django-views
upvote count: 0

http://stackoverflow.com/q/48572617
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49186837
accepted answer: http://stackoverflow.com/a/49186837
has title: How to use pandas_ml to make a confusion matrix with 2 classes?
favorite count: 0
type: Question
has body: I am trying to make a confusion matrix with plotting, pandas_ml seems to have a function but it doesn't work with 2 classes. Is there some secret option to get it working? from pandas_ml import ConfusionMatrix ytrue = ['ham', 'ham', 'spam'] ypred = ['ham', 'spam', 'spam'] cm = ConfusionMatrix(ytrue, ypred) cm results in Predicted False True __all__ Actual False 0 0 0 True 0 0 0 __all__ 0 0 0 This: from pandas_ml import ConfusionMatrix ytrue = ['ham', 'ham', 'spam', 'third'] ypred = ['ham', 'spam', 'spam', 'third'] cm = ConfusionMatrix(ytrue, ypred) cm results in Predicted ham spam third __all__ Actual ham 1 1 0 2 spam 0 1 0 1 third 0 0 1 1 __all__ 1 2 1 4
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48955493
has answer: http://stackoverflow.com/a/49151659
possible better answer: http://stackoverflow.com/a/49151659
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/q/48641217
tagged with: anaconda
has title: anaconda command prompt help required
score: -1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48641381
has body: I started running one python code in anaconda command prompt. Now that python code is running from last two days. Till now it has computed value for 2800 items and there are 8000 more values to compute. I want to get out of that loop and I want that computed data of 2800 values to be safe. How can i get out of that loop( terminate that loop),not whole code, without the loss of that data? my code is still running and computing values. ` # Database = np.zeros(10000*72).reshape(10000,72) for entry in range(10000): Database[entry] = hist print("Entered for !"+imagename) collection = client.test_database.coraltest29 collection.insert({"distances":Database.tolist(),"name":'Coral Dataset'})`
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84279245
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84279337
downvote count: 1

http://stackoverflow.com/q/48579428
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84157075
has comment: http://stackoverflow.com/comment/84156599
has comment: http://stackoverflow.com/comment/84157186
tagged with: centos
tagged with: docker
has comment: http://stackoverflow.com/comment/84157152
has comment: http://stackoverflow.com/comment/84157047
answer count: 2
has comment: http://stackoverflow.com/comment/84157339
downvote count: 0
has answer: http://stackoverflow.com/a/53423014
has answer: http://stackoverflow.com/a/77124038
upvote count: 1
has comment: http://stackoverflow.com/comment/84156651
has title: python subprocess "no such file or directory" inside docker
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84156678
has comment: http://stackoverflow.com/comment/84157306
type: Question
has comment: http://stackoverflow.com/comment/84156494
has comment: http://stackoverflow.com/comment/84156535
has body: app.py def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None command = /some/path/to/command command = which(command) if command is not None: print "command exists and is exectuable" child = subprocess.Popen(command) OUTPUT: command exists and is exectuable [Errno 2] No such file or directory when this is run inside docker, even though it could find the executalbe, when it's run via subprocess, it is throwing the "no such file" error when this is run outside of container, i dont see this behavior any advice on what's going on here when the command is run via subprocess? when I added shell=True, it still cant find it
has comment: http://stackoverflow.com/comment/84156515

http://stackoverflow.com/comment/84160909
has text: Done, please let me know if you were asking for other log file. Thanks!
comment on: http://stackoverflow.com/q/48557887
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84241886
type: QuestionComment
score: 0
has text: Thanks all for your comments. So, probably it's a bad idea to do so. I did find many links suggesting to use dictionary. Probably that remains the best option.
comment on: http://stackoverflow.com/q/48622683
type: Comment

http://stackoverflow.com/a/62752472
answers question: http://stackoverflow.com/q/48560138
has body: I tried all the solutions suggested here, but none of them worked for me. What solved the issue was adding: import plotly.io as pio pio.renderers.default='notebook' and also using fig.show("notebook") rather than simply fig.show(), as suggested here.
downvote count: 0
type: Answer
score: 20
upvote count: 20

http://stackoverflow.com/comment/84169646
type: Comment
type: QuestionComment
has text: You even state in your problem description that you don't write the same string you check for
score: 1
comment on: http://stackoverflow.com/q/48586338

http://stackoverflow.com/comment/84250573
has text: So initially, that document has one line per tag, right ? But you want to measure, on that particular .docx file, how this changes ? Because as you mention, depending on the editor you use, that would change ("if copy-pasted in a simple txt editor, the above text would result in 3 lines instead of 7") ? The return-to-line character is \n, couldn't you just count how many times that one appears ? Do you have a consistent separator between TAG and the prose part ? Maybe tab or ?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48626396

http://stackoverflow.com/comment/84219736
comment on: http://stackoverflow.com/q/48611615
type: Comment
type: QuestionComment
score: 1
has text: You are trying to concatenate a list of strings and number. Python does not know how to do that. You have to convert everything to strings first.

http://stackoverflow.com/q/48541801
linked to: http://stackoverflow.com/q/40504552
has answer: http://stackoverflow.com/a/52150652
has body: I have tried all methods mentioned on the internet but there is no use. I am trying to install misaka by writing pip install misaka it keeps complaining by showing the same message. I have downloaded and installed MS build tool 2015 and 2017, Restarted my laptop. Whatever I did, couldn't figure out why it complains. Python version 3.6.4 Windows 10
tagged with: python
has comment: http://stackoverflow.com/comment/97850560
answer count: 4
score: 33
has title: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
type: Question
downvote count: 0
type: UnansweredQuestion
tagged with: misaka
tagged with: django
duplicate of: http://stackoverflow.com/q/40504552
has answer: http://stackoverflow.com/a/49984619
tagged with: msbuild
has answer: http://stackoverflow.com/a/59057393
favorite count: 0
upvote count: 33
has comment: http://stackoverflow.com/comment/84081503
has comment: http://stackoverflow.com/comment/84099575
tagged with: python-3.x
linked to: http://stackoverflow.com/q/29846087
has answer: http://stackoverflow.com/a/52467429

http://stackoverflow.com/comment/84284962
comment on: http://stackoverflow.com/a/48644006
type: AnswerComment
score: 0
type: Comment
has text: it's surprising as the highest date wins whatever it is. You could try to print `sorted(list_of_files, key=lambda x : max(os.path.getmtime(x),os.path.getctime(x)))` and see which ones come first/last to debug.

http://stackoverflow.com/q/48511018
type: UnansweredQuestion
downvote count: 0
tagged with: caffe
tagged with: machine-learning
tagged with: python
tagged with: computer-vision
has body: I am trying to obtain the gradient of the loss with respect to an input image. In Caffe (the original), the following code achieved my goal: ### Load image into net's data layer img = caffe.io.load_image(jpg_file) transformed_image = transformer.preprocess('data', img) net.blobs['data'].data[...] = transformed_image # copy image data into memory for net ... ### Form the final label vector (one hot vector) finalLabelVector = np.zeros((1,num_classes)) finalLabelVector[0,ground_truth_label] = 1 ### Do a backward pass using finalLabelVector # must have 'force_backward: true' set in deploy prototxt backwardpassData = net.backward(**{net.outputs[0]: finalLabelVector}) # Get the derivative with respect to the input (data layer) delta = backwardpassData['data'] What must I do using the Caffe2 Python interface to calculate the same delta as above?
has title: Caffe2's equivalent to Caffe's Net.backward()?
score: 2
tagged with: caffe2
favorite count: 0
type: Question
answer count: 0
upvote count: 2

http://stackoverflow.com/q/48493745
has body: I have created a simple blog using DJANGO with three classes in views.py views.py def blog(request): posts=blog.objects.filter(createddate__lte=timezone.now()).order_by('-createddate') if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'base.html'{'posts':posts}) def blog_details(request,slug): posts=blog..objects.filter(createddate__lte=timezone.now()).order_by('-createddate') pos=get_object_or_404(app_descripts, slug_title=slug) if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'blog_details.html'{'posts':posts,'pos':pos}) def about(request): posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') if request.method == "POST": name = request.POST.get('name') message = request.POST.get('message') contact.objects.create(name=name message=message) return render(request, 'about.html'{'posts':posts}) in the html I use this way because I have some code: {% extends 'blog/base.html' %} {% block content %} ....................... {% endblock %} In the base.html out of block content I have a simple contain where I have code for all post ( posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') ). but to view the that posts in all pages(blog,blog_details,about) must write this code ( posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate')) in all views to work fine. that happen and for my html contact form because is out of content. how can avoid to execute same code in all views ?
tagged with: django
has comment: http://stackoverflow.com/comment/83981279
favorite count: 0
type: Question
tagged with: django-views
linked to: http://stackoverflow.com/q/2893724
score: 1
has title: django views.py avoid duplicate code in views
tagged with: python
tagged with: python-2.7
answer count: 0
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83981129
type: UnansweredQuestion

http://stackoverflow.com/a/48520908
has comment: http://stackoverflow.com/comment/84107120
type: Answer
has comment: http://stackoverflow.com/comment/84036496
has comment: http://stackoverflow.com/comment/84036412
score: 5
accepted answer of: http://stackoverflow.com/q/48520821
type: AcceptedAnswer
downvote count: 0
has body: That regular expression allows any alphanumeric character (a to z, A to Z, and 0 to 9). You are looking for: # \d allows only numeric digits # - or \- allows only hyphen # [\d-] allows a single character, either a digit or a hyphen # [\d-]+ allows for more than one character, but a minimum of one is required # ^[\d-]+$ the whole input string must match the regular expression RegexField(regex=r'^[\d-]+$', required=True, max_length=50)
has comment: http://stackoverflow.com/comment/127833102
answers question: http://stackoverflow.com/q/48520821
upvote count: 5
has comment: http://stackoverflow.com/comment/84036611
has comment: http://stackoverflow.com/comment/84036382

http://stackoverflow.com/a/48613388
answers question: http://stackoverflow.com/q/48613123
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48613123
type: Answer
score: 3
upvote count: 3
downvote count: 0
has body: The short answer is you don't The pings are handled by the MQTT Client network loop. You need to start this after connecting. There are 3 ways to run the loop: client.start_loop() This starts the network loop on a background thread client.loop_forever() This starts the network loop on the current thread and will block forever. client.loop() this executes one cycle of the network loop and must be called as part of your own loop.

http://stackoverflow.com/comment/84248734
score: 2
comment on: http://stackoverflow.com/q/48625937
type: Comment
has text: you can have the `website` function *return* the `url` to the main scope using `return url`. Then on the main scope, you need to assign the call of `website` to a variable like e.g., `my_url = website()`
type: QuestionComment

http://stackoverflow.com/comment/83998714
type: AnswerComment
comment on: http://stackoverflow.com/a/48502590
score: 0
type: Comment
has text: `print(filter(remNL,i))` gives me the same as `print(i)`, the newline characters are not removed

http://stackoverflow.com/a/48606814
score: 2
type: AcceptedAnswer
has body: You need to put %testcase directly after '%s.tar': testcase = "tc2" lists = ["1.1.1.1",'%s.tar' %testcase,"admin","admin","n",None] for i in lists: cmd = ("%s") %i print(cmd) Output: 1.1.1.1 tc2.tar admin admin n None
answers question: http://stackoverflow.com/q/48606792
has comment: http://stackoverflow.com/comment/84210320
upvote count: 2
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48606792

http://stackoverflow.com/q/48579947
has comment: http://stackoverflow.com/comment/84158844
tagged with: loops
has comment: http://stackoverflow.com/comment/84156227
type: Question
tagged with: matplotlib
type: UnansweredQuestion
tagged with: python
has body: I have a long script which is running in a loop over different files. I am having trouble with the save.fig command within the script. Although it saves the figure with the individual file name the plot data is always overwritten with the data from the last loop so for example I would end up with file 1 up to file100.png but each would appear the same. This is the plt.figure part of the script can anyone tell me what is wrong? fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='radar') ax.plot(theta+(lk&lt;0.0)*np.pi, np.abs(lk), color='r') ax.plot(theta+(rk&lt;0.0)*np.pi, np.abs(rk), color='b') ax.set_theta_offset(pi / 1) ax.set_theta_direction(-1) ax.set_rlabel_position(90) ax.set_varlabels(labels) for label in ax.get_xticklabels()[::2]: label.set_visible(False) plt.axvline(theta[mdpl], color='r') plt.axvline(theta[opp_dpl], color='r') plt.axvline(theta[mdpr], color='b') plt.axvline(theta[opp_dpr], color='b') idx = np.argwhere(np.diff(np.sign(lk - rk)) != 0).reshape(-1) + 0 plt.plot(theta[idx], lk[idx], 'ro') plt.savefig('{}.png'.format(name)) plt.show() plt.clf() Code starts with import of CSV into dataframes, then sets output directory and name: output_dir = r'C:\\path' for name, df in zip(allfiles, listofdf): df.to_csv(os.path.join(output_dir, name+ 'csv'), index=False) Then loop starts for df in listofdf: Indent maintained through to plot section.
tagged with: pandas
has comment: http://stackoverflow.com/comment/84159711
score: 0
has title: plt.save within loop over writing data
has comment: http://stackoverflow.com/comment/84164802
answer count: 0

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/48550546
tag name: python-packaging

http://stackoverflow.com/comment/84052969
score: 1
type: QuestionComment
has text: "scanline" is the uncompressed data which i got by applying the filter + appending the filter value to the filtered pixels
type: Comment
comment on: http://stackoverflow.com/q/48522422

http://stackoverflow.com/q/48553228
accepted answer: http://stackoverflow.com/a/48569771
has answer: http://stackoverflow.com/a/48569771
has comment: http://stackoverflow.com/comment/84135832
upvote count: 0
tagged with: python
score: -1
tagged with: dictionary
has title: How can I write part of dictionary value string as headers to csv file in python? Is there a better way?
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84134837
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84172353
has body: I have a dictionary that uses log file names as keys. When reading through a text file if it contains a value I was searching for, it saves the entire line as a new value in the list of values for that key(log file name). I.e Key: logFile0 Value: [Val1 5, Val2 3, Val3 72]. I want to output to a csv file the values as headers and which log file it was found and the value. Key | Value log1 | [Value_name Val_num], [Value1_name Val_num] log2 | [Value1_name Val_num], [Value3_name Valu_num] log3 | [Value2_name Val_num], [Value3_name Val_num] I want it to be displayed in the csv file where for each time the value was found in the log file, it's value is displayed as: Value_name | Value1_name | Value2_name | Value3_name log1 val_num | val_num | | log2 | val_num | | val_num log3 | | val_num | val_num Does anybody know how to do this? Or is there a better way to store all of this information and then display?
answer count: 1
tagged with: file
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/48569315
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84920671
favorite count: 0
has body: Hey Is there any possibility, that we can store all logs of our script running on pycharm in any text document?
tagged with: python
has comment: http://stackoverflow.com/comment/84134936
type: Question
score: 0
tagged with: pycharm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48569351
answer count: 1
has title: How to store Pycharm logs in any document

http://stackoverflow.com/comment/84017985
has text: That's not exactly a cvs file but you can it as one.
type: Comment
comment on: http://stackoverflow.com/q/48510248
score: 1
type: QuestionComment

http://stackoverflow.com/comment/84137406
score: 1
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga would `pandas` be able to handle it in a better manner?
comment on: http://stackoverflow.com/q/48570385

http://stackoverflow.com/q/48612210
has body: I have a webcam and it has button. In Windows, when I push that button it grabs image snapshot. But now I am on linux and I am using VLC to view video from my usb webcam "/dev/video0". I would like to use python to get signal from that button once pushed - I mean just to get this signal (no grab snapshot automatically). I tried to google it, but no luck. I don't want to use opencv or gstreamer to get video into new window, I just need to grab signal when button on webcam is pushed. Any idea how to get this signal please?
score: 2
type: AnsweredQuestion
tagged with: python-2.7
answer count: 1
has title: grab signal from webcam button
accepted answer: http://stackoverflow.com/a/48612797
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48612797
upvote count: 2
downvote count: 0
tagged with: python

http://stackoverflow.com/a/48527028
upvote count: 1
answers question: http://stackoverflow.com/q/48526788
score: 1
has body: You might want to change the figsize of plt.figure such as... import pandas as pd import seaborn as sns import matplotlib.pyplot as plt df = pd.read_csv('gm_2008_region.csv') df = df.drop('Region', axis=1) plt.figure(figsize=(12, 8)) sns.heatmap(df.corr(), square=True, cmap='RdYlGn') plt.show()
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84148994
has text: There is no statement about the actual error message, also your code is not runnable to reproduce the error. How people are supposed to know what is in `df`?
comment on: http://stackoverflow.com/q/48574347
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84057961
score: 0
has text: I can not reproduce the issue with the missing comma when I use a 2D-array just as @hpaulj suggested, however when I override the lines I also have no commas.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48530915

http://stackoverflow.com/q/48558665
type: AnsweredQuestion
tagged with: python
tagged with: mongodb-query
has comment: http://stackoverflow.com/comment/84113148
tagged with: mongodb
has comment: http://stackoverflow.com/comment/84113238
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: pymongo
has title: Pymongo query based on nested element in document
favorite count: 0
has comment: http://stackoverflow.com/comment/84113462
has body: I have data stored in MongoDB as following: { "payouts": { "entries": [ { "custom_payout_overwrite": false, "entry_name": "", "network_custom_payout_revenue_setting_id": 0, "network_offer_payout_revenue_id": 1, "payout_amount": 0.44, "payout_percentage": 0, "payout_type": "cpa" } ], "total": 1 } } I want to get only data which has payout_amount greater than 0. I have already tried filter_by = {"payouts.entries.payout_amount": {"$gte": 0}} data = db[collection_name].find(filter_by) But it's not working I gues. It's because entries is a list and I am not sure how to query further inside a list. Thanks.
type: Question
has answer: http://stackoverflow.com/a/48558916
accepted answer: http://stackoverflow.com/a/48558916

http://stackoverflow.com/comment/84144436
comment on: http://stackoverflow.com/a/48527889
score: 0
has text: @Newstudent14 this split your df by STA, and doing the dropna of the subset , restore the result into a list , if you want to combine it back to a dataframe doing pd.concate(l)
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48701862
downvote count: 0
answers question: http://stackoverflow.com/q/48520750
has body: EDIT (See the edit below) I found the answer. Since it would work for every two docker containers, I'm gonna write a general solution which one can always use. I have both docker images and containers in the same instance: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 14524d364cff (image) "java -jar ..." 40 hours ago Up 40 hours 0.0.0.0:5000-&gt;5000/tcp api-1 3392994ae3ac (image) "java -jar ..." 40 hours ago Up 40 hours 0.0.0.0:5002-&gt;5002/tcp api-2 Until here it's easy. Then, I wrote a docker-compose.yml version: '2' services: api-1: image: _name-of-image_ container_name: api-1 ports: - "5000:5000" depends_on: - api-2 api-2: image: _name-of-image_ container_name: api-2 ports: - "5002:5002" Then, in the docker file of api-1, for example. ... ENV API-2HOST api-2 ... and that's it. In my particular case, I have an api-1.conf with: accounts = { http = { host = "localhost" host = ${?API-2HOST} port = 5002 poolBufferSize = 100 routes = { authentication = "/authentication" login = "/login/" logout = "/logout" refreshTokens = "/refreshTokens" } } } and then I can easily make a request there and so are both docker containers communicated. Hope it can help someone. EDIT Since it can be complicated, I created a git project with just a dockerfile where you can use flask, nginx, uwsgi and tesseract. So there's no need to use both containers. docker-flask-nginx-uwsgi-tesseract
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48520750
type: AcceptedAnswer

http://stackoverflow.com/q/48531770
has comment: http://stackoverflow.com/comment/84059246
has comment: http://stackoverflow.com/comment/84059228
has title: Python Accessing Lists or Dicts from Names in String Variables
has answer: http://stackoverflow.com/a/48531846
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48531916
tagged with: python
has comment: http://stackoverflow.com/comment/84059305
score: 0
has body: I have a Python function that picks the name of an existing list at random from a text file of existing list names, and returns the chosen lists name as a string. Outside the function, the script should then print the contents of that list. What I'm having trouble with is figuring out how to (outside the function) print/access the list whose name is returned as a string by the function. If I create the lists outside the function: list_number_one = ['apples', 'oranges', 'pears'] list_number_two = ['bananas', 'grapes', 'unbridled existentialism'] and the function itself looks like: def pick_a_list(list1, list2): list_of_lists = [list1, list2] random_list = random.choice(list_of_lists) return random_list when I use the function... chosen_list = pick_a_list('list_number_one', 'list_number_two') if it returns the string 'list_number_one' as the randomly chosen list, how do I then (outside the function): print (chosen_list) and get in return: ['apples', 'oranges', 'pears'] In the actual script, assume my only option is taking string variables as the input for the list names, inconvenient as it may be. And the number of lists I'm working with is very large. I searched high and low for the answer but all of the Q&amp;A's I'm finding are about assigning key/value pairs based on variable input. Any help would be greatly appreciated, I don't want to just bomb the function with global variables.

http://stackoverflow.com/comment/84281851
score: 1
comment on: http://stackoverflow.com/a/48626425
type: Comment
has text: I would be in favour of execution based because if your DAG is dynamic, it's hard to inspect in the Web UI the previous tasks. It's due to the fact that the list of tasks of the DAG is defined on the current state and not what it was at the time of the execution
type: AnswerComment

http://stackoverflow.com/a/48568696
has body: So , I figured out why the mp3 files were not able to be played . It turns out that the text that was supposed to be converted to audio was all in CAPS .I changed the starting letter of each sentences to capital and remaining letters to small , the script worked fine . Assuming , sentence is the variable storing the information in all CAPS , use the following to convert in a manner described above - new_sentence="" for i in sentence.split(): new_sentence+=(i[0].upper())+(i[1:].lower())+" " print(new_sentence) Now , use the new_sentence in the above code , and it will work !
has comment: http://stackoverflow.com/comment/84135454
answers question: http://stackoverflow.com/q/48567772
score: 0
type: Answer

http://stackoverflow.com/comment/84230518
type: Comment
comment on: http://stackoverflow.com/a/48603250
type: AnswerComment
has text: `for i in ['first', 'second', 'third']:` is an explicit `for` loop, right?
score: 0

http://stackoverflow.com/comment/84294650
has text: If your database adapter accepts pyformat placemarkers, then you could use `sql = """SELECT * from orders where orderNumber = %(order)s and status = %(status)s and requiredDate = %(date)s and shippedDate = %(date)s"""` with `df1 = pd.read_sql_query(sql, cnx, params={'order':order, 'status':status, 'date':date})`. Or you could keep your `sql` the same and use `params=[order, status] + [date]*2`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48629483

http://stackoverflow.com/a/59449778
type: Answer
has body: Six days after you posted your question, the reverse_geocode module was updated to support Python 3.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48590140
upvote count: 2
has comment: http://stackoverflow.com/comment/105086495

http://stackoverflow.com/comment/84051536
score: 0
has text: This only maps the string name as the key and the placeholder object as a value right? As in there is no direct relationship between the string name and the class?
type: Comment
comment on: http://stackoverflow.com/a/48528110
type: AnswerComment

http://stackoverflow.com/comment/84000427
comment on: http://stackoverflow.com/q/48502667
type: QuestionComment
type: Comment
has text: Ok, I got it but I do not really understand what is the difference between resizing an image of 1000x2000 to 500x1000 than just simply taking the same image available on internet in resolution 500x1000. I think that these two are identical.
score: 0

http://stackoverflow.com/comment/84180516
has text: Possible duplicate of [Converting float to int](https://stackoverflow.com/questions/17874710/converting-float-to-int)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48591601

http://stackoverflow.com/q/48570269
tagged with: dataframe
tagged with: python
has body: I am trying to access next row of entry of dataframe at index01: ex: next row of df.ix[index01]? thanks
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
downvote count: 0
favorite count: 0
has title: How to access next row after dataframe ix?
type: Question
has answer: http://stackoverflow.com/a/48570346
type: UnansweredQuestion

http://stackoverflow.com/comment/84209548
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48572648
score: 3
has text: Simply look at the length of the work queue `ProcessPoolExecutor._pending_work_items`. If it's greater than zero, you have work items waiting.

http://stackoverflow.com/comment/84000724
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48501080
has text: @ThomasKühn I give it a try
type: Comment

http://stackoverflow.com/comment/84045913
type: AnswerComment
has text: This looks interesting. It would be great if you can add some more details how this works
score: 0
comment on: http://stackoverflow.com/a/48525387
type: Comment

http://stackoverflow.com/a/48630780
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/48606268
type: Answer
downvote count: 0
type: AcceptedAnswer
has body: Flask employs itsdangerous.Signer to do session data signing, the key used in signing is not the one you provided with SECRET_KEY config option but is derived with an HKDF. By default, Flask uses HMAC-SHA1 as HKDF algorithm, you only get 160-bits signing key, the length of SECRET_KEY makes no difference. In order to get 256 bits session signing key, you could extend flask.sessions.SecureCookieSessionInterface, change digest_method to SHA256, of course, you still need a lengthy random SECRET_KEY for enough entropy.
accepted answer of: http://stackoverflow.com/q/48606268

http://stackoverflow.com/a/68209345
score: 7
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/48580762
has body: We use algorithm based on the kind of dataset we have - Bernoulli Naive bayes is good at handling boolean/binary attributes, while Multinomial Naive bayes is good at handling discrete values and Gaussian naive bayes is good at handling continuous values. Consider three scenarios: Consider a dataset which has columns like has_diabetes, has_bp, has_thyroid and then you classify the person as healthy or not. In such a scenario Bernoulli NB will work well. Consider a dataset that has marks of various students of various subjects and you want to predict, whether the student is clever or not. Then in this case multinomial NB will work fine. Consider a dataset that has weight of students and you are predicting height of them, then GaussiaNB will well in this case.
type: Answer

http://stackoverflow.com/q/48593614
upvote count: 1
has comment: http://stackoverflow.com/comment/84185116
favorite count: 0
has comment: http://stackoverflow.com/comment/84185190
has body: I'm hoping someone can relieve me of my ignorance here: I'm using python 3.6.4 currently and I'm trying to convert strings to simple alphanumerics. I've got the how mostly sorted until I get to characters with diacritics. It involves football team names so I'm looking to convert, by way of example, 1. FC Köln to 1fckoln. So: import requests c = requests.get(the_url) content = c.text #code here to extract team name into variable 'ht' ht = simpname(ht) def simpname(who): punct = "' .-/\°()" the_o = 'òóôõöÖøØ' for p in punct: if p in who: who = who.replace(p, '') if the_o in who: who = who.replace(the_o, 'o') who = who.lower() return who (NB: code cut down for the example, I'm handling a, e, etc. in the same fashion) The only problem here is that, in my example, the text is arriving as 1. FC KÃ¶ln. I know I've got a character encoding issue, but I can't seem to get it to the right state. Can someone suggest a way around my issue? Solved! Thank you to @Idlehands and the commenters below for their advice. Below is the same code with the updates applied for future readers can see the difference. import requests incoming = requests.get(the_url) cinput = incoming.content cinput = cinput.decode('iso-8859-1') cinput = str(cinput) # more code, eventually extracts a team name under 'ht' ht = simpname(ht) ... def simpname(who): punct = "' .-/\°()" the_o = 'òóôõöÖøØ' # who is currently 1. FC KÃ¶ln who = who.encode('latin-1') # who becomes b'1. FC K\xc3\xb6ln' who = who.decode('utf-8') # who becomes '1. FC Köln' for p in punct: if p in who: who = who.replace(p, '') for an_o in the_o: if an_o in who: who = who.replace(an_o, 'o') who = who.lower()
has comment: http://stackoverflow.com/comment/84185095
has comment: http://stackoverflow.com/comment/84184718
score: 1
has comment: http://stackoverflow.com/comment/84185225
tagged with: python
tagged with: character-encoding
tagged with: python-3.6
has title: Text en/decoding issue
type: Question
has comment: http://stackoverflow.com/comment/84184611
has comment: http://stackoverflow.com/comment/84184454
has comment: http://stackoverflow.com/comment/84185236
has comment: http://stackoverflow.com/comment/84184772
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/517923
downvote count: 0
has comment: http://stackoverflow.com/comment/84185155

http://stackoverflow.com/q/48639401
tagged with: openssl
has comment: http://stackoverflow.com/comment/84275861
score: 0
has comment: http://stackoverflow.com/comment/84276217
tagged with: urllib2
type: Question
has title: SSL Error in python 2.7.5 version
has body: I tried to collect AWS guard duty logs using boto3 library, I was able to fetch logs using Python 3.6 version but was throwing up some annoying errors while using Python 2.7.5. The error message was: File "C:\Python27\lib\site-packages\botocore\retryhandler.py", line 359, in _check_caught_exception raise caught_exception botocore.vendored.requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol
answer count: 0
tagged with: python
type: UnansweredQuestion
tagged with: boto3
has comment: http://stackoverflow.com/comment/84276258
has comment: http://stackoverflow.com/comment/84314148
tagged with: amazon-web-services

http://stackoverflow.com/comment/84277724
has text: like `if d and d[-1]==somethng:`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48640292
score: 0

http://stackoverflow.com/q/48526884
has comment: http://stackoverflow.com/comment/84058068
answer count: 0
has comment: http://stackoverflow.com/comment/84049323
tagged with: django
has comment: http://stackoverflow.com/comment/84058171
tagged with: virtualenv
type: Question
has comment: http://stackoverflow.com/comment/84048819
has title: python virtualenv os.py not found although exists in system wide
type: UnansweredQuestion
tagged with: python
has body: With virtualenv version 1.10.1 I've created /var/www/vhosts/example.com/django-app-env/ however running it with the following passenger_wsgi.py import sys, os app_name = 'app' env_name = 'django-app-venv' cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/' + app_name) INTERP = cwd + '/' + env_name + '/bin/python' if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) sys.path.insert(0, cwd + '/' + env_name + '/bin') sys.path.insert(0, cwd + '/' + env_name + '/lib/python2.7/site-packages/django') sys.path.insert(0, cwd + '/' + env_name + '/lib/python2.7/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", app_name + ".settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I get... Traceback (most recent call last): File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 325, in &lt;module&gt; app_module = load_app() File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 62, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/var/www/vhosts/example.com/httpdocs/passenger_wsgi.py", line 10, in &lt;module&gt; if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) File "/var/www/vhosts/example.com/django-app-env/lib64/python2.7/os.py", line 312, in execl execv(file, args) OSError: [Errno 2] No such file or directory Its Python 2.7.5 Why?
score: 0
has comment: http://stackoverflow.com/comment/84048789

http://stackoverflow.com/q/48562563
duplicate of: http://stackoverflow.com/q/4357832
score: 0
answer count: 3
upvote count: 1
linked to: http://stackoverflow.com/q/4357832
downvote count: 1
linked to: http://stackoverflow.com/q/21024913
has answer: http://stackoverflow.com/a/48562742
has title: Python programming;
favorite count: 0
type: Question
has body: a=[1, 2, 3, -2, -5, -6, 'geo'] for I in a: if I == star: continue if I&lt;0: print('I=', I) I don't know how to let my program to distill the negative numbers and print only them avoiding strings. Please help me.
tagged with: python-3.x
tagged with: for-loop
type: UnansweredQuestion
tagged with: if-statement
has answer: http://stackoverflow.com/a/48562712
linked to: http://stackoverflow.com/q/21553327
tagged with: python
has answer: http://stackoverflow.com/a/48562705

http://stackoverflow.com/comment/84085600
score: 0
comment on: http://stackoverflow.com/q/48544581
type: Comment
type: QuestionComment
has text: No it tells me not found

http://stackoverflow.com/a/48551355
has comment: http://stackoverflow.com/comment/84099091
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48551297
answers question: http://stackoverflow.com/q/48551297
has comment: http://stackoverflow.com/comment/84099142
has body: IIUC df.groupby('tradingDay').apply(lambda x: sum(x['close'].mul(x['volume']))/np.sum(x['volume'])) Out[323]: tradingDay 2017-01-03 116.132927 dtype: float64
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/48574695
upvote count: 10
has comment: http://stackoverflow.com/comment/84146194
accepted answer of: http://stackoverflow.com/q/48574467
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48574467
has body: Images/pygame.Surfaces should usually be converted with the convert or convert_alpha methods of the pygame.Surface class. This will improve the performance dramatically. IMAGE = pygame.image.load('an_image.png').convert() IMAGE2 = pygame.image.load('an_image_with_transparency.png').convert_alpha() Also, load your images only once when the program starts and reuse them in your program. Loading them from the hard disk with pygame.image.load again is slow and should be avoided. If you need even more speed, you can use OpenGL in conjunction with pygame, but that means rewriting your rendering code and of course you would have to learn OpenGL first. Alternatively, you could check out some of the other game frameworks for Python.
score: 10
type: Answer

http://stackoverflow.com/q/48507048
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3277367
has comment: http://stackoverflow.com/comment/84008553
has comment: http://stackoverflow.com/comment/84008854
has title: multiple inheritance python
score: 0
has comment: http://stackoverflow.com/comment/84008821
favorite count: 0
tagged with: python-3.x
has body: I read Python's documentation and can't understand this piece of information class DerivedClassName(Base1, Base2, Base3): &lt;statement-1&gt; . . . &lt;statement-N&gt; For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy. Thus, if an attribute is not found in DerivedClassName, it is searched for in Base1, then (recursively) in the base classes of Base1, and if it was not found there, it was searched for in Base2, and so on. If it is new-style class, why does Python search recursively in the base classes of Base1 and not going to Base2 then Base3? class A(object): attr = 1 class B(A): pass class C(A): attr = 2 class D(B,C): pass x = D() print(x.attr)# 2 Sample from Mark Lutz's book. Python goes to D then B then C.
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48508476
downvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/48508138
tagged with: multiple-inheritance

http://stackoverflow.com/q/48521036
type: Question
has answer: http://stackoverflow.com/a/48521885
has body: I am writing a python script to help a friend's after-school program to send tuition bill to parents. I have student tuition in a {studentName, tuition} dict, and parent contacts in another {studentName, parentContact} dict, due to different attendance, each student's tuition number is different. I have the following function to intend to send individual email with different tuition info to individual parent. The problem I am having is, when I run my python script, from python shell, when I print it out, it looks like different email with different tuition numbers was intended for different parents, but the actual email each parent received was the same copy of the first student's tuition info. Here is my send email function: def send_mail(studentParentContact, studentTuition): msg=MIMEMultipart() msg['Subject'] = 'Your kid After-school Program Tuition Bill' msg['From'] = FLPEmail #after-school program's email address # Send the message via SMTP server s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login(username, PASSWORD) #after-school program gmail login for student in studentParentContact: ParentEmail=studentParentContact[student] tuition=studentTuition[student] msg['To'] = ParentEmail body="Hi, \nThe tuition for "+student+' is '+'$'+ str(tuition) msg.attach(MIMEText(body, 'plain')) text=msg.as_string() print FLPEmail, ParentEmail, text s.sendmail(FLPEmail, ParentEmail, text) s.quit() So instead of sending student A's tuition info to A's parent, student B's tuition info to B's parent, student C's tuition info to C's parent, the actual outcome right now is that it is sending A's tuition info to A and B and C's parents. Same tuition to all parents. How do I fix this? Thank you very much!
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84036978
has title: How to send different content email to different recipient in Python?
score: 1
tagged with: email
tagged with: python
favorite count: 0

http://stackoverflow.com/q/48569567
type: Question
answer count: 0
type: UnansweredQuestion
has title: Getting error in calculating hog features of multiple images and writing it in a text file
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/84147953
has comment: http://stackoverflow.com/comment/84148152
has comment: http://stackoverflow.com/comment/84148027
has comment: http://stackoverflow.com/comment/84147884
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/84147568
has comment: http://stackoverflow.com/comment/84148423
has comment: http://stackoverflow.com/comment/84147656
tagged with: python
has body: I am trying to calculate HOG feature vectors of multiple images and writing in a text file column wise .But I ma getting this error: np.savetxt('hog.txt',out) File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 132 0, in savetxt "Expected 1D or 2D array, got %dD array instead" % X.ndim) ValueError: Expected 1D or 2D array, got 3D array instead Here is my code: import cv2 import numpy as np winSize = (64,64) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = 4. histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 nlevels = 64 hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma, histogramNormType,L2HysThreshold,gammaCorrection,nlevels) #compute(img[, winStride[, padding[, locations]]]) -&gt; descriptors winStride = (8,8) padding = (8,8) locations = ((10,20),) out = [] for x in range(0,20): image = cv2.imread("{}.jpg".format(x),0) hist = hog.compute(image,winStride,padding,locations) #print (hist) #print (len(hist)) #print (len(hist[0])) out.append(hist) # print ("***********") np.savetxt('hog.txt',out)

http://stackoverflow.com/comment/84228720
type: AnswerComment
has text: more pythonic way... :)
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48582361

http://stackoverflow.com/q/48552580
downvote count: 1
has answer: http://stackoverflow.com/a/48552741
accepted answer: http://stackoverflow.com/a/48552741
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84101562
has title: JSON parse Python
has comment: http://stackoverflow.com/comment/84101715
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/48193502
has body: I have a json data that i got from VK. { "response": [{ "id": 156603484, "name": "Equestria in the Space", "screen_name": "equestriaspace", "is_closed": 0, "type": "group", "is_admin": 1, "admin_level": 3, "is_member": 1, "description": "Официально сообщество Equestria in the Space!", "photo_50": "https://pp.userap...089/u0_mBSE4E34.jpg", "photo_100": "https://pp.userap...088/O6vENP0IW_w.jpg", "photo_200": "https://pp.userap...086/rwntMz6YwWM.jpg" }] } So i wanted to print only "name" but when i did it it gave me an error TypeError: list indices must be integers or slices, not str My code is: method_url = 'https://api.vk.com/method/groups.getById?' data = dict(access_token=access_token, gid=group_id) response = requests.post(method_url, data) result = json.loads(response.text) print (result['response']['name']) Any idea how can i fix it? In google i found how to parse json with one array. But here is two or something P.S dont beat me so much. I am new in Python, just learning
tagged with: http://stackoverflow.com/tag/json
answer count: 1

http://stackoverflow.com/comment/84137540
has text: The entry contents changes ... a variable cannot change. You need to use the method entry.get() in every place you want the current value; not a variable.
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48570078

http://stackoverflow.com/q/48609276
favorite count: 0
tagged with: sklearn-pandas
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
has title: error when try to reshape array
has answer: http://stackoverflow.com/a/48673246
score: 1
has comment: http://stackoverflow.com/comment/84214920
answer count: 1
has body: i am using 2 separate data set one for training and other for testing import numpy as np import pandas as pd import matplotlib.pyplot as pt from sklearn.tree import DecisionTreeClassifier data = pd.read_csv("train.csv").as_matrix() data2 = pd.read_csv("test.csv").as_matrix() clf = DecisionTreeClassifier() # Dataset for training train_data = data[0:41999,1:] train_label = data[0:41999,0] clf.fit(train_data,train_label) # Dataset for Testing test_data = data2[0:27999,1:] actual_lable = data2[0:27999,0] index = 5 sample = test_data[5] sample.shape=(28,28) pt.imshow(255-sample,cmap='gray') print(clf.predict([test_data[5]])) pt.show() i am getting below error in line 35: sample.shape=(28,28) i am getting the following error: ValueError: cannot reshape array of size 783 into shape (28,28) but if i use values from the train_data then there are no errors i.e instead of using sample = test_data[5] if i use sample = train_data[5] i dont get any error. Could you please explain why the above code gives error? List item

http://stackoverflow.com/q/48624719
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/84246519
tagged with: logging
favorite count: 0
has body: In my &lt;my_module_name&gt; module I have this: import logging import my_module_name.log log = logging.getLogger(__name__) This works fine, but I would like to be able to override logging.getLogger() in /log.py so I can use: import my_module_name.log log = my_module_name.log.getLogger(__name__)
has answer: http://stackoverflow.com/a/48625366
score: 1
tagged with: python
has title: python override getLogger()
type: Question
tagged with: python-3.x
downvote count: 0
has comment: http://stackoverflow.com/comment/84247194

http://stackoverflow.com/comment/84038306
has text: `s = ss.accept(); ist = new InputStreamReader(s.getInputStream()); bufferedReader = new BufferedReader(ist); ` That should all be placed BEFORE the while loop. Please adapt your code.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48521184

http://stackoverflow.com/a/48598904
score: 3
has comment: http://stackoverflow.com/comment/84194683
type: Answer
has comment: http://stackoverflow.com/comment/84194635
upvote count: 3
has comment: http://stackoverflow.com/comment/84195566
has comment: http://stackoverflow.com/comment/84194738
downvote count: 0
has body: Instead of focussing too much on contracted forms, etc. We can focus on non-spaces (i.e. \S), and thus use it as: match = re.findall(r'\S+',fetch) This would then produce: &gt;&gt;&gt; fetch = "I don't want to count contracted forms like don't and can't as two words." &gt;&gt;&gt; import re &gt;&gt;&gt; re.findall(r'\S+', fetch) ['I', "don't", 'want', 'to', 'count', 'contracted', 'forms', 'like', "don't", 'and', "can't", 'as', 'two', 'words.'] Note that we also add the dot after words to dot. So we count sequences of non-spaces.
has comment: http://stackoverflow.com/comment/84197160
answers question: http://stackoverflow.com/q/48598874

http://stackoverflow.com/q/48589141
upvote count: 15
has title: Anaconda - UnsatisfiableError: The following specifications were found to be in conflict
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84179881
accepted answer: http://stackoverflow.com/a/48594778
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48594778
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84181982
tagged with: anaconda
linked to: http://stackoverflow.com/q/62288835
tagged with: python
has body: When I was trying to install a module 'pymc' through anaconda environments, it showed the error message as follows: UnsatisfiableError: The following specifications were found to be in conflict: blaze -> pyyaml -> python[version='>=2.7,<2.8.0a0'] -> vc=9 blaze -> pyyaml -> yaml -> *[track_features=vc9] pymc Use "conda info " to see the dependencies for each package. I am using Python 2.7.14, and I installed anaconda 1.6.9 on a Windows. I am new to Python. I first tried to use cmd to install the module pymc and I ran into a lot of problems such as the requirement for install g77 compiler on windows. After I got the compiler from MinGW and also installed the Microsoft Visual C++ Compiler for Python, I still cannot install the module because there came new errors. That is when I found there is pymc module listed in anaconda environment that I can add manually, but it showed this conflict error. I do not know whether the conflict comes from all those other stuff I installed above or not. Please HELP! Thanks!
tagged with: pymc
score: 15
has comment: http://stackoverflow.com/comment/126235503

http://stackoverflow.com/comment/84279245
has text: You can't if its read to a variable list or dict. Try to use multiprocessing next time to split the load over multiple "workers'.. a.k.a. processors. It now runs a serial process and not parallel.
comment on: http://stackoverflow.com/q/48641217
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48638805
has title: Python round to nearest .0125
answer count: 3
has answer: http://stackoverflow.com/a/48638894
upvote count: 2
has body: Does anyone know how to round a number to nearest .0125? For example there's a number 167.1131 then it needs to be converted to 167.1125. I have tried to do it with round but it rounds to 0.x.
downvote count: 0
has comment: http://stackoverflow.com/comment/84274586
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48639379
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/9232256
tagged with: rounding
possible better answer: http://stackoverflow.com/a/48639379
has answer: http://stackoverflow.com/a/48639218
tagged with: python
has comment: http://stackoverflow.com/comment/84274157
score: 2
accepted answer: http://stackoverflow.com/a/48638894

http://stackoverflow.com/q/48504914
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48526997
has comment: http://stackoverflow.com/comment/84020613
has title: log_loss in sklearn: Multioutput target data is not supported with label binarization
tagged with: python
has comment: http://stackoverflow.com/comment/84045588
has body: The following code from sklearn import metrics import numpy as np y_true = np.array([[0.2,0.8,0],[0.9,0.05,0.05]]) y_predict = np.array([[0.5,0.5,0.0],[0.5,0.4,0.1]]) metrics.log_loss(y_true, y_predict) produces the following error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-32-24beeb19448b&gt; in &lt;module&gt;() ----&gt; 1 metrics.log_loss(y_true, y_predict) ~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\sklearn\metrics\classification.py in log_loss(y_true, y_pred, eps, normalize, sample_weight, labels) 1646 lb.fit(labels) 1647 else: -&gt; 1648 lb.fit(y_true) 1649 1650 if len(lb.classes_) == 1: ~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\sklearn\preprocessing\label.py in fit(self, y) 276 self.y_type_ = type_of_target(y) 277 if 'multioutput' in self.y_type_: --&gt; 278 raise ValueError("Multioutput target data is not supported with " 279 "label binarization") 280 if _num_samples(y) == 0: ValueError: Multioutput target data is not supported with label binarization I am curious why. I am trying to re-read definition of log loss and cannot find anything that would make computations incorrect.
type: Question
possible better answer: http://stackoverflow.com/a/48526997
answer count: 2
tagged with: cross-entropy
upvote count: 2
score: 2
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48506172
has comment: http://stackoverflow.com/comment/84048892
favorite count: 0
has answer: http://stackoverflow.com/a/48506172

http://stackoverflow.com/comment/83987793
type: QuestionComment
has text: @Sraw Yes I know reuse is used to share variables. My question is, why they did `tf.get_variable_scope().reuse_variables()` right after defining the network for the first time and not beforehand?
score: 0
comment on: http://stackoverflow.com/q/48496612
type: Comment

http://stackoverflow.com/comment/84183712
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48574626
has text: Thank you, the O(n) solution was brilliant.
type: AnswerComment

http://stackoverflow.com/q/48535069
has body: I'm trying to enroll person profile pic's using kairos API. I have a following python code. My python script: #!/usr/bin/python3 import requests import io import http.client import base64 import json import glob, os from os.path import basename dir_path = "/home/Kairos/profiles/msc/" os.chdir(dir_path) for file in glob.glob("*.*"): img_path = file print(img_path) files = {'image': (img_path, open(dir_path + img_path, 'rb'), 'image/jpg', {'Expires': '0'})} headers = { 'app_id': "xxxx", 'app_key': "xxxxxxxxxxxxxxxxxxxxxx", } values_enrol = { 'subject_id':'msc', 'gallery_name':'mscGallary' } res = requests.post('https://api.kairos.com/enroll', headers=headers, files=files, data=values_enrol) print(res.content) But, I'm getting an error : "Errors": [ { "ErrCode": 1002, "Message": "subject_id one or more required parameters are missing" }, { "ErrCode": 1002, "Message": "gallery_name one or more required parameters are missing" } ] } What am I doing wrong here? Please someone help me. Thanks in advance.
has title: Kairos API : subject_id one or more required parameters are missing
has answer: http://stackoverflow.com/a/48623780
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48623780
answer count: 1
tagged with: kairos-api
has comment: http://stackoverflow.com/comment/84065807
tagged with: face-recognition
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/48560270
tagged with: python
has title: Django REST: Passing extra fields from connected models
score: 0
has body: I need to add additional fields that are not part of my model to the json response. Is this possible? The models are connected using multiple tables, but do not have a direct connection. models.py class Message(models.Model): body = models.TextField(max_length=500, blank=False) sender = models.ForeignKey(User) timestamp = models.DateTimeField(auto_now_add=True) conversation = models.ForeignKey(Conversation) serializers.py class MessageSerializer(serializers.ModelSerializer): conversation = serializers.ReadOnlyField(source='conversation.id') sender = serializers.ReadOnlyField(source='sender.id') # task = TaskSerializer(source='conversation__task_worker__task.id') # This commented code above is not working, but this is what I need. class Meta: model = Message fields = '__all__' So what I need, is to pass the value of task, which can be found by going back a few tables. E.g. if the current model is Message, I need to: Message -> Conversation -> Task_worker -> Task (Get this) My current json response is: { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "conversation": 1, "sender": 2, "body": "Hello There", "timestamp": "2018-01-31T17:48:19.680113Z" }, { "id": 3, "conversation": 1, "sender": 2, "body": "Can you do the task", "timestamp": "2018-02-01T09:39:24.797218Z" } ] } Ideally, I would like the following response: { "count": 2, "next": null, "previous": null, "conversation": 1, "task": 5, "any_extra_fields_key": 'value', "results": [ { "id": 1, "sender": 2, "body": "Hello There", "timestamp": "2018-01-31T17:48:19.680113Z" }, ] } The response is after (list view): GET /api/conversations/&lt;conversation-id&gt;/messages/ EDIT: added views.py class MessageList(generics.ListCreateAPIView): serializer_class = MessageSerializer def get_queryset(self): conversation = Conversation.objects.get(pk=self.kwargs['conv_id']) queryset = Message.objects.filter(conversation=conversation) return queryset def perform_create(self, serializer): conversation = Convers…
answer count: 1
tagged with: django-rest-framework
type: Question
has answer: http://stackoverflow.com/a/48562528
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/84048289
score: 0
comment on: http://stackoverflow.com/a/48523779
type: Comment
type: AnswerComment
has text: updated, let me know if this was enough. Could PM for more detail if it was not enough. I tried to make it more readable but failed.

http://stackoverflow.com/a/48556874
answers question: http://stackoverflow.com/q/48556239
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48556239
has body: I think you need filter out first 3 rows by iloc and then get mean: s = concatenated_df.iloc[3:].mean() Or is possible filter out first 3 rows by parameter skiprows in read_csv: df_from_each_file = (pd.read_csv(f,delim_whitespace=0, usecols=[1], skiprows=[1,2,3]) for f in all_files) concatenated_df = pd.concat(df_from_each_file, axis=1) s = concatenated_df.mean()
has comment: http://stackoverflow.com/comment/84143181
score: 0

http://stackoverflow.com/q/48571254
tagged with: python
has title: Why doesn't PyNacl work in IBM OpenWhisk?
score: 0
has answer: http://stackoverflow.com/a/48573594
tagged with: pynacl
type: Question
tagged with: ibm-cloud-functions
tagged with: openwhisk
tagged with: ibm-cloud
type: UnansweredQuestion
has body: Importing pynacl crashes when I upload a python zip to IBM Cloud Functions. Is that because it has C code instead of being pure python? How can I get around this?
answer count: 1

http://stackoverflow.com/comment/84258898
type: AnswerComment
has text: Worked like a charm.
comment on: http://stackoverflow.com/a/48617497
type: Comment
score: 0

http://stackoverflow.com/comment/84064415
has text: what does that mean?the API expects a request body with an array of Keyword types (string names or IDs)
comment on: http://stackoverflow.com/a/48534437
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48500240
has body: from tkinter import * import tkinter as tk class entr: def __init__(self): frm = tk.Tk() frm.title( "Myform" ) frm.geometry( "600x100" ) frm.config( bg = "blue" ) self.Var_text1 = StringVar() self.entry1 = Entry( frm, justify='right', textvariable=self.Var_text1) self.entry1.pack() self.entry1.bind('<KeyRelease>', lambda event : self.print_char(event) ) frm.mainloop() def print_char(self,event): print(event.char) e=entr() This code prints English letters as "u", But if I enter an Arabic letter like "ع" it is not printed
type: Question
has comment: http://stackoverflow.com/comment/127760520
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/127760523
tagged with: python
has title: print arabic char in python
score: 0
has comment: http://stackoverflow.com/comment/127760782
linked to: http://stackoverflow.com/q/45478440
has comment: http://stackoverflow.com/comment/127760710

http://stackoverflow.com/comment/84327184
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48644519
has text: @IsiahMeadows Thank you for reminding me to make the corrections. I have did some modifications to the answer as you have suggested. I have added a few explanations about the changes i have made and what it does in this code and in general. I hope M Suarez got the help he needed
type: Comment

http://stackoverflow.com/q/48603774
upvote count: 0
has title: convert a directory of csv.gz files to csv
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: python-requests
downvote count: 1
has answer: http://stackoverflow.com/a/48604067
accepted answer: http://stackoverflow.com/a/48604067
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: gzip
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84204213
has comment: http://stackoverflow.com/comment/84205164
has body: I've done that thing where I've confused myself beyond the point of any rational thought! I used requests in python 3.6 to download a bunch of files from a website. All of the said files are in csv.gz format. I would like to convert these files to just .csv format. Suppose I have 3 files in a folder: blahblahblah1.csv.gz blahblahblah2.csv.gz blahblahblah3.csv.gz The documentation regarding gzip compression states: import gzip with gzip.open('somefile.gz', 'rt') as f: text = f.read() I would like to do something along the lines of: import os import gzip for file in os.listdir(folder): convert file from csv.gz to .csv Thank you for any help!!
type: AnsweredQuestion

http://stackoverflow.com/comment/84270511
type: AnswerComment
has text: It looks like you may need to use the `--windowed` command on a mac to generate the .app file. It also appears as though the issue that you are experiencing is known to the PyInstaller developers: https://github.com/pyinstaller/pyinstaller/issues/1804 Sorry I can't be of further help.
type: Comment
comment on: http://stackoverflow.com/a/48627522
score: 0

http://stackoverflow.com/comment/84171123
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48587030
has text: first, your spacing is off. the second line needs to be indented 4 spaces. Second, you'd call it by calling it: "print string_length(this_string)" or "sl = string_length('this')"

http://stackoverflow.com/q/48530078
tagged with: python
has comment: http://stackoverflow.com/comment/84226225
has comment: http://stackoverflow.com/comment/84103512
accepted answer: http://stackoverflow.com/a/48629285
favorite count: 0
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84103585
upvote count: 0
has comment: http://stackoverflow.com/comment/84055678
linked to: http://stackoverflow.com/q/44076203
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84209344
has title: how to create PI chart in python
has answer: http://stackoverflow.com/a/48629285
has body: Hi Python Experts, PI chart is not coming up nicely because of long column names &amp; smaller slices. In this example, you can see that i have 6 buckets but in PI chart, only 5 slices are visible. Even text labeled with slices (top right) and on top are overlapping with each other. Table width is also not sufficient to fit column content. Could you please suggest what is the best way to deal with such situation ? I am new comer to python. I am using anaconda python 3.6. Code: import pandas as pd import matplotlib.pyplot as plt from pandas.tools.plotting import table raw_data = {'FLAG' : ['AT-NBBO', 'BETTER-THAN-NBBO', 'ONE-SIDED-QUOTE', 'OUTSIDE-NBBO', 'OUTSIDE-NBBO-DUE-TO-OVERSIZED-BUT-NO-EXECUTION-WITHIN-NBBO', 'OUTSIDE-NBBO-DUE-TO-OVERSIZED-BUT-SOME-EXECUTION_WITHIN_NBBO'], 'COUNT' : [10840, 8628, 84, 633, 153, 14] } df = pd.DataFrame(raw_data, columns = ['FLAG', 'COUNT']) plt.figure(figsize=(16,8)) ax1 = plt.subplot(121, aspect='equal') df.plot(kind='pie', y = 'COUNT', ax=ax1, autopct='%1.1f%%', startangle=90, shadow=False, labels=df['FLAG'], legend = True, fontsize=14) # plot table ax2 = plt.subplot(122) plt.axis('off') tbl = table(ax2, df, loc='right') tbl.auto_set_font_size(False) tbl.set_fontsize(20) plt.show() Output:
type: Question
tagged with: anaconda
tagged with: pandas
score: -2
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84254344

http://stackoverflow.com/comment/84116785
comment on: http://stackoverflow.com/q/48560201
has text: Your `img` is empty. Check file exists, and read it successfully.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48517784
answer count: 2
has answer: http://stackoverflow.com/a/48518406
has title: Fine control over h5py buffering
upvote count: 2
has comment: http://stackoverflow.com/comment/84030163
downvote count: 0
tagged with: python
has body: I have some data in memory that I want to store in a HDF file. My data are not huge (&lt;100 MB, so they fit in memory very comfortably), so for performance it seems to make sense to keep them there. At the same time, I also want to store it on disk. It is not critical that the two are always exactly in sync, as long as they are both valid (i.e. not corrupted), and that I can trigger a synchronization manually. I could just keep my data in a separate container in memory, and shovel it into an HDF object on demand. If possible I would like to avoid writing this layer. It would require me to keep track of what parts have been changed, and selectively update those. I was hoping HDF would take care of that for me. I know about the driver='core' with backing store functionality, but it AFAICT, it only syncs the backing store when closing the file. I can flush the file, but does that guarantee to write the object to storage? From looking at the HDF5 source code, it seems that the answer is yes. But I'd like to hear a confirmation. Bonus question: Is driver='core' actually faster than normal filesystem back-ends? What do I need to look out for?
has comment: http://stackoverflow.com/comment/84030518
accepted answer: http://stackoverflow.com/a/48518406
score: 2
type: AnsweredQuestion
tagged with: h5py
possible better answer: http://stackoverflow.com/a/49185722
has answer: http://stackoverflow.com/a/49185722
tagged with: hdf5
favorite count: 0
type: Question

android-actionbar
type: Tag
tag name: android-actionbar
tags question: http://stackoverflow.com/q/48488781

http://stackoverflow.com/a/48593765
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: something that prints out like your Item in Python would be expected to be a numpy array and can be most efficiently procesed in numpy as mentioned by cᴏʟᴅsᴘᴇᴇᴅ to make the printout 'array' inf, nan into the np objects, and the 'array' into a np.array: import numpy as np inf, nan = np.inf, np.nan a = np.array([[ 1, 2, 3, 43, 83, 92], [ 12, 54, 93, 23, 94, 83], [ 23, inf, inf, inf, inf, inf], [ 83, 33, 33, 83, 13, 83], [ 83, nan, 83, 73, 43, 43], [ 43, 83, 93, 22, 83, 54], [ 66, nan, 74, 84, 84, 75], [ 74, 44, 65, 6, 9, 7], [ 54, 9, 74, 754, 55, 74]]) then there are numpy functions just for these kind of operations a_infs = np.where(np.isinf(a)) a_infs Out[170]: (array([2, 2, 2, 2, 2], dtype=int64), array([1, 2, 3, 4, 5], dtype=int64)) a[a_infs] Out[171]: array([ inf, inf, inf, inf, inf]) a_nans = np.where(np.isnan(a)) a_nans Out[173]: (array([4, 6], dtype=int64), array([1, 1], dtype=int64)) a[a_nans] Out[174]: array([ nan, nan]) the two ca be combined a_bads = tuple(np.hstack((a_infs, a_nans))) a[a_bads] Out[184]: array([ inf, inf, inf, inf, inf, nan, nan]) a_bads Out[185]: (array([2, 2, 2, 2, 2, 4, 6], dtype=int64), array([1, 2, 3, 4, 5, 1, 1], dtype=int64)) or be converted to list and manipulated a_infs = np.array(a_infs).tolist() a_infs Out[175]: [[2, 2, 2, 2, 2], [1, 2, 3, 4, 5]] [*zip(*a_infs)] Out[176]: [(2, 1), (2, 2), (2, 3), (2, 4), (2, 5)]
answers question: http://stackoverflow.com/q/48592885

http://stackoverflow.com/comment/84186229
comment on: http://stackoverflow.com/q/48593644
score: 0
type: QuestionComment
type: Comment
has text: @ashleedawg, I upload my script as attached. It's not a large program. I remember I could run one or two times before. Now not work at all.

ruby-on-rails
tags question: http://stackoverflow.com/q/48518276
type: Tag
tag name: ruby-on-rails

http://stackoverflow.com/a/48532130
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84060218
has body: Just use the bisect module: import bisect def binarySearch(alist, loc): return [alist[bisect.bisect(alist, i) - 1] for i in loc] array = [5,10,15,20,25] loc1= [23,7,11] print(binarySearch(array, loc1)) Output: [20, 5, 10] Finding the index is simpler: def binarySearchIndex(alist, loc): return [bisect.bisect(alist, i) - 1 for i in loc]
has comment: http://stackoverflow.com/comment/84060129
has comment: http://stackoverflow.com/comment/84060251
has comment: http://stackoverflow.com/comment/84060174
type: Answer
has comment: http://stackoverflow.com/comment/84060071
accepted answer of: http://stackoverflow.com/q/48532003
has comment: http://stackoverflow.com/comment/84060230
answers question: http://stackoverflow.com/q/48532003
has comment: http://stackoverflow.com/comment/84060155
downvote count: 0

http://stackoverflow.com/q/48548937
accepted answer: http://stackoverflow.com/a/48549192
has comment: http://stackoverflow.com/comment/84094515
linked to: http://stackoverflow.com/q/10973362
tagged with: python
upvote count: 4
score: 4
tagged with: logging
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48549207
possible better answer: http://stackoverflow.com/a/48549207
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48549192
downvote count: 0
tagged with: stdout
tagged with: python-2.x
has body: Background I have a very large python application that launches command-line utilities to get pieces of data it needs. I currently just redirect the python launcher script to a log file, which gives me all of the print() output, plus the output of the command-line utilities, i.e.: python -m launcher.py &> /root/out.log Problem I've since implemented a proper logger via logging, which lets me format the logging statements more precisely, lets me limit log file size, etc. I've swapped out most of my print()statements with calls to my logger. However, I have a problem: none of the output from the command-line applications is appearing in my log. It instead gets dumped to the console. Also, the programs aren't all launched the same way: some are launched via popen(), some by exec(), some by os.system(), etc. Question Is there a way to globally redirect all stdout/stderr text to my logging function, without having to re-write/modify the code that launches these command-line tools? I tried setting setting the following which I found in another question: sys.stderr.write = lambda s: logger.error(s) However it fails with "sys.stderr.write is read-only".
favorite count: 0
type: Question
has title: Redirect all stdout/stderr globally to logger
answer count: 2

http://stackoverflow.com/comment/84151935
type: Comment
type: QuestionComment
has text: You should replace your use of globals with `return` calls. Every time you use `global` a kitten dies.
comment on: http://stackoverflow.com/q/48577794
score: 3

http://stackoverflow.com/comment/84042066
comment on: http://stackoverflow.com/q/48523575
score: 0
has text: Please post example contents for the two first files and the corresponding expected result file.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48642581
tagged with: python
accepted answer: http://stackoverflow.com/a/48667069
linked to: http://stackoverflow.com/q/32029403
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48667069
tagged with: list
answer count: 1
tagged with: overlapping
has title: Overlap of nested lists creates unwanted gap
favorite count: 0
linked to: http://stackoverflow.com/q/48651440
type: Question
tagged with: python-3.x
tagged with: overlap
score: 2
upvote count: 2
has body: I have a nest containing three lists which are being filled by a for-loop and the fill is controlled by if-conditions. After the first iteration it could look like the following example: a = [[1,2,0,0,0,0],[0,0,4,5,0,0],[0,0,0,0,6,7]] which, by condition, are not overlapping. After the second iteration new values are being appended to the corresponding nested lists. In order to make sure the lists are the same length I append zeros in each run. As soon as I set a condition so two lists overlap I get a gap the "size" of the desired overlap after the third iteration eventhough it should append directly to the corresponding list. Additionally if i set several overlaps (e.g. for each iteration) they add up so e.g. for three overlaps each the size of two i get a gap of six. Below you see what i mean w/o overlap w overlap (returns) w overlap (should return) 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 1 0 1 1 0 1 0 0 1 1 0 1 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 I have created a Pyfiddle here with the code I am using (it is the shortest I could create).It should give you the idea of what I am trying to achieve and what I have done so far. Further I have used this post to wrap my head around it but it does not seem to apply to my problem. EDIT: I think I have narrowed down the problem. It seems that due to the overlap the relevant list is being "pulled up" by the size of the overlap without adjusting the size of the remaining lists by the size of the offset. So the difference is being filled by zeros. EDIT2: My idea is to add the overlap/offset before the list is filled depending on the size of its predecessor. Since the start index depends on the the size of the predecessor it could be calculated using the difference of predecessor size and the gap. Basically in the parent for-loop for i in range(len(data_j)) I would add: overlap = len(data_j[i-1]['axis'])-offset Unfortunately another problem occured during the …
downvote count: 0

http://stackoverflow.com/a/48596155
accepted answer of: http://stackoverflow.com/q/48568649
has comment: http://stackoverflow.com/comment/127891000
has comment: http://stackoverflow.com/comment/84293614
has comment: http://stackoverflow.com/comment/84294633
type: Answer
has comment: http://stackoverflow.com/comment/84736219
has body: import pandas as pd df = pd.read_json("pywu.cache.json") df = df.loc[["local_time_rfc822", "weather", "temperature_string"],"current_observation"].T df.to_csv("pywu.cache.csv") maybe pandas can be of help for you. the .read_json() function creates a nice dataframe, from which you can easily choose the desired rows and columns. and it can save as csv as well. to add latitude and longitude to the csv-line, you can do this: df = pd.read_json("pywu.cache.csv") df = df.loc[["local_time_rfc822", "weather", "temperature_string", "display_location"],"current_observation"].T df = df.append(pd.Series([df["display_location"]["latitude"], df["display_location"]["longitude"]], index=["latitude", "longitude"])) df = df.drop("display_location") df.to_csv("pywu.cache.csv") to print the location in numeric values, you can do this: df = pd.to_numeric(df, errors="ignore") print(df['latitude'], df['longitude'])
score: 2
has comment: http://stackoverflow.com/comment/84292548
has comment: http://stackoverflow.com/comment/84248232
upvote count: 2
has comment: http://stackoverflow.com/comment/84297666
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84331567
has comment: http://stackoverflow.com/comment/84832102
has comment: http://stackoverflow.com/comment/84296111
has comment: http://stackoverflow.com/comment/84300387
answers question: http://stackoverflow.com/q/48568649
has comment: http://stackoverflow.com/comment/84338164
has comment: http://stackoverflow.com/comment/85020134
has comment: http://stackoverflow.com/comment/84670981
has comment: http://stackoverflow.com/comment/84747141
has comment: http://stackoverflow.com/comment/84346821

http://stackoverflow.com/comment/84029378
has text: @sebb Turns out I had not. I have added it now as you suggested, but it gives an error saying `Task orders.tasks.order_created[719e5c25-b8df-41ad-95bd-6c432d82566e] raised unexpected: error(61, 'Connection refused')`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48517318
score: 0

http://stackoverflow.com/q/48533192
tagged with: python
type: AnsweredQuestion
has body: So, I have just recently installed jgrasp on my computer. I have just selected the standard installation. For this particular instance, I am writing in python. However, whenever I try to run my code, I get an error message that the command python is not defined, and is in the wrong path. I have tried redirecting the path in startup settings as well as following troubleshooting guides about environmental variables on google, but it still does not work. Here is the error message: jGRASP wedge error: command "python" not found. This command must be in the current Working directory or on the current PATH to use this function. working directory is "C:\Acc CS". PATH is ";C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\QuickTime\QTSystem\". jGRASP: operation complete.
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48549561
favorite count: 0
type: Question
tagged with: jgrasp
has title: Error message with python in jGrasp about path
tagged with: path
accepted answer: http://stackoverflow.com/a/48549561

http://stackoverflow.com/comment/83984040
has text: What’s the problem? Can you report current output and compare to expected output?
score: 0
comment on: http://stackoverflow.com/q/48495372
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48575110
tagged with: http://stackoverflow.com/tag/docx
answer count: 2
has answer: http://stackoverflow.com/a/48575197
tagged with: python
type: AnsweredQuestion
score: 0
has body: I'm trying to get a random word file from a specified directory, but it returns nothing Here's the some part of the code. for filename in glob.glob(os.path.join(path, '*docx')): fl = [] fl.append(filename) return fl choice = random.choice(fl) doc = docx.Document(choice) print(doc.paragraphs[0].text) # There is a paragraph on the document starting on the first line so problem is not there. There is nothing wrong with the path. Eveything was working just fine when I was not trying to get only one random file instead of all the files. What am I doing it wrong? Is there any more efficient way of doing it?
tagged with: random
has answer: http://stackoverflow.com/a/48575267
accepted answer: http://stackoverflow.com/a/48575267
possible better answer: http://stackoverflow.com/a/48575197
has title: Why can't I get a random file from the directory?
tagged with: ms-word
type: Question

http://stackoverflow.com/comment/84172845
type: Comment
comment on: http://stackoverflow.com/q/48587691
type: QuestionComment
score: 0
has text: I understand, but what command is generating the exception?

http://stackoverflow.com/a/48634163
has comment: http://stackoverflow.com/comment/131900764
has body: I find the answer. Zip the lists into 'matches' variable and construct the template like this: template = Template(''' "Matches": { {% for key, team, time in matches %} "{{key}}": { "teams": "{{team}}", "time": "{{time}}" }, {% endfor %} } ''' ) print(template.render(matches=zip(keys, teams, times)))
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48632585

http://stackoverflow.com/comment/84205155
type: Comment
comment on: http://stackoverflow.com/a/48601774
score: 0
type: AnswerComment
has text: And tex2pix is not working, `Exception: pdflatex could not be run: PDF, PNG, and JPEG format modes cannot work`

http://stackoverflow.com/q/48600444
tagged with: flask-wtforms
has comment: http://stackoverflow.com/comment/84198681
has title: FlaskForm wtforms multiple input fields single submit
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/84221968
upvote count: 2
has answer: http://stackoverflow.com/a/48612723
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48612723
downvote count: 0
answer count: 1
has body: Using FlaskForm and SelectMultipleField, I'm creating a table of choices allowing for multiple selection to be ranked: 1, 2, 3, ... . In order to place the choices in a grid pattern on a table, I made each row it's own instance of SelectMultipleField. The submit button is only returning the values of the first instance of SelectMultipleField (dogs). How can I get the submit button to return values in all instances of SelectMultipleField? Here's the class in my forms module: class LPRForm(FlaskForm): party = ['Dogs', 'Cats', 'Rabbits', 'Birds'] dog = [('', 'D. Duke'), ('', 'R. Rusty'), \ ('', 'T. Tucker'), ('', 'R. Roger')] cat = [('', 'S. Shadow'), ('', 'M. Misty'), \ ('', 'P. Patch'), ('', 'P. Paws')] rabbit = [('', ''), ('', 'C. Clover'), ('', ''), ('', '')] bird = [('', 'P. Pikachu'), ('', 'S. Starburst'), \ ('', ''), ('', 'F. Flighty')] vote_dog = SelectMultipleField('District', choices=dog, option_widget=widgets.TextInput() ) vote_cat = SelectMultipleField('District', choices=cat, option_widget=widgets.TextInput() ) vote_rabbit = SelectMultipleField('District', choices=rabbit, option_widget=widgets.TextInput() ) vote_bird = SelectMultipleField('District', choices=bird, option_widget=widgets.TextInput() ) submit = SubmitField('Cast Ballot') Here's the relevant protion of the html file: {% for vote in form.vote_dog %} {% if vote.label != '': %} {{ vote(size="2") }} {{ vote.label }} {% endif %} {% endfor %} {% for vote in form.vote_cat %} {% if vote.label != '': %} {{ vote(size="2") }} {{ vote.label }} {% endif %} {% endfor %} {% for vote in form.vote_rabbit %} {% if vote.label != '': %} {{ vote(size="2") }} {{ vote.label }} {% endif %} {% endfor %} {% for vote in form.vote_bird %} {% if vote.label != '': %} {{ vote(size="2") }} {{ vote.label }} {% endif %} {% endfor %} {{ form.submit }} And the view module: @app.route('/lpr', methods=['GET', 'POST']) def lpr(): form = LPRForm() return render_template('lpr.html', title='Home', form=form)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84258775

http://stackoverflow.com/q/48531163
type: AnsweredQuestion
answer count: 2
has body: I am reading a text file in which one of the columns (3rd) contains date values in different date formats along with other data types (string, number, etc). I am identifying each unique date format in my input file and outputting the values for each date format to a text file. One of the date formats I am looking for in my input file is - Month dd, YYYY. For e.g. May 1, 2001. I am using the python strftime() function to search for the above date format in my file. However, my code provided below is only outputting date values with zero-padding. For e.g. May 01, 2001 But, I need my program to also find date values without the zero-padding that I know exist in my input file such as: May 1, 2001 2/4/2012 I have searched the forum for the solution, and most of it involved removing/replacing the zero. However, this does not solve my problem as I am searching the file for both zero padded and non zero-padded date values. I also tried adding the "-" sign after the "%" sign in my date format, but it did not work. I have provided my code below. Can anyone guide me in the right direction ? I am using Pycharm CE 2017.2 with the python 3.6.3 interpreter. My Code: # Identifying Month dd, yyyy date format from datetime import datetime import csv with open('file1.csv', 'r') as f_input, open('file2.txt', 'w') as f_output: csv_input = csv.reader(f_input) csv_output = csv.writer(f_output) for row in csv_input: for date_format in ['%B %d, %Y']: try: converted = datetime.strptime(row[3], date_format) csv_output.writerow([row[0], row[1], row[2], converted.strftime(date_format), row[4]]) except ValueError: pass
accepted answer: http://stackoverflow.com/a/48531862
score: 1
has answer: http://stackoverflow.com/a/48531862
downvote count: 0
has answer: http://stackoverflow.com/a/48531633
upvote count: 1
favorite count: 0
type: Question
has title: Identifying date values in a text file that do not have zero padding for month and day using python strftime()
possible better answer: http://stackoverflow.com/a/48531633
tagged with: strftime
tagged with: datetime
tagged with: python

http://stackoverflow.com/a/48578370
has comment: http://stackoverflow.com/comment/84153211
has comment: http://stackoverflow.com/comment/84153128
upvote count: 10
type: Answer
has body: To click on the Login button you can use either of the the following line of code : LinkText : driver.find_element_by_link_text("Login").click() CssSelector : driver.find_element_by_css_selector("a.login-btn &gt; span.btn-text").click() Getting more granular with the CssSelector you can also use the following line of code : driver.find_element_by_css_selector("a.login-btn[data-bind='click:loginSection.loginClick'] &gt; span.btn-text").click() Update : As you are seeing NoSuchElementException you can check this discussion
score: 8
has comment: http://stackoverflow.com/comment/84153177
downvote count: 2
accepted answer of: http://stackoverflow.com/q/48578336
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48578336

http://stackoverflow.com/a/48527471
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Okay, I've figured it out. Using my above code (in the Update section of my initial question), I made two changes. The first is right under the main Class structure: class Manifold(Tk.Tk): def __init__(self, *args, **kwargs): Tk.Tk.__init__(self, *args, **kwargs) #preload windows (avoids watching widgets load in real time): self.withdraw() #hide window self.after(0,self.deiconify) #unhide window asap The second is in the show_frame loop, with the preceding wait tuple (within the chunk starting with for F, geometry,etc. set to (10,10,10,10): def show_frame(self, page_name): #show a frame for the given page name frame, geometry, title, scaling, wait = self.frames[page_name] self.quit() #seems to be important in exiting out of previous window entirely self.geometry(geometry) #changes between window sizes self.title(title) #changes titles of windows self.resizable(*scaling) #changes ability of user to resize each window self.withdraw() frame.tkraise() #raises window to top self.after(wait,self.deiconify) #preload page before viewing self.update_idletasks() If anyone else ends up running into something like this, I hope this helps!
accepted answer of: http://stackoverflow.com/q/48492273
type: Answer
answers question: http://stackoverflow.com/q/48492273
score: 1

http://stackoverflow.com/q/48492155
has answer: http://stackoverflow.com/a/48492221
type: AnsweredQuestion
score: 0
tagged with: list
has body: I have this list: f = ['a','b','c',['me','you','him/her'], {'apples':430,'peaches':239,'bananas':839}, {'apples':123,'peaches':345,'bananas':536}] I know i can access each item in this list if i use slices. For example to access the first dictionary i would do a print(f[4]) #---&gt; {'apples': 430, 'peaches': 239, 'bananas': 839} To access a value of a key in the dictionary i do it like this: print(f[4]['apples']) #---&gt; 430 My question is how can i access the values of both apples keys (430,123) in those 2 separate dictionaries, to be displayed one after another automatically? Can someone please advise, on how to fix this? Thanks.
answer count: 2
has title: How to access multiple dictionaries values of the same keys from a list?
has answer: http://stackoverflow.com/a/48492231
accepted answer: http://stackoverflow.com/a/48492231
type: Question
possible better answer: http://stackoverflow.com/a/48492221
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/84313867
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48607096
has text: @LoneLearner, Can you check if you are facing the issue described here http://tarunlalwani.com/post/why-delayed-output-python-docker/?

http://stackoverflow.com/q/48612603
tagged with: python-asyncio
has body: I am in the process of making a discord bot using discord.py and asyncio. The bot has commands like kick and ban which obviously should not be available to normal users. I want to make a simple system which will detect what permissions the user's role has using ctx.message.author to get the user who sent the command. I do not want the bot to detect a specific role name as these vary across servers. I also prefer not to have multiple files for the bot to keep it simple. I have seen the discord.py documentation and various other sources but none contain examples of how to implement the various methods they talk about. As an example, here is a single command from my bot: async def kick(ctx, userName: discord.User): if True: #ctx.message.author.Permissions.administrator await BSL.kick(userName) else: permission_error = str('Sorry ' + ctx.message.author + ' you do not have permissions to do that!') await BSL.send_message(ctx.message.channel, permission_error) Where the if else statement is my attempt of doing this on my own. The #ctx.message.author.Permissions.administrator is commented out as it does not work and replaced with True for testing purposes. Thank you for any help and suggestions in advance.
has title: Permission System for Discord.py Bot
tagged with: discord
answer count: 4
has answer: http://stackoverflow.com/a/74454845
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/57443946
tagged with: discord.py
has answer: http://stackoverflow.com/a/57443946
downvote count: 0
score: 13
tagged with: python
favorite count: 0
upvote count: 13
accepted answer: http://stackoverflow.com/a/48613050
has answer: http://stackoverflow.com/a/52789887
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48613050

http://stackoverflow.com/a/48527083
type: Answer
has body: ord() gives the ASCII code. Read the whole file, iterate over each charter and and convert it: tuple(ord(x) for x in open(file_name).read()) Example File content of testing.txt: testing Now: &gt;&gt;&gt; tuple(ord(x) for x in open('testing.txt').read()) (116, 101, 115, 116, 105, 110, 103) Version for multi-line file stripping the newline charterers (as well as leading an trailing whitespace). File content of testing.txt: testing testing Code: &gt;&gt;&gt; with open('testing.txt') as fobj: ... res = tuple(ord(x) for line in fobj for x in line.strip()) &gt;&gt;&gt; res (116, 101, 115, 116, 105, 110, 103, 116, 101, 115, 116, 105, 110, 103)
answers question: http://stackoverflow.com/q/48527033
score: 0

http://stackoverflow.com/comment/84102810
has text: you can also use `assert y > x, "Second integer must be larger than first integer!"` after the `input` lines.
type: Comment
comment on: http://stackoverflow.com/q/48553036
score: 0
type: QuestionComment

http://stackoverflow.com/a/48532922
accepted answer of: http://stackoverflow.com/q/48526687
upvote count: 4
answers question: http://stackoverflow.com/q/48526687
type: AcceptedAnswer
downvote count: 0
has body: The problem is that the standard interpreter — CPython — is a stackful interpreter, i.e. every invocation of Python function results in recursive call inside the interpreter. So the Python FrameType objects are just views (.f_back is a read-only attribute for the good reason) of the C stack frames, there is no point to change the f_back pointer. If you really want to manipulate the stack, you will have to write a C module, like the greenlet module does. Goog luck!
type: Answer
score: 4

http://stackoverflow.com/comment/84204751
comment on: http://stackoverflow.com/q/48603998
type: QuestionComment
score: 0
type: Comment
has text: You could use `collections.deque`, using `pop` and `append` on different sides.

http://stackoverflow.com/comment/94139217
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48541040
score: 0
has text: I have the same issue. I want to save the file _on the google drive_. This way I can work with collaborators. @monamona, Even if I do this, python does not complain, but the file does not show up anywhere on my Google drive. I used the solution below, but it seems stupid to download a file locally, then have to upload it to get it back on Google drive. For one thing, that can't be automated.

http://stackoverflow.com/comment/84120449
score: 1
type: QuestionComment
has text: Do you want to delete elements from the existing list (actually a tuple, that can not be modifed), or create a new, filtered list of the other elements?
comment on: http://stackoverflow.com/q/48562470
type: Comment

http://stackoverflow.com/comment/84084913
type: AnswerComment
has text: Absolutely, I can find only `{{` in my templates. Or `{%` for chained placeholders. You're right, I'll edit that. Thanks :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48541016

http://stackoverflow.com/comment/84108575
comment on: http://stackoverflow.com/q/48556211
has text: @QHarr is VBA excels formula language? And I'll checkout xlWings. Thanks.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84151460
type: Comment
has text: That was an extraordinary amount of work. I really appreciate your time and help with this problem.
comment on: http://stackoverflow.com/a/48566474
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84266173
comment on: http://stackoverflow.com/q/48634622
type: Comment
type: QuestionComment
score: 8
has text: It is bad to post code or data as pictures. There is no way to copy and paste a picture into a code editor. So it will be much harder, and thus less likely, for someone to help. To get the most out of the site it is important to [ask good questions](http://stackoverflow.com/help/how-to-ask), that includes creating a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example.

http://stackoverflow.com/comment/84257835
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48629766
has text: It worked now! I changed the url in the .pypirc file to "upload.pypi.org/legacy/"

http://stackoverflow.com/q/48613481
has answer: http://stackoverflow.com/a/48613534
has answer: http://stackoverflow.com/a/48613983
tagged with: python
has body: I have the following dataframe: id number 1 13 1 13 1 NaN 1 NaN 2 11 2 11 2 11 2 NaN I want to find the first non-NaN value per id and mark it with a 1. The result should look like this: id number code 1 13 NaN 1 13 1 1 NaN NaN 1 NaN NaN 2 11 NaN 2 11 NaN 2 11 1 2 NaN NaN I tried the following command and then go from there: df["test"] = df.groupby("id")["number"].first_valid_index() It gives me the following error: Cannot access callable attribute 'first_valid_index' of 'SeriesGroupBy' objects, try using the 'apply' method Then I tried this: df['test'] = df.groupby("id")['number'].apply(lambda x: x.first_valid_index()) But this gives me just a column of Nats... Does anybody know how the problem could be solved efficiently?
score: 2
has title: Python: Groupby First Non NaN Value
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48613983
answer count: 2
tagged with: pandas
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48613534
favorite count: 0
has comment: http://stackoverflow.com/comment/84223779
type: Question

http://stackoverflow.com/comment/84083522
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48533238
type: Comment
has text: Could you show me how you would render a specific category on a django template (in html)?

postgis
tags question: http://stackoverflow.com/q/48592648
type: Tag
tag name: postgis

http://stackoverflow.com/q/48552343
downvote count: 0
score: 45
upvote count: 45
answer count: 7
linked to: http://stackoverflow.com/q/47949173
linked to: http://stackoverflow.com/q/15166941
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47894506
has answer: http://stackoverflow.com/a/48552490
has answer: http://stackoverflow.com/a/48552417
has answer: http://stackoverflow.com/a/48552581
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84101058
has comment: http://stackoverflow.com/comment/84101421
tagged with: http://stackoverflow.com/tag/html
has body: I have a number of python scripts that I have saved on my computer, out of curiosity I have created a html file that just has one button. Instead on going into the terminal and running python <path to script>, I would like to make it so when that button is clicked, is kicks off one of my python scripts. Is this possible/how can it be done? for example purposes we'll call the script to be run MYSCRIPT.py. I've done a little research but have come up with nothing promising. I'm aware the following code is incorrect but just for a starting point here is my html file.
tagged with: javascript
has comment: http://stackoverflow.com/comment/84101072
tagged with: python
has answer: http://stackoverflow.com/a/55058578
has comment: http://stackoverflow.com/comment/84101122
has comment: http://stackoverflow.com/comment/84101158
has comment: http://stackoverflow.com/comment/84101075
has title: How can I execute a python script from an html button?
linked to: http://stackoverflow.com/q/42601478
has answer: http://stackoverflow.com/a/48552560
has comment: http://stackoverflow.com/comment/84101096
has comment: http://stackoverflow.com/comment/84101190
has comment: http://stackoverflow.com/comment/84101077
has answer: http://stackoverflow.com/a/61077082
has comment: http://stackoverflow.com/comment/84101046
has comment: http://stackoverflow.com/comment/84101124
has answer: http://stackoverflow.com/a/53944884
has comment: http://stackoverflow.com/comment/84101090

algorithm
tags question: http://stackoverflow.com/q/48491412
tags question: http://stackoverflow.com/q/48538451
tags question: http://stackoverflow.com/q/48634190
tags question: http://stackoverflow.com/q/48546347
type: Tag
tag name: algorithm
tags question: http://stackoverflow.com/q/48512321
tags question: http://stackoverflow.com/q/48502586
tags question: http://stackoverflow.com/q/48574566
tags question: http://stackoverflow.com/q/48627247
tags question: http://stackoverflow.com/q/48614055
tags question: http://stackoverflow.com/q/48569024
tags question: http://stackoverflow.com/q/48492886
tags question: http://stackoverflow.com/q/48566905
tags question: http://stackoverflow.com/q/48535063
tags question: http://stackoverflow.com/q/48580625
tags question: http://stackoverflow.com/q/48620355
tags question: http://stackoverflow.com/q/48554542
tags question: http://stackoverflow.com/q/48631106
tags question: http://stackoverflow.com/q/48631113
tags question: http://stackoverflow.com/q/48629033
tags question: http://stackoverflow.com/q/48609590
tags question: http://stackoverflow.com/q/48515415
tags question: http://stackoverflow.com/q/48585820
tags question: http://stackoverflow.com/q/48574363
tags question: http://stackoverflow.com/q/48614165
tags question: http://stackoverflow.com/q/48523562
tags question: http://stackoverflow.com/q/48612549
tags question: http://stackoverflow.com/q/48504721
tags question: http://stackoverflow.com/q/48572552
tags question: http://stackoverflow.com/q/48643921
tags question: http://stackoverflow.com/q/48490799
tags question: http://stackoverflow.com/q/48566401
tags question: http://stackoverflow.com/q/48595023

http://stackoverflow.com/q/48606314
accepted answer: http://stackoverflow.com/a/48608309
tagged with: python-mock
tagged with: exception
tagged with: python-3.5
tagged with: python
linked to: http://stackoverflow.com/q/40736292
has body: This demo function I want to test is pretty straight forward: def is_email_deliverable(email): try: return external.verify(email) except Exception: logger.error("External failed failed") return False This function uses an external service, which I want to mock out. But I can't figure out how to throw an exception from external.verify(email) i.e. how to force the except clause to be executed. My attempt: @patch.object(other_module, 'external') def test_is_email_deliverable(patched_external): def my_side_effect(email): raise Exception("Test") patched_external.verify.side_effects = my_side_effect # Or, # patched_external.verify.side_effects = Exception("Test") # Or, # patched_external.verify.side_effects = Mock(side_effect=Exception("Test")) assert is_email_deliverable("some_mail@domain.com") == False This question claims to have the answer, but it didn't work for me.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73534861
possible better answer: http://stackoverflow.com/a/73534861
answer count: 2
upvote count: 7
score: 7
downvote count: 0
tagged with: python-unittest
has title: How to throw exception from mocked instance's method?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48608309

http://stackoverflow.com/comment/84156025
comment on: http://stackoverflow.com/q/48579159
score: 0
type: Comment
has text: I am resetting the default graph on each api call, because of which I am not able to preload my model. Is there a way in which I can use preloaded model in session with new graph
type: QuestionComment

http://stackoverflow.com/comment/84057846
type: QuestionComment
comment on: http://stackoverflow.com/q/48530970
has text: @juanpa.arrivillaga The code as it currently is produces 176501 individual lines; one `Line2D` object on a plot for sure costs much more than 8 bytes.
score: 0
type: Comment

http://stackoverflow.com/q/48605818
has title: Object oriented python: calling a class with method(self, *optargs) and receiving error "takes at most 2 arguments (4 given)"
score: 0
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/84208062
has comment: http://stackoverflow.com/comment/84208012
type: UnansweredQuestion
has body: I am working with a piece of python code that looks something like this: #script.py from module import moduleobject class classname(moduleobject): def __init__(self): pass def lookupFunction(self, **optargs): data =self.moduleobjectfunction(param1, param2, param3, **optargs) return data I want to return the results of lookupFunction() with my own parameters in **optargs, let's call it arg1. In my shell, I've written the following: from script import classname a = classname() a.lookupFunction(arg1) My goal is to return the results of self.moduleobjectfunction(param1, param2, param3, arg1), however, I am getting the following error: TypeError: moduleobjectfunction() takes at most 2 arguments (4 given) How do I interpret this? 3 parameters, param1, param2, param3 are hard-coded while I am only passing arg1-- I'm not sure where the issue is with argument mismatches.
has answer: http://stackoverflow.com/a/48613160
tagged with: python

http://stackoverflow.com/q/48613445
tagged with: function
type: UnansweredQuestion
tagged with: contextmanager
has comment: http://stackoverflow.com/comment/84224048
answer count: 1
has comment: http://stackoverflow.com/comment/84225070
favorite count: 0
has comment: http://stackoverflow.com/comment/84224856
has comment: http://stackoverflow.com/comment/84224435
tagged with: oop
has title: In python is there a way to make a function/class that behaves like a function and a context manager?
downvote count: 1
has body: In python is there a way to make a function/class that behaves like a function and a context manager? Note: that I need the function/class to return an object that doesn't have a __exit__ method and I cant change that object (that's why I am wrapping it). so just making a class with __enter__ and __exit__ won't work because I need it to also behave like a function. I have tried the contextmanager decorator: @contextmanager def my_context_man(my_str): my_str = 'begging ' + my_str yield my_str+' after func' print('end') And it worked perfectly within the context manger, but not as a function: a = 'middle' old_a = my_context_man(a) print('old_a', old_a) with my_context_man(a) as new_a: print('new_a', new_a) the output: old_a &lt;contextlib._GeneratorContextManager object at 0x0000000004F832E8&gt; new_a begging middle after func end while the desired output will be: old_a begging middle after func new_a begging middle after func end edit: The specific problem that i am having is with the psycopg2 module. I want to use a different context manager. and it returns a connection object. def connect(dsn=None, connection_factory=None, cursor_factory=None, **kwargs): *the connection code* return conn I am trying to change it so that people will be able to use it with my context manager but in a way that will not break code. I cannot change the conn object
tagged with: python
has answer: http://stackoverflow.com/a/48613532
score: -1
tagged with: python-decorators
type: Question
has comment: http://stackoverflow.com/comment/84223791
upvote count: 0
has comment: http://stackoverflow.com/comment/84224466

http://stackoverflow.com/a/48516092
type: Answer
has body: Try this: import html non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd) a = 'your string' print(html.unescape(a).translate(non_bmp_map))
score: 0
answers question: http://stackoverflow.com/q/48514039

http://stackoverflow.com/a/48628498
has body: Maybe you could use a main for loop. This is some explanation code. file1 = open("file1.txt", r).readlines() file2 = open("file2.txt", r).readlines() for i in range(0, len(biggest_file)): if file[i] == file[i]: print("The text on line:{} is the same in both files".format(i)) else: print("The text on line:{} is not the same in both files".format(i)) Just note this isn't working code this is just how the system should work.
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48628181
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48628181
type: Answer

http://stackoverflow.com/comment/84099590
score: 0
comment on: http://stackoverflow.com/q/48545076
type: Comment
type: QuestionComment
has text: @djk47463: that question uses a list of names, this one uses a list of indices. I retitled both questions to make the slight difference clear.

http://stackoverflow.com/comment/84038448
has text: @Clara Look at the answers here https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python
type: QuestionComment
comment on: http://stackoverflow.com/q/48521886
type: Comment
score: 1

http://stackoverflow.com/comment/84215675
type: QuestionComment
has text: `print(end1 + end2, end=' ')` or `print(end1 + end2, end3 + end4)`
comment on: http://stackoverflow.com/q/48609626
score: 0
type: Comment

http://stackoverflow.com/q/48625019
score: 2
has body: I'm designing a simple GUI with Tkinter composed of a ListBox (with Scrollbar) and a canvas (FigureCanvasTkAgg) to plot. The ListBox is a collection of variables (time series) that are drawn as a x-y plot upon selection. The layout is schematically: |---------------- Menu Bar --------------| |----------------------------------------| | |--- Frame 1-- | |------ Frame 2 ------| | |-- ListBox -- |^| | | | Item 1 |-| | | | Item 2 |-| Canvas | | | Item 3 |-| | | | Item 4 |-| ------------------- | | | Item 5 |-| Navigation toolbar | | |--------------|v|---------------------| |----------------------------------------| When the GUI is built, the Navigation Toolbar is absent and I have tried either with both pack() and grid() geometry managers. I apologize if the mistake is so evident but I'm not aware of what can be wrong. The minimal code is: import matplotlib from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from tkinter import * class Plot_tool(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.master.option_add('*tearOff', 'FALSE') self.master.title("Tool") self.options = [ i for i in range(50) ] # Some staff in ListBox self.pack(fill = BOTH, expand = 1) self.init_window() def init_window(self): menubar = Menu(self.master) self.master.config(menu = menubar) filemenu = Menu(menubar) filemenu.add_command(label = "Load") menubar.add_cascade(label = "File", menu = filemenu) # Frame 1 (ListBox and Scrollbar) framei = LabelFrame(self, text="frame", labelanchor="n") framei.pack(side="left", fill=Y) scrollbar = Scrollbar(framei) scrollbar.pack(side="right",fill=Y) self.items = Listbox(framei, yscrollcommand=scrollbar.set) self.items.pack(side="left", fill=Y) scrollbar.config(command = self.items.yview) self.items.insert(0, *self.options) # Frame 2 (Canvas and Navigation Toolbar) group2 = Frame(self) group2.pack(side="right") fig = Figure(figsize=(200,100)) se…
tagged with: tkinter
has title: Matplotlib NavigationToolbar widget is not displayed in Tkinter GUI
has answer: http://stackoverflow.com/a/48625275
upvote count: 2
tagged with: tkinter-canvas
answer count: 1
downvote count: 0
tagged with: tkinter-layout
favorite count: 0
type: Question
tagged with: matplotlib
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48626043
type: Answer
answers question: http://stackoverflow.com/q/48625782
has body: You're probably invalidating the first condition by the second "if" in the statement. I don't know python thus I'm not aware of any other conditional logic but it should be something like this: for i in range(0,5): if (i == 0 or i == 2): print("if i =", i) else: print("else i=", i)
score: 0

http://stackoverflow.com/a/48519302
type: AcceptedAnswer
score: 0
has body: I'd restructure it so each fare_class was a key in a given airline's dictionary. So Delta's dictionary would become 'Delta': { 'N': 0, 'E': 1, 'H': 1, 'K': 1, 'L': 1, 'M': 1, 'Q': 1, 'S': 1, 'T': 1, 'U': 1, 'V': 1, 'W+': 1, 'X': 1, 'A': 1.5, 'B': 1.5, 'C': 1.5, 'D': 1.5, 'G': 1.5, 'I': 1.5, 'P': 1.5, 'W': 1.5, 'Y': 1.5, 'Z': 1.5, 'F': 2, 'J': 2, }, The multiplier can then be obtained with multiplier = FARE_CLASS_MULTIPLIER_DICTIONARY[airline_name][fare_class]
accepted answer of: http://stackoverflow.com/q/48517177
type: Answer
answers question: http://stackoverflow.com/q/48517177
has comment: http://stackoverflow.com/comment/84060976

http://stackoverflow.com/comment/84050272
type: Comment
comment on: http://stackoverflow.com/q/48527646
type: QuestionComment
has text: Does `Comment` have a foreign key field to `Product`?
score: 0

http://stackoverflow.com/comment/84132955
type: Comment
type: QuestionComment
score: 0
has text: @DanielPryden It is an open source library, so modifying it isn't a problem. However, other programs reference `other_package.py`, so making a change would be bad for other programs who use the class as is. What would be the appropriate way to make a change to the class in question that only affects this program, but goes open source library wide? Meaning that other files from the library that use the class receive the changes only for this program.
comment on: http://stackoverflow.com/q/48567880

http://stackoverflow.com/comment/84165951
type: Comment
type: QuestionComment
has text: if for that reason the external key is in detalle, since several of them belong to a single venta, but when I want to update a sale through the venta, I have to call the details that refer to that venta and not a detail that is my problem
comment on: http://stackoverflow.com/q/48572925
score: 0

http://stackoverflow.com/comment/84206380
type: QuestionComment
comment on: http://stackoverflow.com/q/48604896
type: Comment
score: 0
has text: Have you tried [researching](https://stackoverflow.com/questions/37752903/valueerror-invalid-placeholder-in-string)?

http://stackoverflow.com/comment/84155023
score: 0
type: AnswerComment
has text: Works better than before, but the use of `dim_r` and `dim_c` isn't right for my case. I edited my original post with an example.
type: Comment
comment on: http://stackoverflow.com/a/48578832

http://stackoverflow.com/comment/84224623
comment on: http://stackoverflow.com/a/48613615
has text: i guess the same way with you Alex it relates the print behaviour thank you :)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48529762
answers question: http://stackoverflow.com/q/48529567
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48529567
score: 2
has comment: http://stackoverflow.com/comment/84055386
has comment: http://stackoverflow.com/comment/84055023
type: Answer
has body: As others have noted, the primary problem is that the break only breaks from the inner for loop, not from the outer while loop, which can be fixed using e.g. a boolean variable or return. But unless you want the "not registered" line to be printed for every line that does not contain the user's name, you should use for/else instead of if/else. However, instead of using a for loop, you could also just use next with a generator expression to get the right line (if any). while True: chosenUser = raw_input("Enter a username: ") with open("userDetails.txt", "r") as userDetailsFile: lineWithUser = next((line for line in userDetailsFile if chosenUser in line), None) if lineWithUser is not None: print "\n" print chosenUser, "has taken previous tests. " break # will break from while now else: print "That username is not registered." Or if you do not actually need the lineWithUser, just use any: while True: chosenUser = raw_input("Enter a username: ") with open("userDetails.txt", "r") as userDetailsFile: if any(chosenUser in line for line in userDetailsFile): print "\n" print chosenUser, "has taken previous tests. " break # will break from while now else: print "That username is not registered." This way, the code is also much more compact and easier to read/understand what it's doing.
upvote count: 2

http://stackoverflow.com/comment/83994342
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48500491
has text: This is a great start, I'll see if I can adapt it. The problem is that a key can have multiple values, representing vectors. For example `'*TM_ROW0': '1.0000', '0.0000': '0.0000'` should parse to `'*TM_ROW0': ['1.0000','0.0000', '0.0000']`

http://stackoverflow.com/comment/133177975
type: AnswerComment
has text: thanks @r.e.s. indeed `random.Random(b'1'*i)` with `i=20000` or `i=20001` do not seed the same random sequence, which I think should be the behavior in case of seed truncation at 20'000 bytes
comment on: http://stackoverflow.com/a/50808998
type: Comment
score: 0

http://stackoverflow.com/comment/84227501
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48527667
has text: alright, thanks, I put it into an array. but unless I'm missing something, this doesn't really do what I wanted help with. I'm trying to change certain values into NA depending on the other values in the row and this basically just prints out the same numbers as I initially imported.
type: AnswerComment

http://stackoverflow.com/comment/84421490
has text: no, it didn't work. now I use `wrapper_object()` method to get some wrapper and insert it into python list when initialize, use this python list control click . in this way runs well except can not get the widget status
type: QuestionComment
comment on: http://stackoverflow.com/q/48559538
type: Comment
score: 0

http://stackoverflow.com/comment/84128944
comment on: http://stackoverflow.com/q/48566418
score: 0
type: Comment
type: QuestionComment
has text: Also, if `quizwords == "1"`, you can just do `quizwords = answerChoice[index]` instead of `replace`, but is this really what you intended?

http://stackoverflow.com/q/48632452
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84262955
has body: I'm using openpyxl in Python to copy some data from a txt file into an Excel spreadsheet. The following code, however simple, is skipping every second line though, and is only writing to every other line in the spreadsheet. Can someone help and tell me what I'm doing wrong? line_index = 1 # To keep track of the current line's "index" in the file for l in f: line = l.split(",") # Transfer needed values into Spreadsheet, leaving the first two columns # empty so they can be populated later, because openpyxl doesn't support # easy insertion of columns. for i in range(len(line)): ws.cell(row=line_index, column=i+3).value = line[i] line_index += 1
has title: Writing data into an Excel spreadsheet - why does it skip every second line?
type: UnansweredQuestion
tagged with: openpyxl
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48643449
score: 1
has comment: http://stackoverflow.com/comment/84280503
tagged with: loops
has comment: http://stackoverflow.com/comment/84262723

http://stackoverflow.com/q/48491073
score: 1
answer count: 1
has title: Searching strings in lists of list for substring
has comment: http://stackoverflow.com/comment/83976446
favorite count: 0
type: Question
has body: I have a list made up of lists of strings: my_list = [[u'Port Name Status'], [u'Int1 London connected'], [u'Int2 Paris A disconnected'], [u'Port3 Paris A Backup disabled']] I thought about splitting each string by (" ") and creating tuples as I have worked with them before, but as some of the names are separated this doesn't work. I want to search each string for items in another list and if it exists pop it from my_list, my full code is my_list = [[u'Port Name Status'], [u'Int1 London connected'], [u'Int2 Paris A disconnected'], [u'Port3 Paris A Backup disabled']] remove_from_list = ['Port', 'connected'] for i in my_list: for j in remove_from_list: if j in i: my_list.pop(i) Aside from not working I also know my code isn't very pythonic, is there a better way with list comprehension to do this? I want only exact matches to be removed, so an item with disconnected stays but connected is removed.
accepted answer: http://stackoverflow.com/a/48491179
has answer: http://stackoverflow.com/a/48491179
has comment: http://stackoverflow.com/comment/83975396
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83975286
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/84182156
score: 1
comment on: http://stackoverflow.com/q/48588498
type: Comment
type: QuestionComment
has text: Can you post some sample data from your file? We can't run any of your code without your data, or sample data that approximates it.

http://stackoverflow.com/q/48515037
type: UnansweredQuestion
has body: MY OBJECTIVE : To read/write values to/from a large table by many users. My dataframe is a table of size 10000x3000 (approx). They contain integers/float only. They are nothing but stock prices updated every 1/3/5 minutes. Some simple stat calculations are performed and some columns in this table are updated. Rows grow but columns dont. Till now I used pandas dataframe to perform tasks and finally read/write to CSV files as a means of storage. I was the only user. Now I want to give access to others too. So this dataset needs to handle concurrent access. OPTION A : Many DBMS (MYSQL,MONGODB etc) have these(and many others) features built in and SQLAlchemy/DATASET simplify further.But I think it to be overkill as I have no complex queries to operate. I just pass **[i]**th row and **[j]**th column and fetch/write the corresponding 'value'. Even other users will do the same(read only access). OPTION B : Another idea of mine is a custom server taking in [i][j] and performing read write actions. Will I face any hurdles here ? So how do I go about making this dataset available to a larger audience ?
tagged with: python
has comment: http://stackoverflow.com/comment/84129078
tagged with: pandas
score: 0
tagged with: dataframe
tagged with: mysql
type: Question
has title: Pandas dataframe and concurrent access by several users
tagged with: mongodb
has comment: http://stackoverflow.com/comment/84031258
answer count: 0
has comment: http://stackoverflow.com/comment/84024832

http://stackoverflow.com/a/48632922
has body: I'm pretty sure you want to use a TypeVar: T = typing.TypeVar('T', int, str) # can be either int or str, but not both in a single call def f(*args: T) -&gt; None: pass
type: Answer
has comment: http://stackoverflow.com/comment/84267703
answers question: http://stackoverflow.com/q/48632608
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/a/48514338
has body: Easy way with transform counts_col2 = df.groupby("Col2")["Col2"].transform(len) counts_col3 = df.groupby("Col3")["Col3"].transform(len) mask = (counts_col2 &gt; 5) &amp; (counts_col3 &gt; 5) df[mask] output: Col1 Col2 Col3 Col4 0 1 apple tomato banana 2 1 apple tomato banana 3 1 apple tomato banana 4 1 apple tomato banana 5 1 apple tomato banana
has comment: http://stackoverflow.com/comment/84023264
score: 5
has comment: http://stackoverflow.com/comment/84023287
upvote count: 5
has comment: http://stackoverflow.com/comment/84023226
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84023326
has comment: http://stackoverflow.com/comment/111549829
has comment: http://stackoverflow.com/comment/111598365
has comment: http://stackoverflow.com/comment/104325555
answers question: http://stackoverflow.com/q/48513886

http://stackoverflow.com/a/48525379
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/48520254
type: Answer
has body: SSPI does not understand GSS-API-style SPNs. Use HTTP/xyz.abc.com. This will work.
upvote count: 3

http://stackoverflow.com/q/48618935
tagged with: list
tagged with: pandas
has comment: http://stackoverflow.com/comment/84234662
accepted answer: http://stackoverflow.com/a/48619115
answer count: 1
has comment: http://stackoverflow.com/comment/84234473
has answer: http://stackoverflow.com/a/48619115
has comment: http://stackoverflow.com/comment/84234722
has comment: http://stackoverflow.com/comment/84234476
favorite count: 0
has comment: http://stackoverflow.com/comment/84234491
type: Question
tagged with: numpy
has body: The problem is best described as an example (like most cases). I have the following example list: test = ['a','a','b','b','c','b'] I would like to get a list of pandas arrays with the length of the input list (6 in this case) where each array has length of the unique values in 'test' in that case 3 ('a', 'b' and 'c') and it contains zeroes and a single 1 corresponding to which value of the unique values (the order here obviously matters so it would be nice if the unique values are sorted or even better order would be as the values occur for the first time, in the example the two orders coincide) each element of the input list contains. The output would be a list of arrays looking like this for the example above: (1,0,0) (1,0,0) (0,1,0) (0,1,0) (0,0,1) (0,1,0) Additional example: test = ['a', 'g', 'b'] (1,0,0) (0,1,0) (0,0,1) I also need the order of the corresponding to the output unique values if arbitrary. It is best to be as the unique element is first encountered in the list. In this case it is 'a', 'g', 'b'. Thank you
upvote count: 2
has comment: http://stackoverflow.com/comment/84234481
has comment: http://stackoverflow.com/comment/84234438
downvote count: 0
tagged with: python
has title: how to derive binary array from a list of strings
has comment: http://stackoverflow.com/comment/84234622
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/48701199
type: Answer
score: 0
has body: The answer is based on @Xatyrian's comments buy using __all__ keyword in Python (a discussion on Stackoverflow can be found here, @Aaron Hall's comments are very good) Request 1: import all classes defined in src.module1 Please check @Marshal Hayes answer in this discussion. Basically, we are going to import the module using import module_name Request 2: import fundamental classes defined in src.module1 and src.module2 This can be done using the keyword __all__. --src |---__init__.py (1) |---module1 | |----- __init__.py (2) | |----- my_file1.py |---module2 | |----- __init__.py (3) | |----- my_file2.py --app |---my_application.py In (1) __init__.py we can denote which module we want to export ( we export the module if we want to export functions from this module). In (2) and (3) we denote which file we want to export (we export the file if we want to export functions from this file). Then in each function implementation file, for example, my_file1.py we can list all functions we want to export in __all__=[fun1,fun2,fun3] keyword. Then when we want to use the exported functions in application file, we simply import the top module name. In our example, we will do the following: import src src.fun1() src.fun2() print(dir(src)) : list all functions and modules in this package
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48536834
accepted answer of: http://stackoverflow.com/q/48536834

http://stackoverflow.com/q/48542273
upvote count: 1
tagged with: python-requests
favorite count: 0
tagged with: get
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48550323
type: Question
has title: Zoopla property listing API returns "Unknown location" using python and requests
tagged with: python-3.x
has body: I am trying to retrieve the property listing using Python 3 and the requests library. For some reason, the API returns error code 7 "Unknown location entered". The same parameters seems to work well on Zoopla's IO-Docs where results are returned. My request: import requests api_key = xxxxxxxxx r3 = requests.get("https://api.zoopla.co.uk/api/v1/property_listings",data = {'area':'Oxford','api_key':api_key})' The request returns the following: print(r3.request.url) --> https://api.zoopla.co.uk/api/v1/property_listings print(r3.request.body)' --> area=Oxford&api_key=xxxxxxxxx print("Status code:",r3.status_code)' --> Status code: 400 print(r3.content)' -->b'<?xml version="1.0" encoding="UTF-8" standalone="yes" >\n \n <error_code>7</error_code>\n <error_string>Unknown location entered.</error_string>\n \n' I don't understand why it returns "Unknown location" while the same parameters work fine on their website. Can anyone help, please? Thank you.
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/105404553
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48573937
has text: ^ won't work since its a datetime, and not a string
score: 1

http://stackoverflow.com/comment/84002844
has text: Just close the file, reopen it, read the contents, and print them!
score: 0
comment on: http://stackoverflow.com/a/48504285
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84192875
comment on: http://stackoverflow.com/q/48598086
type: Comment
type: QuestionComment
score: 0
has text: @Matthias it was a typo. I deleted it. I'm aware how loops work.

http://stackoverflow.com/q/48530936
accepted answer: http://stackoverflow.com/a/48532587
has body: I am trying to make a radar chart using this code : import matplotlib.pyplot as plt import numpy as np import sys import pandas as pd from math import pi import seaborn as sns import cv2 tab1 = np.random.rand(21) #Experiment tab1 =[(-10)*x for x in tab1] # ------- PART 1: Create background # number of variable cell_lines = range(0,22) N = len(range) # What will be the angle of each axis in the plot? (we divide the plot / number of variable) angles = [n / float(N) * 2 * pi for n in range(N)] angles += angles[:0] # Initialise the spider plot ax = plt.subplot(111, polar=True) # If you want the first axis to be on top: ax.set_theta_offset(pi / 6) ax.set_theta_direction(-1) # Draw one axe per variable + add labels labels yet plt.xticks(angles[0:], cell_lines, fontsize=20,fontname="Arial",fontweight='bold',linespacing=0) x=(3,6,9) plt.yticks(x,fontsize=20, fontweight='bold',fontname="Arial",linespacing=0) # Draw ylabels ax.set_rlabel_position(0) #plt.ylabel("%", fontsize=16) #plt.title("STUFF", fontsize=20, fontweight='bold', linespacing=2) # ------- PART 2: Add plots # Plot each individual = each line of the data # I don't do a loop, because plotting more than 3 groups makes the chart unreadable #print(control) # Ind1 #values=df.loc[0].drop('control').values.flatten().tolist() #values += values[:1] #ax.plot(angles, control, linewidth=5, linestyle='solid', label="control") #ax.fill(angles, control, 'b', alpha=0.1) ax.plot(angles, tab1, linewidth=5, linestyle='solid', label="tab1", color='blue') ax.fill(angles, tab1, 'b', alpha=0.1) # Add legend plt.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1), fontsize=20) plt.show() With this code, I'd like to be able to reverse the r-axis so that the outer most circle is 0 and the inner most circle is 1. I have no idea how to proceed about doing this. Even when I multiplied the entire data set by -1 and then graphed it (as I did below the experiment comment), the data only looked more skewed and it was missing the inner circles a…
has comment: http://stackoverflow.com/comment/84059488
has answer: http://stackoverflow.com/a/48532587
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84061996
has comment: http://stackoverflow.com/comment/84060822
has title: Reversing the r-axis on a radar chart matplotlib
answer count: 1
tagged with: plot
type: Question
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/comment/84256788
comment on: http://stackoverflow.com/q/48566181
has text: insert() will also work, I tested it [here](https://stackoverflow.com/questions/47820780/adding-widgets-dynamically-in-bokeh/47876820#47876820). But I honestly don't know if it will work with very complex layout, I don't see why it couldn't work...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48622412
has comment: http://stackoverflow.com/comment/103938013
score: 3
has body: XlsxWriter is designed only as a file writer. It cannot read or modify an existing Excel file. You can use openpyxl for file appending. #!/usr/bin/python3 from openpyxl import Workbook book = Workbook() sheet = book.active rows = ( (88, 46, 57), (89, 38, 12), (23, 59, 78), (56, 21, 98), (24, 18, 43), (34, 15, 67) ) for row in rows: sheet.append(row) book.save('appending.xlsx')
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/48621625
downvote count: 1

pivottable.js
tag name: pivottable.js
tags question: http://stackoverflow.com/q/48517928
type: Tag

http://stackoverflow.com/a/48627665
type: Answer
has comment: http://stackoverflow.com/comment/84252391
has comment: http://stackoverflow.com/comment/84252683
answers question: http://stackoverflow.com/q/48627303
score: 0
has comment: http://stackoverflow.com/comment/84252557
has comment: http://stackoverflow.com/comment/84252434
has comment: http://stackoverflow.com/comment/84252344
has comment: http://stackoverflow.com/comment/84261999
has comment: http://stackoverflow.com/comment/84252705
has comment: http://stackoverflow.com/comment/84252461
has comment: http://stackoverflow.com/comment/84252487
has comment: http://stackoverflow.com/comment/84252456
has comment: http://stackoverflow.com/comment/84252381
has body: You need to properly escape the characters, try the following. [^0-9a-zA-Z.,\-\*]+$

http://stackoverflow.com/q/48639646
tagged with: python
tagged with: virus
has comment: http://stackoverflow.com/comment/84281455
tagged with: http://stackoverflow.com/tag/zip
answer count: 0
upvote count: 2
score: 1
has body: I am creating a ZIP file with python ZipFile library. It contains 4 .txt files the content of each is just a string with some data for a report. It also contains 4 .pdf files which are created from a HTML template converted to pdf with wkhtmtopdf. The ZIP is then stored in binary in a PostgreSQL database. Then it is provided to the user for download. The problem I experience is that when the download is initiated most browsers treat the file as harmful (virus). zip_stream = io.BytesIO() with ZipFile(zip_stream, 'w') as myzip: myzip.writestr('file1.txt', report_data['file1_txt']) myzip.writestr('file2.txt', report_data['file2_txt']) myzip.writestr('file3.txt', report_data['file3_txt']) myzip.writestr('file4.txt', report_data['file4_txt']) myzip.writestr('file1.pdf', wkhtmltopdf.render_qweb_pdf(report_data['file1_html']) myzip.writestr('file2.pdf', wkhtmltopodf.render_qweb_pdf(report_data['file2_html']) myzip.writestr('file3.pdf', wkhtmltodpf.render_qweb_pdf(report_data['file3_html']) myzip.writestr('file4.pdf',wkhtmltopdf.render_qweb_pdf(report_data['file4_html']) values = { 'name': 'report.zip', 'type': 'binary', 'mimetype': 'application/zip', 'public': False, 'db_datas': base64.b64encode(zip_stream.getvalue()) } # Writing to database using custom ORM. attachment_id = self.env['ir.attachment'].create(values) # Creating download URL: download_url = '/web/content/' + str(attachment_id.id) + '?download=True' base_url = self.env['ir.config_parameter'].get_param('web.base.url')
downvote count: 1
favorite count: 0
type: Question
has title: ZIP file created with Python treated as virus by browsers
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84277187
tagged with: odoo

http://stackoverflow.com/comment/84255850
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48629413
score: 0
has text: orderNumber int64 orderDate object requiredDate object shippedDate object status object comments object customerNumber int64

http://stackoverflow.com/q/48540319
has body: I have the following elements in my navbar. &lt;div class="nav-languages"&gt; &lt;a class="navbar-brand active" id="langStyle" href="/language/it"&gt; ITA &lt;/a&gt; &lt;a class="navbar-brand" id="langStyle" href="/language/en"&gt; ENG &lt;/a&gt; &lt;/div&gt; After clicking on a links, I need to add the class "active" to the clicked element and remove the class "active" to the others. My jQuery is the following: $('.nav-languages a').click(function() { $('.nav-languages a').removeClass('active'); $(this).addClass('active'); }); Right now, soon after clicking, the clicked element correctly changes color becoming active, while the other turns to inactive. But as soon as the page ends to load, the situation goes back to previous state. I've read lots of answers to similar questions but no one helped me to solve my issue.. Please note that I'm totally new-by in jQuery &amp; js. Thank you for any help you could provide. EDIT: I'm using Django-Python urls.py: urlpatterns = [ url(r'^$', webprojects_home, name="homepage"), url(r'^language/(?P&lt;language&gt;[a-z\-]+)/$', language), ] and views.py: ### setting language session def language(request, language='it'): response = HttpResponse("setting language to %s" % language) response.set_cookie('lang', language) request.session['lang'] = language return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
has comment: http://stackoverflow.com/comment/84079300
has title: Set active class in nav bar with JQuery not working
accepted answer: http://stackoverflow.com/a/48566535
has comment: http://stackoverflow.com/comment/84084391
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/84078382
has comment: http://stackoverflow.com/comment/84075929
has comment: http://stackoverflow.com/comment/84076219
tagged with: python
has comment: http://stackoverflow.com/comment/84078261
has comment: http://stackoverflow.com/comment/84076163
has comment: http://stackoverflow.com/comment/84078176
has comment: http://stackoverflow.com/comment/84076316
has comment: http://stackoverflow.com/comment/84075864
answer count: 2
has comment: http://stackoverflow.com/comment/84075887
has comment: http://stackoverflow.com/comment/84076472
has comment: http://stackoverflow.com/comment/84084347
has comment: http://stackoverflow.com/comment/84075961
has answer: http://stackoverflow.com/a/48566535
tagged with: javascript
has comment: http://stackoverflow.com/comment/84076346
upvote count: 1
tagged with: jquery
possible better answer: http://stackoverflow.com/a/48540478
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84075724
type: Question
has answer: http://stackoverflow.com/a/48540478
has comment: http://stackoverflow.com/comment/84075777
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48496339
has comment: http://stackoverflow.com/comment/83985585
type: UnansweredQuestion
has body: I have been struggling with an example code that I use to practice and learn Python. Understanding the below's code is not hard, however, if I go line by line I am not sure what the following one does. course_running.add_student(self) How is it possible that we run add_student method of CourseRunning class to a parameter course_running (Student class, enrol method)? I would be very grateful if you can provide an explanation how that line of code works? The full code is provided below. class Student: def __init__(self, name, student_number): self.name = name self.student_number = student_number self.classes = [] def enrol(self, course_running): self.classes.append(course_running) course_running.add_student(self) class Department: def __init__(self, name, department_code): self.name = name self.department_code = department_code self.courses = {} def add_course(self, description, course_code, credits): self.courses[course_code] = Course(description, course_code, credits, self) return self.courses[course_code] class Course: def __init__(self, description, course_code, credits, department): self.description = description self.course_code = course_code self.credits = credits self.department = department self.department.add_course(self) self.runnings = [] def add_running(self, year): self.runnings.append(CourseRunning(self, year)) return self.runnings[-1] class CourseRunning: def __init__(self, course, year): self.course = course self.year = year self.students = [] def add_student(self, student): self.students.append(student) Thanks in advance! Igor
downvote count: 1
has answer: http://stackoverflow.com/a/48496766
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83986121
tagged with: composition
tagged with: python
has answer: http://stackoverflow.com/a/48496698
score: -1
has title: Python composition example
upvote count: 0
answer count: 2

http://stackoverflow.com/a/48556699
has body: I haven't checked this solution But you may try using this https://github.com/FacePlusPlus/facepp-python-sdk copy this file to your project https://github.com/FacePlusPlus/facepp-python-sdk/blob/master/facepp.py and then use it like that: from facepp import API api = API(key, secret) api.detection.detect(url=url)
has comment: http://stackoverflow.com/comment/84109373
has comment: http://stackoverflow.com/comment/84109673
has comment: http://stackoverflow.com/comment/84109432
answers question: http://stackoverflow.com/q/48556102
has comment: http://stackoverflow.com/comment/84110041
type: Answer
has comment: http://stackoverflow.com/comment/84113844
score: 0
has comment: http://stackoverflow.com/comment/84109620

http://stackoverflow.com/q/48491839
type: AnsweredQuestion
answer count: 2
tagged with: amazon-s3
has body: I wrote a python script to process very large files (few TB in total), which I'll run on an EC2 instance. Afterwards, I want to store the processed files in an S3 bucket. Currently, my script first saves the data to disk and then uploads it to S3. Unfortunately, this will be quite costly given the extra time spent waiting for the instance to first write to disk and then upload. Is there any way to use boto3 to write files directly to an S3 bucket? Edit: to clarify my question, I'm asking if I have an object in memory, writing that object directly to S3 without first saving the object onto disk.
downvote count: 0
possible better answer: http://stackoverflow.com/a/48837282
accepted answer: http://stackoverflow.com/a/48493537
favorite count: 0
score: 28
type: Question
has answer: http://stackoverflow.com/a/48837282
has answer: http://stackoverflow.com/a/48493537
upvote count: 28
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has title: Any way to write files DIRECTLY to S3 using boto3?

http://stackoverflow.com/comment/84286916
type: QuestionComment
has text: note that you can change `sts = os.waitpid(p.pid, 0)` => `sts = p.wait()`
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48644937

itk
tags question: http://stackoverflow.com/q/48543002
tag name: itk
tags question: http://stackoverflow.com/q/48561123
tags question: http://stackoverflow.com/q/48632372
type: Tag
tags question: http://stackoverflow.com/q/48547499

http://stackoverflow.com/comment/84124391
has text: show us what you have tried sofar, show us your code
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48563186
type: Comment

http://stackoverflow.com/comment/84323472
score: 1
type: Comment
type: QuestionComment
has text: I wouldn't recommend you using SQL for this, better go through the API, altering the DB yourself could cause trouble. What's the problem with multiple POST requests?
comment on: http://stackoverflow.com/q/48637985

http://stackoverflow.com/a/48571572
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/48571463
type: Answer
has body: With 2 pass awk you can do this: # when 2nd pattern is not found awk -v ps='A' -v pe='P' 'NR==FNR{if ($0 ~ ps) start=FNR; else if ($0 ~ pe) stop=FNR; if (stop) nextfile; else next} !stop || FNR&lt;start || FNR&gt;stop' file file G H A B C D N # when 2nd pattern is found awk -v ps='A' -v pe='D' 'NR==FNR{if ($0 ~ ps) start=FNR; else if ($0 ~ pe) stop=FNR; if (stop) nextfile; else next} !stop || FNR&lt;start || FNR&gt;stop' file file G H N About your 2nd part you can tweak this awk a bit with another parameter: awk -v n=2 -v ps='A' -v pe='D' 'NR==FNR { if ($0 ~ ps) start=FNR else if ($0 ~ pe) stop=FNR+n if (stop) nextfile else next } !stop || FNR&lt;start || FNR&gt;stop' file file
upvote count: 3

http://stackoverflow.com/q/48643968
upvote count: 2
has answer: http://stackoverflow.com/a/48644024
accepted answer: http://stackoverflow.com/a/48644024
downvote count: 0
type: Question
type: AnsweredQuestion
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I have two dataframes, one with more columns (but two of them are important) and the second with two columns. df1: col_a col_b 101 104 102 201 103 301 505 601 df2: col_a_a col_b_b 420 637 425 643 201 701 601 702 I need the next thing. Lookup at df1['col_b'] and if exist in df2['col_a_a'] then replace it with df2['col_b_b']. I have tried two ways: df1['col_b'] = np.where(df1['col_b'] == df2['col_a_a'], df2['col_b_b'], df1['col_b']) df1.col_b[df1.col_b == df2.col_a_a] = df2.col_b_b But both of them return me the same error: ValueError: Can only compare identically-labeled Series objects Desired output: col_a col_b 101 104 102 701 103 301 505 702
has answer: http://stackoverflow.com/a/48644465
possible better answer: http://stackoverflow.com/a/48644465
favorite count: 0
score: 2
tagged with: numpy
has title: Replace values in column with column values from other dataframe in Python
answer count: 2

http://stackoverflow.com/comment/84121908
score: 0
type: Comment
type: AnswerComment
has text: Sorry but the terms you keep on using clearly demonstrate that you do _not_ "understand well enough" and that youy would _really_ benefit from this little lecture.
comment on: http://stackoverflow.com/a/48562810

http://stackoverflow.com/a/48508293
type: Answer
has comment: http://stackoverflow.com/comment/84052251
answers question: http://stackoverflow.com/q/48507975
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48507975
has comment: http://stackoverflow.com/comment/84052700
has body: IIUC v=df1.melt('Date') v.variable=v.variable.astype(int) s=v.merge(df2,left_on='variable',right_on='num',how='left') v.loc[s.Date_x&lt;s.Date_y,'value']=0 v.set_index(['Date','variable']).unstack() Out[1211]: value variable 4001 4002 4003 4004 4005 Date 2017-01-01 151902 0 0 0 0 2017-01-02 157271 143598 0 0 0 2017-01-03 95806 138308 126034 0 0 2017-01-04 68874 91469 129751 116066 0

http://stackoverflow.com/comment/84221079
type: AnswerComment
comment on: http://stackoverflow.com/a/48611718
has text: He's probably talking about [this kind of backtrack](https://regex101.com/r/Ym5qGj/1). @WiktorStribiżew
type: Comment
score: 0

http://stackoverflow.com/a/48530953
has comment: http://stackoverflow.com/comment/84057685
downvote count: 0
answers question: http://stackoverflow.com/q/48530930
upvote count: 1
has comment: http://stackoverflow.com/comment/84057352
type: Answer
has comment: http://stackoverflow.com/comment/84058052
score: 1
has body: line.split() is a function call that returns a string. You then tried to call that string as a function with an argument of "\n". If you're trying to split on line breaks, you need line.split("\n")

http://stackoverflow.com/comment/84275617
type: Comment
has text: Possible duplicate of [Using sudo with Python script](https://stackoverflow.com/questions/13045593/using-sudo-with-python-script)
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48639609

http://stackoverflow.com/comment/84009958
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48507623
has text: I am sure the prices are present when the page is first loaded. There are references to javascript in the prettified html, though I am unsure as to whether that's the means by which it's adding the prices.
type: Comment

http://stackoverflow.com/comment/84003313
score: 0
comment on: http://stackoverflow.com/q/48504023
type: Comment
type: QuestionComment
has text: Right.. well I was kind of stuck with multiprocessing, so thanks for the hint.

http://stackoverflow.com/comment/84247962
type: QuestionComment
has text: That's not what classes are for. Put those methods into a module instead. (This isn't java!)
comment on: http://stackoverflow.com/q/48625470
score: 7
type: Comment

http://stackoverflow.com/comment/83973609
score: 0
has text: No where in the `Using this` block are you specifying the `dtype`. `numpy` does not infer a compound dtype like this from the elements of a tuple.
type: Comment
comment on: http://stackoverflow.com/q/48489978
type: QuestionComment

http://stackoverflow.com/comment/84022163
has text: I see this is different from your previous problem, but would you mind explaining the reasoning behind this output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48513721
score: 0

http://stackoverflow.com/a/48590043
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48589734
has body: Pythons Datetime pulls from the system time. So if the system is setup to use DST then you will be fine. If you don't or cant trust the system time then no build in function will be accurate. You will then need to have your program go out and pull time from another server.
score: -1
upvote count: 0

http://stackoverflow.com/comment/83987252
has text: Have you tried to step through the code with a debugger to see where the NaN values start to appear?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48497092
score: 0

http://stackoverflow.com/comment/84223957
type: Comment
comment on: http://stackoverflow.com/a/48613571
type: AnswerComment
has text: But in this case I know how to get the dates, just by iterating trough PayDayTable. What I don't know, is how to access the elements associates with each date by a for iteration.
score: 0

http://stackoverflow.com/comment/84036658
comment on: http://stackoverflow.com/q/48517353
type: QuestionComment
type: Comment
has text: I just figured out that in case of 'tensorflow' it is actually different case related to wheel and egg packages.
score: 0

http://stackoverflow.com/comment/84264800
has text: In a real life situation, I would use the longest list as `z` and make it a set, before I'd run this list comprehension. Would you like me to incorporate your comment, giving you credit for it?
type: Comment
comment on: http://stackoverflow.com/a/48633788
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84149492
comment on: http://stackoverflow.com/q/48566401
type: Comment
has text: Thanks Patrick Haugh, provided me good idea. but for me, the split should work for odd/even an to work with 10%, 30 % like that , not just equal half
type: QuestionComment
score: 0

restore
tag name: restore
tags question: http://stackoverflow.com/q/48593279
type: Tag

http://stackoverflow.com/comment/84050297
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48526580
has text: Yes, its not empty. Its size is 1.2 GB

http://stackoverflow.com/comment/84234267
has text: I assume you want the value of the dual variables in the optimal solution. The example https://github.com/coin-or/pulp/blob/master/examples/CG.py shows how to access these.
type: Comment
comment on: http://stackoverflow.com/q/48606094
score: 1
type: QuestionComment

http://stackoverflow.com/a/48656064
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48606686
has body: You can assign new data to source.data, try this: source.data = {'xs':[[10,20,30], [10,50,50,40]], 'ys':[[30,15,70], [10,50,50,50]]} push_notebook(nb)
answers question: http://stackoverflow.com/q/48606686
type: AcceptedAnswer

http://stackoverflow.com/q/48637560
has answer: http://stackoverflow.com/a/48637602
has body: I created a middleware which contain lot of functions to check something before getting the view. And i added the middleware to the setting.py, but it is for all requests. So, how can i make the middleware work for some requests, not all?
answer count: 1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: django
tagged with: python
has title: Python 3 Django - middleware for some request

flask-restless
type: Tag
tags question: http://stackoverflow.com/q/48498184
tag name: flask-restless

http://stackoverflow.com/q/48567935
has comment: http://stackoverflow.com/comment/84132260
has title: Get parameter(arg) count of builtin functions in Python
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 5
has comment: http://stackoverflow.com/comment/84132328
has answer: http://stackoverflow.com/a/48567936
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/84132669
has comment: http://stackoverflow.com/comment/84132121
tagged with: parameters
has comment: http://stackoverflow.com/comment/84132501
has body: I wrote my own c-module for Python and for a custom table in a documentation I need the number of parameters of the builtin-functions during runtime. There are functions in Python 2 like inspect.getargspec or functions in Python 3 like inspect.signature which support normal Python functions, but leave builtin-functions unsupported. There are two other community solutions so far: Parsing the doc-strings Parsing the original *.c file See answer for third approach In some cases the docstrings are outdated and/or it's hard to extract the argument count since the docstring can be any plain string. Parsing the original *.c file is a good approach as well, but you might not have access to it.
has comment: http://stackoverflow.com/comment/84132145
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84132547
accepted answer: http://stackoverflow.com/a/48567936
downvote count: 1
answer count: 1

http://stackoverflow.com/comment/83977263
score: 2
comment on: http://stackoverflow.com/q/48491984
type: Comment
type: QuestionComment
has text: Possible duplicate of [TypeError: 'int' object is not callable python](https://stackoverflow.com/questions/32478298/typeerror-int-object-is-not-callable-python)

http://stackoverflow.com/q/48638105
type: Question
has answer: http://stackoverflow.com/a/48638524
score: -2
tagged with: java
has comment: http://stackoverflow.com/comment/84272855
tagged with: python
tagged with: android
has comment: http://stackoverflow.com/comment/84277112
upvote count: 0
has body: I'm using Multipartentity for uploading image to python server. I got an error is Response from server: org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.0.104:5000 refused. Can explain anyone, why this come error? This is the backend task code: private class UploadFileToServer extends AsyncTask&lt;Void, Integer, String&gt; { long totalSize = 0; ProgressDialog progressDialog; @Override protected void onPreExecute() { // setting progress bar to zero progressDialog = new ProgressDialog(RegisterActivity.this); progressDialog.show(); } @Override protected String doInBackground(Void... params) { return uploadFile(); } @SuppressWarnings("deprecation") private String uploadFile() { String responseString = null; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(UPLOAD_URL); try { AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new AndroidMultiPartEntity.ProgressListener() { @Override public void transferred(long num) { publishProgress((int) ((num / (float) totalSize) * 100)); } }); String imagefilepath = null; String filemanagerstring = filePath.getPath();; String selectedImagePath = getPath(filePath); if (selectedImagePath != null) { imagefilepath = selectedImagePath; } else if (filemanagerstring != null) { imagefilepath = filemanagerstring; } else { Toast.makeText(getApplicationContext(), "Unknown path", Toast.LENGTH_LONG).show(); Log.e("Bitmap", "Unknown path"); } File sourceFile = new File(imagefilepath); // Adding file data to http body entity.addPart("aadharimage", new FileBody(sourceFile)); totalSize = entity.getContentLength(); httppost.setEntity(entity); // Making server call HttpResponse response = httpclient.execute(httppost); HttpEntity r_entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // Server response responseString = EntityUtils.toString(r_entity); } else { responseString = "Error occurred! Http Status Code: " + statusCode;…
type: UnansweredQuestion
downvote count: 2
answer count: 1
tagged with: flask
has title: unable to upload image from android to python flask server, show the error org.apache.http.conn.HttpHostConnectException in android
favorite count: 0

http://stackoverflow.com/q/48602625
tagged with: python-3.x
has title: Python2 versus Python3 post request
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84201990
score: 1
tagged with: python
tagged with: urllib
type: Question
accepted answer: http://stackoverflow.com/a/48602939
has answer: http://stackoverflow.com/a/48602939
answer count: 1
downvote count: 0
upvote count: 1
tagged with: django
has body: I've looked at seemingly all the other python3 urllib posts and nothing seems to work. I have a Django (v1.11.1, using Python2) application that should be accepting POST requests (e.g. sending it some JSON data); it works in python2 using urllib/urllib2, but with python3 (and urllib) I cannot get it to send a request that Django understands. Looking for some help in getting this sorted. My Django view function: def update_db(request):print dir(request) print request.POST return HttpResponse('Thanks for visiting.') Here's a working request in Python2: import urllib import urllib2 import json d={'foo': 1, 'bar': 2} data = urllib.urlencode(d) req = urllib2.Request(url, {'Content-Type': 'application/json'}) f = urllib2.urlopen(req, data=data) # works! Looking at the logs in my Django app I see that it understood the request: &lt;QueryDict: {u'foo': [u'1'], u'bar': [u'2']}&gt; Now, for Python3 here's my request method: import urllib.parse import urllib.request import json d={'foo': 1, 'bar': 2} data = json.dumps(d).encode('utf8') req = urllib.request.Request(url, data=data, headers={'Content-type': 'application/json'}) f = urllib.request.urlopen(req) And my Django log shows: &lt;QueryDict: {}&gt; Django also reports that request.method was indeed POST, but for whatever reason it's not understanding the actual JSON I'm sending as part of the post request. I also tried the requests library, as suggested in other threads, but nothing seems to work-- I'm always getting blank for the POST contents. Finally, I also tried ascii in the encode method (instead of the utf8 shown). Any tips? Is there a way I can inspect the outgoing request that urllib is actually making to the url? Thanks! EDIT: As mentioned in the comments below, I was not understanding the actual content I was sending. My working version for Python3 now reads: import urllib.parse import urllib.request d={'foo': 1, 'bar': 2} data = urllib.parse.urlencode(d).encode('utf8') req = urllib.request.Request(url, data=dat…
favorite count: 0

http://stackoverflow.com/a/48642167
upvote count: 2
has body: import numpy as np import pandas as pd df = pd.DataFrame([10, 20, 0, 30, 50], columns = ['Values']) df.Values[df['Values'] == 0] = np.nan df['Values'] = df['Values'].interpolate(how='linear') print(df) Values 0 10.0 1 20.0 2 25.0 3 30.0 4 50.0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84289277
accepted answer of: http://stackoverflow.com/q/48640593
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48640593
has comment: http://stackoverflow.com/comment/84283159

http://stackoverflow.com/a/48532269
answers question: http://stackoverflow.com/q/48531942
type: Answer
has body: First of all, the two approaches you've listed are not exactly equivalent - in the first you're only persisting the information about the total number of votes, whereas in the second one you also keep the information about the user who voted (and you might want to add additional relevant fields). Obviously, the first approach is more efficient since it won't require a join like the second one, but I'll be a bit careless here and say that you probably don't have to worry about that - don't forget what Mr. Knuth said which might be relevant here: We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%
score: 0

http://stackoverflow.com/comment/84286465
type: Comment
has text: Hi. Yes the context for precision is set.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48641168

http://stackoverflow.com/comment/84133445
comment on: http://stackoverflow.com/a/48566755
type: AnswerComment
has text: Wow, I wish I could give you more than just one upvote. One last question, in the `on_data_changed` method, how can I access the model's `table_data`? I wish to read it so I can pass it on to the rest of my program once editing of the table is done.
score: 0
type: Comment

http://stackoverflow.com/a/48578288
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You cannot just dump the content of a file into a YAML document (or documents), as on loading that content will get parsed. Such parsed content might be incorrect YAML, causing a loader error, or it might be correct YAML resulting in a data structure that is unlikely going to be turned exactly into the (string) content of the original file read. The latter because a YAML dumper normalizes indentation and most dumpers dispose of end-of-line comments. Files can also consist of binary data and that needs to be properly encoded, or, depending on the content of the file, escaped. Then the approach to put a # (as in your code) as a separator between path elements and filenames is not going to work if any of the paths or files has that valid filename character in their name. You should either use a reserved character (on Unix-likes the NUL character or /), or make things more transportable by splitting the path into segments and putting those segments plus the filename in a sequence of string scalars. To get all that to be correct YAML, make sure you load this information in a datastructure and then dump that datastructure using a YAML loader/dumper library instead of trying to write the file yourself. With Python your only real choice is ruamel.yaml (disclaimer: I am the author of that package) as e.g. the older PyYAML cannot dump a sequence as a key for a mapping, although that is perfectly valid according to the YAML specification. There are multiple ways to create the datastructure and you also need to decide if your file is going to contain one YAML document or multiple ones. If you want one document, I would represent the path+filename separated by the /, as a key into mapping and have the content of the files in literal block scalars form as values for those keys: import os import sys import ruamel.yaml root_dir = '.' data = ruamel.yaml.comments.CommentedMap() for root, directory_names, file_names in os.walk(root_dir): if root == root_dir: # don't do the file in the…
accepted answer of: http://stackoverflow.com/q/48561818
has comment: http://stackoverflow.com/comment/84154740
has comment: http://stackoverflow.com/comment/84155386
type: Answer
answers question: http://stackoverflow.com/q/48561818
score: 1

http://stackoverflow.com/comment/84153880
has text: What DebanjanB has suggested should work. Have you tried putting some delay just before that line? You may try like this `driver.find_element_by_link_text('Login').click()` as well. Btw, is that a slow loading page?
comment on: http://stackoverflow.com/q/48578336
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87962107
score: 0
has text: @guenkohl any chance that you forgot to transform the xaxis into a datetime object that plotly understands? The present sorting scheme seems to be alphanumeric IMO. You can use [this link](https://stackoverflow.com/questions/32034689/why-is-pandas-to-datetime-slow-for-non-standard-time-format-such-as-2014-12-31/32034914#32034914) to improve speed.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48628493

http://stackoverflow.com/comment/84006426
has text: Just a s a note the urllib2.urlopen() method sends a post request as default if you specify data to send.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48505794

http://stackoverflow.com/q/48489260
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83971395
has answer: http://stackoverflow.com/a/65391796
has body: I have this code: def funky_fun(lst): tmp = list(map(lambda x,y: x+y, lst[1:], lst[:-1])) print('check:', tmp, lst[1:] + lst[:-1]) return [lst[0]] + tmp + [lst[-1]] print(funky_fun(funky_fun([1]))) Here funky_fun([1]) returns [1, 1], while the second call (funky_fun([1, 1]) returns [1, 2, 1]. Do you understand why? Because lsr[1:] is [1], and lst[:-1] is also [1], so I would think it would print [1, 1, 1, 1], but tmp is [2]. It probably has something to do with the map function that I don't understand.
tagged with: built-in
score: 0
upvote count: 1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83971321
favorite count: 0
has comment: http://stackoverflow.com/comment/83971342
has comment: http://stackoverflow.com/comment/83971410
has title: How does python's map work with several arguments
type: Question
has comment: http://stackoverflow.com/comment/83971383

http://stackoverflow.com/comment/89957912
score: 0
has text: This is not an efficient way to feed data into Tensorflow.
type: AnswerComment
comment on: http://stackoverflow.com/a/48593610
type: Comment

http://stackoverflow.com/a/48597833
upvote count: 1
answers question: http://stackoverflow.com/q/48597758
has body: I didn't quite catch what you are trying to do, but assuming there is the list you provided us with: df = [1,2,3,'name 123'] And you want to remove only the '123' in the specific location, you could do: df[3] = df[3].replace(" 123","")
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/q/48599690
linked to: http://stackoverflow.com/q/47619074
downvote count: 1
has answer: http://stackoverflow.com/a/48599708
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84196219
duplicate of: http://stackoverflow.com/q/47619074
answer count: 1
score: -1
tagged with: global
accepted answer: http://stackoverflow.com/a/48599708
type: Question
upvote count: 0
has title: Global variable process
tagged with: tkinter
has body: I am creating a Reset button of a GUI by using the Tkinter. My purpose is that reset all values of labels to 0 or disappear. To reset value of labels, I defined the labels as global variable. labelP = None labelV = None labelH = None labelT = None Main function: def predict(): global labelP global labelV global labelH global labelT ... labelP = Label(mainframe, text = np.array(A[1,0]), width=5, font = 'Arial 10 bold').grid(column=2, row=5, sticky=W) labelV = Label(mainframe, text = np.array(A[1,1]), width=5, font = 'Arial 10 bold').grid(column=2, row=6, sticky=W) labelH = Label(mainframe, text = np.array(A[1,2]), width=5, font = 'Arial 10 bold').grid(column=2, row=7, sticky=W) labelT = Label(mainframe, text = np.array(A[1,3]), width=5, font = 'Arial 10 bold').grid(column=2, row=8, sticky=W) ... reset function: def reset(): global labelP global labelV global labelH global labelT labelP.delete() labelV.delete() labelH.delete() labelT.delete() Reset button: btn2 = Button(mainframe, text="Reset", command = reset).grid(column=1, row=9, sticky=W) Although I also tried labelP.config(), labelP.set(""), labelP.destroy() but I always get the error: AttributeError: 'NoneType' object has no attribute ... What should I define for the global variables? Thank you This is my code: https://gist.github.com/TonyS0n/8ee8db392196a405c2ef27ac44df3059
tagged with: user-interface
tagged with: python
tagged with: variables
linked to: http://stackoverflow.com/q/21592630

http://stackoverflow.com/comment/84183149
score: 1
comment on: http://stackoverflow.com/a/48592789
type: Comment
has text: You remember this one (-: `df2.name.map(dict(df1.values))`
type: AnswerComment

http://stackoverflow.com/comment/84311088
comment on: http://stackoverflow.com/a/48620823
has text: @user2997582 your question is not clear enough then, please be more specific. From what I got by reading your question `is_month_end` is exactly what you need
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48522081
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84039058
has comment: http://stackoverflow.com/comment/84039307
has comment: http://stackoverflow.com/comment/84040970
score: 0
has title: How to make django database such that the new objects will get id (last object's id +1) rather than (last deleted object's id+1)?
linked to: http://stackoverflow.com/q/1601697
tagged with: sqlite
answer count: 1
has body: I'm writing a django website with a sqlite database, I have a model in my website like this : class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date &gt;= timezone.now() - datetime.timedelta(days=1) Suppose I create Question object "What's up" and delete it and now create another Question object "HI" then "Hi" will get the id 2 not 1.But I want it to be 1 only.Is this possible? I m using django 1.8.7 and can't change the version as whole database is written in django 1.8.7. &gt;&gt; f = Question(question_text="What's up",pub_date=timezone.now()) &gt;&gt; f.id 1 &gt;&gt; f.delete() &gt;&gt; g = Question(question_text="Hi",pub_date=timezone.now()) &gt;&gt; g.id 2 Any help will be appreciated.Thanks in advance
has comment: http://stackoverflow.com/comment/84038894
has comment: http://stackoverflow.com/comment/84042201
type: Question
has answer: http://stackoverflow.com/a/48535559
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84039935

http://stackoverflow.com/comment/84064744
comment on: http://stackoverflow.com/a/48534594
type: Comment
has text: This is great. A key line from the documentation I find is this: *[The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.](https://docs.python.org/3/howto/sorting.html#key-functions)* So in a way it's like creating an ordered dictionary with keys sorted based on returned values from the function (`x*x`), and `sorted()`return only the values in order from this dictionary as a list. This makes a lot of sense to me.
type: AnswerComment
score: 1

http://stackoverflow.com/a/48550825
downvote count: 0
has comment: http://stackoverflow.com/comment/88927612
type: AcceptedAnswer
upvote count: 16
score: 16
has comment: http://stackoverflow.com/comment/88936505
accepted answer of: http://stackoverflow.com/q/48550201
type: Answer
answers question: http://stackoverflow.com/q/48550201
has body: Yes, train_on_batch trains using a single batch only and once. While fit trains many batches for many epochs. (Each batch causes an update in weights). The idea of using train_on_batch is probably to do more things yourself between each batch.

http://stackoverflow.com/q/48560138
has answer: http://stackoverflow.com/a/68063736
has answer: http://stackoverflow.com/a/69000412
has answer: http://stackoverflow.com/a/62752472
has answer: http://stackoverflow.com/a/48709863
has answer: http://stackoverflow.com/a/68557290
has answer: http://stackoverflow.com/a/79362416
favorite count: 0
type: Question
tagged with: jupyter-lab
has comment: http://stackoverflow.com/comment/136802791
has answer: http://stackoverflow.com/a/64603867
tagged with: plotly
has comment: http://stackoverflow.com/comment/91957328
has comment: http://stackoverflow.com/comment/84290762
has body: I am trying to create a Sankey chart in a Jupyter notebook, basing my code on the first example shown here. I ended up with this, which I can run without getting any errors: import numpy as npy import pandas as pd import plotly as ply ply.offline.init_notebook_mode(connected=True) df = pd.read_csv('C:\\Users\\a245401\\Desktop\\Test.csv',sep=';') print(df.head()) print(ply.__version__) data_trace = dict( type='sankey', domain = dict( x = [0,1], y = [0,1] ), orientation = "h", valueformat = ".0f", node = dict( pad = 10, thickness = 30, line = dict( color = "black", width = 0.5 ), label = df['Node, Label'].dropna(axis=0, how='any'), color = df['Color'] ), link = dict( source = df['Source'].dropna(axis=0, how='any'), target = df['Target'].dropna(axis=0, how='any'), value = df['Value'].dropna(axis=0, how='any'), ) ) print(data_trace) layout = dict( title = "Test", height = 772, width = 950, font = dict( size = 10 ), ) print(layout) fig = dict(data=[data_trace], layout=layout) ply.offline.iplot(fig, filename='Test') With the csv-file looking like this: Source;Target;Value;Color;Node, Label 0;2;2958.5;#262C46;Test 1 0;2;236.7;#262C46;Test 2 0;2;1033.4;#262C46;Test 3 0;2;58.8;#262C46;Test 4 0;2;5.2;#262C46;Test 5 0;2;9.4;#262C46;Test 6 0;2;3.4;#262C46;Test 7 It seems to run fine, with the various outputs looking right at a first glance, but the final output from ply.offline.iplot(fig, filename='Test') just shows a large blank field: The terminal looks like this after having run all the cells in the notebook once: Can someone please point me to where I am going wrong here? edit: I also posted this question on the plotly forums: https://community.plot.ly/t/no-output-from-plotly-offline-iplot/8086 -
tagged with: python
has comment: http://stackoverflow.com/comment/84116844
has answer: http://stackoverflow.com/a/77813877
has answer: http://stackoverflow.com/a/56777702
has answer: http://stackoverflow.com/a/76052314
tagged with: jupyter
has comment: http://stackoverflow.com/comment/84255622
answer count: 17
has answer: http://stackoverflow.com/a/56683056
has comment: http://stackoverflow.com/comment/84124328
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/55025112
linked to: http://stackoverflow.com/q/54936125
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84317239
score: 41
has answer: http://stackoverflow.com/a/53930462
has answer: http://stackoverflow.com/a/78794224
has comment: http://stackoverflow.com/comment/84269722
possible better answer: http://stackoverflow.com/a/62752472
has comment: http://stackoverflow.com/comment/84404216
upvote count: 41
has answer: http://stackoverflow.com/a/71121834
has answer: http://stackoverflow.com/a/71218731
has answer: http://stackoverflow.com/a/60666951
downvote count: 0
has comment: http://stackoverflow.com/comment/84418601
accepted answer: http://stackoverflow.com/a/48709863
has title: plotly.offline.iplot gives a large blank field as its output in Jupyter Notebook/Lab

http://stackoverflow.com/a/48548660
score: 0
answers question: http://stackoverflow.com/q/48548372
type: Answer
has body: You can also use pandas for this: # Convert DataFrame to Dictionary df_dict = df.to_dict() # Now convert it to list of values for key,value in df_dict: df_dict[key] = [value for key,value in df_dict[key].items()] # Or you can directly use: df_dict = df.to_dict("list") Hope this helps :)

http://stackoverflow.com/a/48579281
has body: Use: N = 5 def f(x): x = x.astype(float) x.index = range(N + 1 - len(x), N + 1) return x.reindex(range(1, N + 1)) df1 = df1.groupby(level=0)['d','c'].apply(f).rename_axis((None, 'day')).reset_index(level=1) print (df1) day d c 32 1 NaN NaN 32 2 NaN NaN 32 3 2.0 3.0 32 4 4.0 5.0 32 5 6.0 7.0 44 1 NaN NaN 44 2 NaN NaN 44 3 NaN NaN 44 4 NaN NaN 44 5 2.0 3.0 55 1 NaN NaN 55 2 NaN NaN 55 3 NaN NaN 55 4 4.0 5.0 55 5 6.0 7.0
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84154702
answers question: http://stackoverflow.com/q/48579238
score: 1
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48579238

http://stackoverflow.com/comment/84243814
type: Comment
score: 0
has text: I would like to avoid doing raw SQL since I need this to work with multiple database backends. I'm not even sure what it would look in raw sql either. Doing the annotation in memory won't work either since I probably will apply some filters on the annotations in the future too.
type: QuestionComment
comment on: http://stackoverflow.com/q/48621678

http://stackoverflow.com/a/48633749
downvote count: 0
has comment: http://stackoverflow.com/comment/84264566
accepted answer of: http://stackoverflow.com/q/48633729
type: Answer
has body: You can use itertools.product: import itertools x = (10,11,12,13,14,15) y = (10,11,12,13,14,15) z = (10,11,12,13,14,15) answer = 45 final_results = [i for i in itertools.product(x, y, z) if sum(i) == answer] Output: [(15, 15, 15)]
answers question: http://stackoverflow.com/q/48633729
type: AcceptedAnswer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/84264568

http://stackoverflow.com/comment/84205614
comment on: http://stackoverflow.com/a/48600194
has text: Would you please tell me the name of the package and the version number that fixes this? There are some packages I cannot update.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48640004
tagged with: python
tagged with: dictionary
tagged with: pyenchant
type: AnsweredQuestion
tagged with: spell-checking
has answer: http://stackoverflow.com/a/48640116
has body: I do not want to add a new dictionary to PyEnchant , instead I want to add single words to the dictionary with suggestions how to correct them. For example I have the code import enchant enchantdict = enchant.Dict("de_GE") suggested_words = [enchantdict.suggest(word) for word in ['Kunden','Nr','201']] where "Nr" is a short way of saying "Nummer" (meaning "Number" in English). I would like to add to the PyEnchant dictionary such, that it is able to suggest "Nummer" when it sees "Nr". How can I do this?
downvote count: 0
answer count: 1
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48640116
favorite count: 0
type: Question
has title: Add specific words to PyEnchant dictionary

http://stackoverflow.com/comment/84054310
type: QuestionComment
has text: Can you show the contents of `gifimages`?
score: 0
comment on: http://stackoverflow.com/q/48527429
type: Comment

http://stackoverflow.com/a/78297682
has body: Soumya Boral, you are using Keras 3 To use an older version: requirements.txt: keras==2.15.0 pip3 install -r requirements.txt Then the answer by bruno desthuilliers will work
answers question: http://stackoverflow.com/q/48561909
type: Answer
score: 0

http://stackoverflow.com/a/48633744
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84295173
answers question: http://stackoverflow.com/q/48633316
has comment: http://stackoverflow.com/comment/84307469
accepted answer of: http://stackoverflow.com/q/48633316
has body: Finally I caught the root cause. Httplib2 doesn't catch&amp;apply OS proxy setting. Requests does automatically catch&amp;apply OS proxy setting. That is why the HTTP request was rejected (NTLM Auth Failed in Proxy) when using Python Requests. So the solution is simple, ignore the OS proxy in the codes (For Python Requests lib). Another way is implement Proxy NTLM Auth, but it will be complicated, at least I didn't find out any related codes in the internet. Below codes works: import httplib2 h = httplib2.Http(".cache") h.add_credentials('xxx', 'xxxx') # Basic authentication resp, content = h.request("http://test:180/test.aspx", "GET", body="") print (content) Below codes are generated by PostMan, then it will work if ignore default OS proxy (two solutoins: disables gobal proxy setting or uses empty proxy instead). import requests url = "http://test:180/test.aspx" session = requests.Session() session.trust_env = False #disable OS proxy headers = { 'authorization': "Basic d3NndWVzdDpzbWMxxjMhQA==", 'cache-control': "no-cache", 'postman-token': "157e52fa-95f5-5287-9ee0-xxxxxxxx" } response = session.get(url, headers=headers) print(response.text) #use empty proxy instead proxies = { "http": None, "https": None, } response = requests.get(url, auth=HTTPBasicAuth('test', 'test'), proxies=proxies) print (response)
has comment: http://stackoverflow.com/comment/99103700
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84264589
has comment: http://stackoverflow.com/comment/84289567
type: AcceptedAnswer

http://stackoverflow.com/comment/84132634
type: AnswerComment
has text: I wanted those to be callable link, so whenever I press that link it will take to that respective website page,Nylon Calculus: Game Control and a new take on team metrics': 'https://fansided.com/2018/01/30/nylon-calculus-game-control-score/', like this
score: 0
comment on: http://stackoverflow.com/a/48567502
type: Comment

http://stackoverflow.com/q/48582675
tagged with: interpolation
score: 0
has title: Interpolate in Scipy, return polynomial
answer count: 1
tagged with: scipy
has answer: http://stackoverflow.com/a/48582974
type: Question
has body: I am using interp1d from scipy.interpolate for interpolating using a cubic polynomial. Is there any way in which I can extract the coefficients of the cubic polynomial?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48621821
upvote count: 1
downvote count: 1
has body: You can use the Fraction class to represent 0.2, and you can access the numerator and denominator as follows: &gt;&gt;&gt; from fractions import Fraction &gt;&gt;&gt; f = Fraction(1, 5) &gt;&gt;&gt; f.numerator 1 &gt;&gt;&gt; f.denominator 5 Hope it helps.
score: 0
answers question: http://stackoverflow.com/q/48620963
has comment: http://stackoverflow.com/comment/84241521
type: Answer
has comment: http://stackoverflow.com/comment/84241561

http://stackoverflow.com/q/48514970
answer count: 1
accepted answer: http://stackoverflow.com/a/48515088
has title: deleting duplication of list value in python
favorite count: 0
type: Question
has body: I have a list, list1 = [[1,4,0,0],[2,0,1,0],[9,8,4,0],[0,2,5,3]] and this list is like this; list1 =[[d[x][y] for y in key] for x in key] so when I write this list1 using writer.writerows(list1), its excel table shows this: 1 4 0 0 2 0 1 0 9 8 4 0 0 2 5 3 and as you know, its not symmetrical, I made a new list, list2 = [[d[x][y]+d[y][x] for y in key] for x in key] I could have made this table in the excel file: 2 6 9 0 6 0 9 2 9 9 8 5 0 2 5 6 but here comes the problem. I have to make a file that if x==y, in d[x][y] then its values should not be calculated. So I want my result to be like this: 1 6 9 0 6 0 9 2 9 9 4 5 0 2 5 3 FYI, I've used: d = defaultdict(lambda:defaultdict(int)) keys = sorted(d) how can I deal with this problem?
downvote count: 0
upvote count: 1
tagged with: python
tagged with: calculation
has answer: http://stackoverflow.com/a/48515088
type: AnsweredQuestion
tagged with: list
tagged with: http://stackoverflow.com/tag/csv
score: 1

http://stackoverflow.com/comment/83980062
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48493384
score: 0
has text: https://stackoverflow.com/questions/36438321/pyspark-rdd-find-index-of-an-element

http://stackoverflow.com/a/48602939
downvote count: 0
type: AcceptedAnswer
has body: Your first snippet is confusing. You claim to be sending JSON, but you're not; you're sending standard form-encoded data. This is what Django understands by default, anyway. There doesn't seem to be any reason why you wouldn't do the same in Python 3 though. Why serialise to JSON? Just do: data = urllib.parse.urlencode(d) And drop the headers in both circumstances, since you're not sending JSON. Finally, just use requests.
answers question: http://stackoverflow.com/q/48602625
type: Answer
has comment: http://stackoverflow.com/comment/84202837
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48602625

http://stackoverflow.com/comment/84109303
score: 0
type: Comment
type: QuestionComment
has text: @jezrael thanks, but now it looks like `0 hello, hello1, hello2 1 hello3, hello4, hello5` each line has two lists [[..]], ideally should be 1 [..], how should we make it as such?
comment on: http://stackoverflow.com/q/48556373

http://stackoverflow.com/comment/84244597
comment on: http://stackoverflow.com/a/48622910
type: AnswerComment
score: 0
has text: no i want to count frames that for example angry man occured.,(how insert in code?)
type: Comment

http://stackoverflow.com/comment/84055378
comment on: http://stackoverflow.com/a/48529964
type: Comment
score: 0
type: AnswerComment
has text: thanks for this! I didn't know about the apply function, that's cool. I have to use map because I'm actually using multiprocessing pool.map. I could use a loop there with apply_async on each. The full complexity I'm dealing with is that I have a list of lists of functions, the sub-list of functions needs to be called in order, but those altogether can be called in parallel. So I have `pool.map(lambda a: [b() for b in a], list_of_lists_of_functions)`

http://stackoverflow.com/comment/84261498
has text: @CorentinMar because the tutorial was written for an older version of OpenCV which only returns two values (as Jan mentioned, the function has changed in OpenCV 3). Note in the [3.0 documentation](https://docs.opencv.org/3.0-beta/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours) you can see that there are three return values and not two, [as there was in 2.4](https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours).
type: AnswerComment
comment on: http://stackoverflow.com/a/48628748
score: 0
type: Comment

http://stackoverflow.com/comment/84219602
has text: @JessMatthews, perhaps, change your title and question to: "find common items between 2 lists"
comment on: http://stackoverflow.com/q/48611525
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48528030
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48527420
accepted answer of: http://stackoverflow.com/q/48527420
has comment: http://stackoverflow.com/comment/84051164
type: Answer
has body: You can write a function def get_status(df): if df['TIME_1'] == df['TIME_MIN']: return df['STATUS_1'] elif df['TIME_2'] == df['TIME_MIN']: return df['STATUS_2'] elif df['TIME_3'] == df['TIME_MIN']: return df['STATUS_3'] elif df['TIME_4'] == df['TIME_MIN']: return df['STATUS_4'] else: return df['STATUS_5'] df['STATUS'] = df.apply(get_status, axis = 1) Or use a very-nested np.where, df['STATUS'] = np.where(df['TIME_1'] == df['TIME_MIN'], df['STATUS_1'],\ np.where(df['TIME_2'] == df['TIME_MIN'], df['STATUS_2'],\ np.where(df['TIME_3'] == df['TIME_MIN'], df['STATUS_3'],\ np.where(df['TIME_4'] == df['TIME_MIN'], df['STATUS_4'], df['STATUS_5']))))
score: 12
upvote count: 12

http://stackoverflow.com/comment/84249965
comment on: http://stackoverflow.com/a/48626452
type: AnswerComment
score: 0
has text: @JH_EARTH You can check pivot , also , if pivot you need 3 column rather than 2
type: Comment

http://stackoverflow.com/comment/84284804
has text: Interestingly, the tox.ini file suggests the tests get run against 3.5: https://github.com/openstack/pyghmi/blob/master/tox.ini#L2
score: 0
comment on: http://stackoverflow.com/q/48642928
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48494831
score: 0
possible better answer: http://stackoverflow.com/a/48494865
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48494858
has body: def step(g, m, n): notstorage=[] actualvalues =[] for i in range(m, (n+1)): for primechecker in range(2,i): if i % primechecker == 0: notstorage.append(i) for value in range(m, (n+1)): if (value) and (value+g) not in set(notstorage): actualvalues.append(value) actualvalues.append(value+g) break return(actualvalues) In the above code I'm trying to figure out which numbers are prime and create a list that checks if there are two prime numbers separated by a certain number (g). I'm having issues because for some reason the number 303 is being returned as a prime number when it clearly is not since it is divisible by 3.... I'm not sure why the code isn't working properly? When I input: step(4,300,400) I am expecting an output of (307,311) since those are the first 2 prime numbers that are 4 numbers apart but instead I get a return of (303, 307) Not sure what I've done wrong?
has title: Python 'not in' operator not working correctly?
has answer: http://stackoverflow.com/a/48494858
tagged with: python
has answer: http://stackoverflow.com/a/48494865
tagged with: definitions
answer count: 2
tagged with: iterator
tagged with: for-loop

http://stackoverflow.com/a/48499133
answers question: http://stackoverflow.com/q/48497795
has comment: http://stackoverflow.com/comment/83992033
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Here's a memory efficient solution which uses pandas categories. The cost is now just an integer for each value in 'txt' column in the result, which is significantly cheaper than storing text strings. import pandas as pd ids = range(0,4) texts = ['first sent', 'another one', 'I think you', 'will like this'] df = pd.DataFrame({'txt':texts, 'id':ids}) df2 = pd.DataFrame({'attr':['chem', 'dis', 'chem', 'chem', 'chem', 'dis', 'dis', 'dis', 'dis', 'chem'] ,'id':[0,0,1,1,2,2,3,3,4,4]}) # convert to category codes and store mapping df['txt'] = df['txt'].astype('category') df_txt_cats = dict(enumerate(df['txt'].cat.categories)) df['txt'] = df['txt'].cat.codes # perform merge - memory efficinet since result only uses integers df_merged = df.merge(df2, on='id') # rename categories from integers to text strings from previously stored mapping df_merged['txt'] = df_merged['txt'].astype('category') df_merged['txt'].cat.categories = list(map(df_txt_cats.get, df_merged['txt'].cat.categories)) df_merged.dtypes # id int32 # txt category # attr object # dtype: object
has comment: http://stackoverflow.com/comment/83992224
has comment: http://stackoverflow.com/comment/84019800

http://stackoverflow.com/comment/84163845
score: 0
comment on: http://stackoverflow.com/q/48583744
type: Comment
type: QuestionComment
has text: `'a' in pd.Series(['a','b','c','d'])` check membership of indices

http://stackoverflow.com/comment/84170026
score: 0
has text: Do you know the len of your list ? -- nevermind, I wanted to make a special implementation of binary search. But you would have needed the length of your current list. But if you don't have it at the beginning, you won't go faster than iterating once through your list, and counting the elements that interests you, and stop when you know you won't find any as you have a sorted list.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48586305

http://stackoverflow.com/q/48528206
answer count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84054787
has body: I have a python script here that copy images in multiple times, the first copying of image was a success but the second one gave this error. i know for sure that i changed my dir up one level or i did it in a wrong way? any ideas? os.chdir(path) FileNotFoundError: [WinError 3] The system cannot find the path specified: 'my_images/babesia divergen this is my code import os import shutil for file in os.listdir("my_images/"): path='my_images/' + file os.chdir(path) cwd=os.getcwd() print(cwd) images=os.listdir(cwd) a = 0 while a &lt; 2: a = a + 1 shutil.copy2(images[0],os.path.splitext(images[0])[0]+str(a)+os.path.splitext(images[0])[1]) print(os.path.splitext(images[0])[0],a,os.path.splitext(images[0])[1]) os.chdir('..') cwd2=os.getcwd() print(cwd2) this is the output after C:\Users\Polaius-Work\Desktop\New folder (2)\my_images\ascaris lumbricodes ascaris lumbricodes 1 .jpg ascaris lumbricodes 2 .jpg C:\Users\Polaius-Work\Desktop\New folder (2)\my_images Traceback (most recent call last): File "duplicate_images.py", line 10, in &lt;module&gt; os.chdir(path) FileNotFoundError: [WinError 3] The system cannot find the path specified: 'my_images/babesia divergen' so clearly the os.chdir('') is working but but it dont recognize the second folder
has comment: http://stackoverflow.com/comment/84056320
favorite count: 0
has comment: http://stackoverflow.com/comment/84053723
has comment: http://stackoverflow.com/comment/84052648
has comment: http://stackoverflow.com/comment/84052126
has comment: http://stackoverflow.com/comment/84053897
tagged with: python
has title: The system cannot find the path specified after os.chdir('..')
has comment: http://stackoverflow.com/comment/84052072
has comment: http://stackoverflow.com/comment/84052529
type: Question

http://stackoverflow.com/comment/84217514
has text: You have the same answer :P
comment on: http://stackoverflow.com/a/48610172
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84189134
has text: @Christopher You mean as a concatenated string?
type: AnswerComment
comment on: http://stackoverflow.com/a/48595935
score: 0
type: Comment

http://stackoverflow.com/q/48631680
favorite count: 0
type: Question
type: UnansweredQuestion
has title: TypeError: 'SArray' object does not support item assignment?
tagged with: python
tagged with: graphlab
has body: I am working on graphlab and geeting problems in all kind of assignments using SFrame, which are like dataframe and series objects are SArrays. Each time I have to convert the whole data to dataframe and again to SFrame. import graphlab as gl sf = gl.SFrame('abc.csv') # have columns 'Name','Price', 'Quantity' etc. for i in range(0, len(sf)): temp = (str)sf['Name'][i] temp = temp.replace('_br_', '') sf['Name'][i] = temp Now, I wanted to do some string operations and matching, but first I can't even assign values to SArray. Any advice on how to simplify item assignment using SFrame or alternative apart from dataframe would be helpful.
tagged with: pandas
answer count: 0
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84278085
type: AnswerComment
comment on: http://stackoverflow.com/a/48640426
type: Comment
score: 0
has text: Also, there is one more problem as the data is not present even after grouping, filtering won't work like the way I want. What I wanted to do is group it between startdate and enddate and after put the count in between the months

http://stackoverflow.com/comment/84019708
type: Comment
comment on: http://stackoverflow.com/a/48512140
type: AnswerComment
has text: Yes, I suspected as much, but it is only really important that it works for the majority of cases. Could it generate a matrix with a total sum different of the input matrix sum? What could be expected of this "convex combination" case?
score: 0

http://stackoverflow.com/q/48506113
tagged with: python
accepted answer: http://stackoverflow.com/a/48511573
upvote count: 8
favorite count: 0
score: 8
type: Question
has body: I created the simplest Flask app I could imagine: import flask from flask import Flask application = Flask(__name__) @application.route('/') def index(): return flask.jsonify(ok=True) I deployed this app on 1/26 to Elastic Beanstalk. It has served 0 requests since deployment. Here is a graph of the memory usage, using Amazon's memory monitoring scripts: You can see the little dip where (I assume) garbage collection happened on 1/29. But what on earth is allocating so much memory? If this is normal, how should I be monitoring memory so I can actually figure out if my (real) application has a memory leak? Is this Flask's fault, Python's fault, AWS's fault, ...something else? Edited to add: I switched over to using mod_wsgi this aftenoon, but it didn't seem to have any effect. Updated graph (the dips are deploying new versions, it took a few tries to get the config right): Output of free -m: total used free shared buffers cached Mem: 532 501 31 0 81 37 -/+ buffers/cache: 381 150 Swap: 0 0 0
has title: Why is flask using all of my memory?
tagged with: amazon-web-services
tagged with: flask
has answer: http://stackoverflow.com/a/48511573
type: AnsweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84131054
has text: @chaugen1 My code returns a `numpy.ndarray`, not a generator. Did you run exactly the code that I posted?
comment on: http://stackoverflow.com/a/48556595
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84133498
type: Comment
has text: No. Create a `dir` called `templatetags` and put the file inside that. Follow this [doc](https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/) - update in the answer also
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48568366

http://stackoverflow.com/q/48571995
type: Question
has comment: http://stackoverflow.com/comment/84142021
has body: If one goes AWS console to create a Lambda function the required runtime selection only lists C#, Go, Java8, and Python so why No C++ here? Then in AWS information I have read like "only C++ and python SDKs provide AWS greengrass specific functionality for Discovery Service, and CA downloads. I know C++ I do not know Python, and C/C++ is the universal language for embedded devices (as a rule) so I would prefer to stick with C++ with AWS unless AWS folk are not fully supporting C++ and or heading to python instead. So the question is Does AWS greengrass fully support C++ as it does python? I do not have the AWS developer support level so I can not ask the technical support at AWS,
score: 1
has comment: http://stackoverflow.com/comment/84167403
tagged with: python
has answer: http://stackoverflow.com/a/51347675
tagged with: c++
has comment: http://stackoverflow.com/comment/84168391
answer count: 2
has answer: http://stackoverflow.com/a/63792590
downvote count: 0
has title: Does AWS greengrass fully support C++ as it does python
upvote count: 1
type: UnansweredQuestion
tagged with: amazon-ec2
has comment: http://stackoverflow.com/comment/92487002
has comment: http://stackoverflow.com/comment/84170258
tagged with: amazon-web-services
favorite count: 0

http://stackoverflow.com/q/48586861
has comment: http://stackoverflow.com/comment/84171823
tagged with: google-bigquery
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84171013
answer count: 1
downvote count: 0
has body: I am trying to query my BigQuery database using Python but every time I run this code I get an error saying "No query found" even though the query works fine on Google Cloud Console. Note: myfilepath.json and my-project-id are valid values in the code I have. def explicit(): import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "myfilepath.json" credentials = GoogleCredentials.get_application_default() bigquery_service = build('bigquery', 'v2', credentials=credentials) query_request = bigquery_service.jobs() query_data = { 'query': ('#standardSQL SELECT * FROM `SentimentAnalysis.testdataset`') } query_response = query_request.query( projectId='my-project-id', body=query_data).execute() print(query_response) explicit() The error I get every time is: googleapiclient.errors.HttpError: &lt;HttpError 400 when requesting https://www.googleapis.com/bigquery/v2/projects/my-project-id/queries?alt=json returned "1.58 - 1.58: No query found."&gt;
has title: BigQuery API returns "No query found"
upvote count: 1
tagged with: python
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/48588031
score: 1
has comment: http://stackoverflow.com/comment/84171066

http://stackoverflow.com/comment/84172547
comment on: http://stackoverflow.com/q/48587748
type: QuestionComment
has text: What code have you tried so far?
type: Comment
score: 0

http://stackoverflow.com/comment/84113659
type: QuestionComment
has text: You have set score to be equal to `len([])`. So you've initialised it to equal `0`. You need to initialise it as just the list `score = []` and then call `print(len(score))` to achieve what you intended
comment on: http://stackoverflow.com/q/48558987
score: 0
type: Comment

http://stackoverflow.com/comment/84181982
has text: I use 2.7 because I need to use a module that may not work for Python 3.4.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48589141
type: QuestionComment

http://stackoverflow.com/q/48543326
linked to: http://stackoverflow.com/q/22856136
has comment: http://stackoverflow.com/comment/84082055
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48543900
answer count: 1
has comment: http://stackoverflow.com/comment/84082137
has body: I am trying to add a custom header to my common request like so: myApp.config(['$httpProvider', function ($httpProvider) { // $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; $httpProvider.defaults.headers.common['test_key'] = 'kkkkk'; }]); Without the above header request works fine. but when added gives the following error: { "data": null, "status": -1, "config": { "method": "GET", "transformRequest": [ null ], "transformResponse": [ null ], "jsonpCallbackParam": "callback", "url": "http://localhost:8900/tt/", "data": {}, "headers": { "Accept": "application/json, text/plain, */*", "test_key": "kkkkk" } }, "statusText": "", "xhrStatus": "error" } On server side I have Django with Django Rest Framework. Server side code is very simple: from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def test(request): return Response({'ddddddd'}) urlpatterns = [ url(r'^tt/$', test) ] What am I doing wrong? How should I add these headers?
has title: AngularJS $http request fails with custom headers
type: Question
accepted answer: http://stackoverflow.com/a/48543900
tagged with: angularjs
tagged with: django
tagged with: python

http://stackoverflow.com/comment/84172035
type: Comment
comment on: http://stackoverflow.com/q/48587447
type: QuestionComment
has text: The docs provide suggestions about how to use logging in a library: https://docs.python.org/3.7/howto/logging.html#configuring-logging-for-a-library. That may have some useful information for you.
score: 0

pyopenssl
tag name: pyopenssl
type: Tag
tags question: http://stackoverflow.com/q/48573631

http://stackoverflow.com/comment/84008452
has text: But i want to access the p tag,and that is returning an error.
comment on: http://stackoverflow.com/a/48505865
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84109809
score: 1
type: QuestionComment
type: Comment
has text: Can't you extend pandas and override the behavior for that specific part?
comment on: http://stackoverflow.com/q/48557002

http://stackoverflow.com/comment/84316606
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48639813
type: Comment
has text: user2357112, @AGNGazer plz check my [yet another](https://stackoverflow.com/a/48659524/237105) answer - the first one got downvoted too much.

http://stackoverflow.com/a/51216578
upvote count: 5
type: Answer
has body: I would suggest: from botocore.vendored import requests requests.get('http://checkip.amazonaws.com').text.rstrip() inside your lambda function. Otherwise you may get an error that says that lambda cannot find requests unless you created your lambda from a .zip file that includes requests installed via pip
answers question: http://stackoverflow.com/q/48619163
has comment: http://stackoverflow.com/comment/108167087
score: 4
downvote count: 1
has comment: http://stackoverflow.com/comment/121403645
has comment: http://stackoverflow.com/comment/89454028

http://stackoverflow.com/a/48533433
accepted answer of: http://stackoverflow.com/q/48530689
answers question: http://stackoverflow.com/q/48530689
type: Answer
has comment: http://stackoverflow.com/comment/84062661
score: 0
type: AcceptedAnswer
has body: Using IPython inside Spyder, the backend in use will be selected before actually putting typing any code. Changing the backend would hence require to change the automatic setting inside the spyder settings. Any changes made here would require to restart Spyder.

http://stackoverflow.com/q/48574173
answer count: 0
tagged with: deep-learning
tagged with: pytorch
has title: Compute gradient of bias b in pytorch for Softmax Regression
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has body: I am learning pytorch materials and I encountered a problem that while using backpropagation using autograd moudule of pytorch, I was able to get the gradient of weights W, but not the bias b for the SOFTMAX REGRRESSION. The code is presented below. The problem is that I am getting b.grad= None and I was expecting not None values. How can we fix this error? Help will be appreciated. import torch from torch.autograd import Variable dtype = torch.FloatTensor dtype2 = torch.LongTensor X_data = 10 * torch.rand(2, 300).type(dtype) y_labels = torch.zeros(300).type(dtype2) y_labels[0:100] = 1 y_labels[100:200] = 2 y_labels = y_labels.type(dtype2) print(y_labels) X = Variable(X_data, requires_grad = False) y = Variable(y_labels, requires_grad = False) N = X.shape[1] decay = 0.01 W = Variable(torch.randn(3, 2).type(dtype), requires_grad = True) b = Variable(torch.zeros(3, 1).type(dtype), requires_grad = True) XT = X.t() WT = W.t() ones = Variable(torch.ones(1,N).type(dtype), requires_grad = False) # print("XT.shape = {}".format(XT.shape)) # 300,2 # print("WT.shape = {}".format(WT.shape)) # 2,3 # print("b.shape = {}".format(b.shape)) # 3,1 # scores z = torch.mm(XT, WT) + torch.mm(b,ones).t() # 300,3 # Get exponentials and probabilities exp_z = torch.exp(z - torch.max(z)) probs = exp_z / torch.sum(exp_z) # 300,3 # loss correct_probs = probs.data[0:N,y.data.type(torch.LongTensor)] # 300, logprobs = torch.log(correct_probs) loss_data = -1/N * torch.sum(logprobs) # regularization loss_reg = 0.5 * decay * torch.sum(W**2) loss = loss_data + loss_reg # gradients loss.backward() print("W = {}".format(W)) print("b = {}".format(b)) print("W.grad = {}".format(W.grad)) print("b.grad = {}".format(b.grad)) # this is None
tagged with: softmax
tagged with: machine-learning
tagged with: python
score: 2

http://stackoverflow.com/a/67919586
score: -2
type: Answer
has body: Try to change port=2181 and check hbase-site.xml
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/124793977
answers question: http://stackoverflow.com/q/48640978

http://stackoverflow.com/comment/84182503
type: QuestionComment
comment on: http://stackoverflow.com/q/48592572
score: 0
type: Comment
has text: 1) use the url in the form's action attribute, 2) post this data `{'submitAllStores': 'View All Stores'}`

http://stackoverflow.com/q/48550578
upvote count: 0
answer count: 2
tagged with: tkinter
downvote count: 1
has answer: http://stackoverflow.com/a/48551183
has answer: http://stackoverflow.com/a/48551189
tagged with: grid
has title: How to delete unsaved tkinker label?
favorite count: 0
type: Question
has body: I made this program where I am putting labels on a grid without saving them in a variable. I do this because then I can for loop through a list of classes and get the data from each class in and add them to a row. This is a small piece of it: self.collum = 0 for i in self.gui_resource_list: Label(text=i.get_name(), relief="groove", width=15).grid(column=self.column, row=0) Label(text=i.get_buyPrice(), relief="groove", width=15).grid(column=self.column, row=1) Label(text=i.get_salePrice(), relief="groove", width=15).grid(column=self.column, row=2) Label(text=i.arrow, relief="groove", width=15).grid(column=self.column,row=3) self.column += 1 So this will generate a table-like layout. Then there is a button that updates all the values runs that for loop again. So it basically draws the new labels on top of the older ones. This is not good because when you are on the turn 300 there are 300 labels times the all the resource instances in gui_resource list. A way to fix this is to delete the old labels. Is there a way to delete an unsaved label? Something like: delete_grid(column=2,row=3) And that would delete all of the things in the grid at position 2,3?
has comment: http://stackoverflow.com/comment/84102182
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84098209
tagged with: python
score: -1
tagged with: label

http://stackoverflow.com/comment/84293538
type: AnswerComment
score: 0
type: Comment
has text: Marking it as the right answer, even though it is just a small improvement. thanks! I'll try using vectors and matrices, as @marcman proposed.
comment on: http://stackoverflow.com/a/48612121

http://stackoverflow.com/q/48554923
has title: Python w/ Excel sheet. For each value in First Col. calculate two columns.
has comment: http://stackoverflow.com/comment/84126120
tagged with: python
score: -2
has body: I do have an excel sheet that has for example 100 rows in Col A the value changes after every five rows, so First 5 rows have value 1, Second 5 rows has value 2,.. etc until I reach the last 5 rows that have value 20. I want to go through Col A values and computes Col B with Col C. in ColA I will have 20 values. So, a traditional way to do that is: n= 5 lst=[row for row in range(1, 100//n) for _ in range(n)] row=1 for row in lst: value = sheet.cell(row, 0).value if value==1: ''' My code here''' elif value == 2: ''' My code here''' :: :: :: :: :: :: :: :: # I do this till I reach value == 20 I don't want to write more lots lines of code to go through all the values in Col A. All these lines doing the same job except they change the value in column A after every 5 rows. My question here how can I make a loop or any other way to go through col A. Please if you want me to elaborate I'm happy to do so. The output should be like this as an example: For value # 1 in Col A. Total is: 50 (sum numbers in Col B with Col C) For value # 2 in Col A. Total is: 86 (sum numbers in Col B with Col C) For value # 3 in Col A. Total is: 99 (sum numbers in Col B with Col C) ... Until Reach For value # 20 in Col A. Total is: 4235 (sum numbers in Col B with Col C) Note: How Can I make a loop in values in Col A. calculate values in Col B with Col C that corresponding to value in Col A.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48555005
upvote count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: openpyxl
answer count: 1
tagged with: excel

http://stackoverflow.com/comment/84233182
type: Comment
comment on: http://stackoverflow.com/q/48618287
score: 0
has text: please show your effort
type: QuestionComment

http://stackoverflow.com/comment/84050572
type: AnswerComment
has text: Can u elaborate _"When you pass None as the master, the master becomes the current root instance of Tk class."_ using my script? For `class App`, I read `self.s = ttk.Style()` as `ttk.Frame.s` (or `a.s`) is `ttk.Style`. According to `ttk.py`, `ttk.Style()` is to define `self.tk = self.master.tk` where `self.master` is either `tkinter._default_root` or `tkinter.Tk()`. I think `tkinter.Tk()` will create a new root, while `tkinter._default_root` will refer to the root of `a` which is also tkinter.Tk(). For `class myWidget`, it's master is `a` which is a `class App`. So what happens here?
comment on: http://stackoverflow.com/a/48520126
type: Comment
score: 0

http://stackoverflow.com/q/48524894
has comment: http://stackoverflow.com/comment/84045161
answer count: 3
has answer: http://stackoverflow.com/a/48525229
downvote count: 0
has title: Dynamically double-quote "keys" in text to form valid JSON string in python
has answer: http://stackoverflow.com/a/48525244
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48525523
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: regex
score: 4
upvote count: 4
tagged with: double-quotes
has body: I'm working with text contained in JS variables on a webpage and extracting strings using regex, then turning it into JSON objects in python using json.loads(). The issue I'm having is the unquoted "keys". Right now, I'm doing a series of replacements (code below) to "" each key in each string, but what I want is to dynamically identify any unquoted keys before passing the string into json.loads(). Example 1 with no space after : character json_data1 = '[{storeName:"testName",address:"12345 Road",address2:"Suite 500",city:"testCity",storeImage:"http://www.testLink.com",state:"testState",phone:"999-999-9999",lat:99.9999,lng:-99.9999}]' Example 2 with space after : character json_data2 = '[{storeName: "testName",address: "12345 Road",address2: "Suite 500",city: "testCity",storeImage: "http://www.testLink.com",state: "testState",phone: "999-999-9999",lat: 99.9999,lng: -99.9999}]' Example 3 with space after ,: characters json_data3 = '[{storeName: "testName", address: "12345 Road", address2: "Suite 500", city: "testCity", storeImage: "http://www.testLink.com", state: "testState", phone: "999-999-9999", lat: 99.9999, lng: -99.9999}]' Example 4 with space after : character and newlines json_data4 = '''[ { storeName: "testName", address: "12345 Road", address2: "Suite 500", city: "testCity", storeImage: "http://www.testLink.com", state: "testState", phone: "999-999-9999", lat: 99.9999, lng: -99.9999 }]''' I need to create pattern that identifies which are keys and not random string values containing characters such as the string link in storeImage. In other words, I want to dynamically find keys and double-quote them to use json.loads() and return a valid JSON object. I'm currently replacing each key in the text this way content = re.sub('storeName:', '"storeName":', content) content = re.sub('address:', '"address":', content) content = re.sub('address2:', '"address2":', content) content = re.sub('city:', '"city":', content) content = re.sub('storeImage:', '"storeImage":',…

http://stackoverflow.com/comment/84038144
has text: Noo, that is for sure not useful. You should point out what you have tried using a [mcve].
type: Comment
comment on: http://stackoverflow.com/q/48521291
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84244136
score: 0
comment on: http://stackoverflow.com/q/48622002
has text: Any more details on your error? Could you may print(1,2,3, ...) between your lines to determine the line of code, where your programm is crashing? Furthermore, you should a add a check if you current location is allready the location in the Startup/Appdata-folder.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/131105737
comment on: http://stackoverflow.com/a/74209058
type: AnswerComment
score: 0
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/33035545)
type: Comment

http://stackoverflow.com/comment/84248027
type: QuestionComment
comment on: http://stackoverflow.com/q/48623047
has text: It's the same path and known on both machines. Tortoise SVN if that matter.
score: 0
type: Comment

http://stackoverflow.com/a/48627155
type: Answer
answers question: http://stackoverflow.com/q/48627109
score: 2
upvote count: 2
has body: You need DatetimeIndex.month and DatetimeIndex.dayofweek: df['month'] = df.index.month df['Day_of_week'] = df.index.dayofweek print (df) Random_Number month Day_of_week 2018-01-05 00:00:00 1 1 4 2018-01-05 06:00:00 8 1 4 2018-01-05 12:00:00 4 1 4 2018-01-05 18:00:00 5 1 4 2018-01-06 00:00:00 1 1 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48627109

http://stackoverflow.com/comment/84049700
comment on: http://stackoverflow.com/q/48523773
score: 1
has text: @jp_data_analysis, @max9111, I don't think we should be suggesting `numba` at this stage. The OP needs to learn to work with basic array masking and indexing first. The use of `while` loops suggests he's Python novice.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48537990
type: Answer
has comment: http://stackoverflow.com/comment/84072557
score: 0
answers question: http://stackoverflow.com/q/48537953
has body: Yes, it is possible. variable = Demo_list[0]**2 The code above won't modify the list.

http://stackoverflow.com/comment/84286680
type: QuestionComment
comment on: http://stackoverflow.com/q/48644511
has text: @eyllanesc I have 'eliminated' the focus by opening a new window (like Chrome, a window from Explorer,etc..)
score: 0
type: Comment

http://stackoverflow.com/q/48585848
has comment: http://stackoverflow.com/comment/84169295
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84169397
has comment: http://stackoverflow.com/comment/84220442
has comment: http://stackoverflow.com/comment/84168605
tagged with: docopt
answer count: 0
has body: So I am trying to learn Python but I am a little bit overwhelmed with many new things. One of these things that I am not able to understand is: if __name__ == '__main__': args = docopt(__doc__) print(args) The results of the print function is always: {'initdb': False, 'run': False} In some examples, the 'initdb' must be true in order to initialize the database and pretty much to run the app? if __name__ == '__main__': args = docopt(__doc__) if not args['initdb']: ... How can I make the initdb value equals true? This is my first attempt to learn the subject, apologies if the question is not clear enough.
tagged with: sqlite
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
has title: Trying to understand docopt(__doc__)
type: Question

http://stackoverflow.com/comment/84121356
score: 1
has text: Side note: I'd have major security concerns allowing to run arbitrary user code on a server not packed inside a sandbox. You may want to rethink your approach in case you want to put this into production.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48562821

http://stackoverflow.com/q/48593118
score: 5
answer count: 1
downvote count: 0
tagged with: python
has body: I have a pandas dataframe df which has a DatatimeIndex spanning about 2 years, 2 columns and over 30 million rows of float64 data. I quickly noticed that there is a stark difference in performance between df.rolling('1d').mean() and df.rolling('1d').max() &gt;&gt;&gt; n=100000; import timeit; r=df[:n].rolling('1d'); timeit.timeit(lambda: r.max(), number=1) 2.5886592870228924 &gt;&gt;&gt; n=100000; import timeit; r=df[:n].rolling('1d'); timeit.timeit(lambda: r.mean(), number=1) 0.011829487979412079 &gt;&gt;&gt; n=1000000; import timeit; r=df[:n].rolling('1d'); timeit.timeit(lambda: r.max(), number=1) 53.8340517100296 &gt;&gt;&gt; n=1000000; import timeit; r=df[:n].rolling('1d'); timeit.timeit(lambda: r.mean(), number=1) 0.06093513499945402 As you can see, df.rolling('1d').mean() is several hundred times faster than df.rolling('1d').max(). I would expect it to be somewhat faster since to calculate the maximum pandas presumably has to keep track the order of all values in the rolling window at each step. However, it's easy to see how to implement this by adding at most a log factor, so I would expect a smaller difference. If this is the best one can do, using df.rolling('1d').max is going to be a pain on the full dataset, since it looks like it will take hours each time. Having run into efficiency issues with pandas before (Series.iloc indexing), I am curious as to whether this is a pandas issue or if there is a faster way to solve this problem. Edit This was recently fixed in the master branch of pandas. Even on the full dataset, the rolling maximum can now be computed in 2.35 seconds whereas before it probably would have taken hours. Thanks to hexgnu for the fix. &gt;&gt;&gt; runtime(lambda: df.rolling('1d').max()) 2.3093386580003425 &gt;&gt;&gt; n=100000; import timeit; r=df[:n].rolling('1d'); timeit.timeit(lambda: r.max(), number=1) 0.015023122999991756 &gt;&gt;&gt; n=1000000; import timeit; r=df[:n].rolling('1d'); timeit.timeit(lambda: r.max(), number=1) 0.0801312…
type: AnsweredQuestion
tagged with: pandas
upvote count: 5
accepted answer: http://stackoverflow.com/a/48593365
has title: Rolling max with pandas on large datasets is very slow
favorite count: 0
has answer: http://stackoverflow.com/a/48593365
type: Question

http://stackoverflow.com/comment/83987922
has text: If you could ready carefully my answer I think you will find all the answers needed :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48497396
type: Comment

http://stackoverflow.com/a/48554947
type: Answer
has body: To square an integer in python, use two asterisks e.g. 2**2 will produce 4 For example, save this as square.py #!/usr/bin/env python import sys integer_to_square = int(sys.argv[1]) print(integer_to_square**2) Then run it with different inputs $ python square.py 2 4 $ python square.py 4 16 $ python square.py 8 64 $ python square.py 16 256
answers question: http://stackoverflow.com/q/48554234
score: 0

http://stackoverflow.com/a/48635405
score: 0
answers question: http://stackoverflow.com/q/48635316
has comment: http://stackoverflow.com/comment/84267911
type: Answer
has body: "\r" maybe put in the end of line. import time for index in range(0, len(animation)): sys.stdout.write(str(animation[index]) + "\r") sys.stdout.flush() time.sleep(0.2)

http://stackoverflow.com/q/48494110
downvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/48494183
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48494159
has answer: http://stackoverflow.com/a/48494353
has answer: http://stackoverflow.com/a/48494209
tagged with: python
answer count: 6
has title: Find the next iteration in loop python
score: 2
upvote count: 3
has body: I am trying to find out if given a string if 2 target characters follow one another. So essentially, I am trying to find if a character and its neighbor are target characters. How should I go about this? The following is what I have tried so far. target_list=["t","a","r","g","e","t"] for char in some_string: if (char and some_string[some_string.index(char)+1]) in target_list: print ("correct") else: print ("incorrect") Expected output: if some_string="heytr" == "correct" if some_string="hyt" == "incorrect" if some_string="heyt" == "incorrect"
has answer: http://stackoverflow.com/a/48494259
has answer: http://stackoverflow.com/a/48494420
tagged with: for-loop
type: UnansweredQuestion

http://stackoverflow.com/comment/84205003
comment on: http://stackoverflow.com/q/48593683
score: 0
type: Comment
type: QuestionComment
has text: @user2699 Thank you. I just thought it maybe clearer in the format of console output. I will keep it in mind.

http://stackoverflow.com/comment/84228377
type: Comment
type: QuestionComment
has text: I'm getting the same error using the most basic configurations taken from the vscode documentation here - https://donjayamanne.github.io/pythonVSCodeDocs/docs/debugging_remote-debugging/. This might actually be a vscode bug, maybe worth opening an issue.
score: 0
comment on: http://stackoverflow.com/q/48611967

http://stackoverflow.com/q/48493545
type: Question
has title: how to get this fib sequence to start at 0?
upvote count: 2
has comment: http://stackoverflow.com/comment/83980478
answer count: 1
accepted answer: http://stackoverflow.com/a/48493572
favorite count: 0
has comment: http://stackoverflow.com/comment/83980303
has answer: http://stackoverflow.com/a/48493572
type: AnsweredQuestion
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/83980300
score: -3
has body: so I have this sequence running from 1 to 21. but I need it to start at 0. nbr1 = 0 nbr2 = 1 i = 0 for i in range (0, N): tmpnbr = nbr1 nbr1 = nbr1 + nbr2 nbr2 = tmpnbr print (nbr1) I just can't seem to figure out how to get it start at 0 zero. any ideas?

http://stackoverflow.com/a/48606839
downvote count: 0
has body: I'm not sure I've really understood your question. Note that your code is equivalent to: doc = """I like movie. But I don't like the cast. The story is very nice""" doc1 = doc.split('.') result = list(enumerate(doc1)) (I've used result because list would hide the name list I use to construct the list) If you put doc = """I like movie. But I don't like the cast. The story is very nice""" as input you'll get in result the value result = [(0,"I like movie"),(1," But I don't like the cast"),(2," The story is very nice")] Note the spaces at the begining of the strings. It may or may not be what you're looking for. Basic result If you're question is "How to recreate the initial string given the result ?", here is a sample code to do that: recreated_doc = ".".join(value for index, value in result) Advanced answer Note that if you provide doc = """I like movie. But I don't like the cast. The story is very nice.""" with a ending comma, you'll get: result = [(0,"I like movie"),(1," But I don't like the cast"),(2," The story is very nice"),(3,"")] But what if I want to get the next line instead ? result = [(0,"I like movie"),(1,"But I don't like the cast"),(2,"The story is very nice")] (Notice that there is no spaces at the start of the strings, nor empty strings.) Here will be the code: doc = """I like movie. But I don't like the cast. The story is very nice.""" doc1 = doc.split('.') doc2 = (part.strip(' ') for part in doc1) doc3 = (part for part in doc2 if len(part) &gt; 0) result = list(enumerate(doc3)) # result = [(0, 'I like movie'), (1, "But I don't like the cast"), (2, 'The story is very nice')] And to recrete the original string: recreated_doc = " ".join(value+"." for index, value in result) # recreated_doc = """I like movie. But I don't like the cast. The story is very nice.""" Warning, the advanced solution doesn't recreate always the same original doc, so it may be a no go. Example: doc = """This a document with a lot of spaces. . Too much spaces here. And also here…
answers question: http://stackoverflow.com/q/48606567
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84209958
accepted answer of: http://stackoverflow.com/q/48606567
score: 2
upvote count: 2

http://stackoverflow.com/q/48592334
has comment: http://stackoverflow.com/comment/84182175
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84182014
tagged with: python
tagged with: dictionary
tagged with: morse-code
favorite count: 0
has title: How to translate whole words into morse-code with a dictionary?
score: -2
has comment: http://stackoverflow.com/comment/84182109
has comment: http://stackoverflow.com/comment/84182066
type: Question
has body: I'm writing a program that translates normal text to Morse code and I've written the core program that translates single letters to Morse code I still can't figure out how to translate whole words and text. more clarification: i can translate single letters but i cant translate whole words Here's the code: from tkinter import * #key down function def click(): entered_text=textentry.get() #this wil collect the text from the text entry box outpout.delete(0.0, END) try: definition = my_dictionary[entered_text] except: definition= "sorry an error occured" outpout.insert(END, definition) #### main window = Tk() window.title("THIS IS A SIMPLE TITLE") window.configure(background="yellow") #create label Label (window,text="Enter a text here.", bg="YELLOW", fg="BLACK", font="arial 30 bold italic" ) .grid(row=1, column=0, sticky=W) #create a text entry box textentry= Entry(window, width=20, bg="WHITE") textentry.grid(row=2, column=0, sticky=W) #add a submit button Button(window, text="SUBMIT", width=6, command=click) .grid(row=3 ,column=0, sticky=W) #create another label Label (window,text="THE ENCRYPTED TEXT IS:", bg="YELLOW", fg="BLACK", font="arial 10 bold" ) .grid(row=4, column=0, sticky=W) #create a text box outpout = Text(window, width=75, height=6, wrap=WORD, bg="WHITE") outpout.grid(row=5, column=0, columnspan=2, sticky=W) #the dictionary my_dictionary = { "A" : ".-", "B" : "-...", "C" : "-.-.", "D" : "-..", "E" : ".", "F" : "..-.", "G" : "--.", "H" : "....", "I" : "..", "J" : ".---", "K" : "-.-", "L" : ".-..", "M" : "--", "N" : "-.", "O" : "---", "P" : ".--.", "Q" : "--.-", "R" : ".-.", "S" : "...", "T" : "-", "U" : "..-", "V" : "...-", "W" : ".--", "X" : "-..-", "Y" : "-.--", "Z" : "--..", " " : "/" } #run the main loop window.mainloop()
has comment: http://stackoverflow.com/comment/84182197
has answer: http://stackoverflow.com/a/48592492
upvote count: 0
type: UnansweredQuestion
tagged with: translation

http://stackoverflow.com/q/48598599
has body: I have Jalaali date and time as Iran timezone,what I want to do is convert them to Gregorian date and UTC time respectively and separately and then create a Django datetime object to save it in my model ,everything works fine but when I try to save it , it saves previous value for them (before converting with astimezone), but if remove the tzinfo from datetime object the save problem goes away this is my code: import datetime import pytz gregorian_dict = {'gy':2018,'gm':2,'gd':3} time_list = [9,0,0] gregorian_date_iran_time = pytz.timezone('Iran').localize(datetime.datetime(gregorian_dict['gy'], gregorian_dict['gm'], gregorian_dict['gd'],time_list[0],time_list[1],time_list[2])) gregorian_date_utc_time = gregorian_date_iran_time.astimezone(pytz.utc) so far everything is Okey and the output is desired, but when i try to save it the value for gregorian_date_iran_time is save instead eventhough the prints is desired values suggestion = Suggest() suggestion.request = online_request suggestion.teacher = teacher suggestion.session_length = length print(gregorian_date_utc_time) # 2018-02-03 05:30:00+00:00 suggestion.date = gregorian_date_utc_time print(suggestion.date) # 2018-02-03 05:30:00+00:00 suggestion.save() but when i do this,i get correct result after save gregorian_date_utc_time = gregorian_date_utc_time.replace(tzinfo=None) I dont know if I am making a dumy mistake or forget something what is the solution for this? edit looked up in database and find out that the value that stored in database is that the value saved in database is correct , but in django admin I get 9:00:00 2018-02-03 05:30:00.000000 what is wrong?
type: Question
has title: python convert timezone issue
tagged with: timezone
answer count: 1
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48599623
has answer: http://stackoverflow.com/a/48599623
tagged with: datetime

http://stackoverflow.com/a/53896726
score: 0
has body: Find the absl-py related folder in your site-packages folder and delete it. Try reinstalling pip3 install absl-py. I solved this way, I hope to be useful to you.
answers question: http://stackoverflow.com/q/48490260
type: Answer

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/48615284
tags question: http://stackoverflow.com/q/48549453
tags question: http://stackoverflow.com/q/48634151
tags question: http://stackoverflow.com/q/48600277
tags question: http://stackoverflow.com/q/48538314
tags question: http://stackoverflow.com/q/48532723
tags question: http://stackoverflow.com/q/48555290
tags question: http://stackoverflow.com/q/48505727
type: Tag
tags question: http://stackoverflow.com/q/48580085
tags question: http://stackoverflow.com/q/48495628
tags question: http://stackoverflow.com/q/48533200
tags question: http://stackoverflow.com/q/48595858
tags question: http://stackoverflow.com/q/48505749
tags question: http://stackoverflow.com/q/48547017
tags question: http://stackoverflow.com/q/48519062
tags question: http://stackoverflow.com/q/48639220
tags question: http://stackoverflow.com/q/48596429
tag name: r
tags question: http://stackoverflow.com/q/48536058
tags question: http://stackoverflow.com/q/48597453

http://stackoverflow.com/comment/84072083
has text: Any reason for the contempt towards command line? Contrary to the python gdal, it seems to be working
type: QuestionComment
comment on: http://stackoverflow.com/q/48531082
type: Comment
score: 0

http://stackoverflow.com/a/48563024
has comment: http://stackoverflow.com/comment/84386681
has comment: http://stackoverflow.com/comment/84671917
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84200258
has comment: http://stackoverflow.com/comment/84605285
has comment: http://stackoverflow.com/comment/84183173
has comment: http://stackoverflow.com/comment/84632516
has comment: http://stackoverflow.com/comment/84645651
answers question: http://stackoverflow.com/q/48551672
has comment: http://stackoverflow.com/comment/84386178
score: 3
has body: You sent ScreenFive as callback for on_press. the callback is called with the button instance so your error raise. try this: def callback(instance): sm.current = "screen_five" ... ... on_press=callback
type: Answer
has comment: http://stackoverflow.com/comment/84600464
has comment: http://stackoverflow.com/comment/84671895

http://stackoverflow.com/q/48558140
tagged with: python
has comment: http://stackoverflow.com/comment/84112007
score: 0
has comment: http://stackoverflow.com/comment/84127053
answer count: 0
type: UnansweredQuestion
tagged with: pip
has title: pip install error tensorflow
tagged with: tensorflow
linked to: http://stackoverflow.com/q/42962765
type: Question
has comment: http://stackoverflow.com/comment/84127125
linked to: http://stackoverflow.com/q/38896424
has body: am trying to install tensorflow but am getting this following error, i have updated the setup tools also, command: pip3 install --upgrade tensorflow error: writing top-level names to pip-egg-info\absl_py.egg-info\top_level.txt writing manifest file 'pip-egg-info\absl_py.egg-info\SOURCES.txt' error: [Errno 2] No such file or directory: 'c:\\users\\user\\downloads\\python-3.5.2-embed- amd64\\python35.zip\\lib2to3\\Grammar.txt' Command "python setup.py egg_info" failed with error code 1 in C:\Users\user\AppData\Local\Temp\pip-build-hhz6jia9\absl-py\

http://stackoverflow.com/comment/84143163
has text: Thanks for the provided solution, although it did not work for me. Now, the dependency (django) is installed but I cannot find where as python 2/3 cannot import it while being outside or inside of virtualenv. I do not have a complex app, therefore I'd stick to the main purpose of Docker for now, although, there are still threads where it is explained why creating venv inside the docker container is still a fine practice. [Example](https://stackoverflow.com/questions/29146792/why-people-create-virtualenv-in-a-docker-container)
type: AnswerComment
comment on: http://stackoverflow.com/a/48565216
score: 1
type: Comment

http://stackoverflow.com/q/48591317
has body: So, I have an alert that has multiple span elements with different error messages. I need to test if a specified message is contained in that alert. For example, in the screenshot below, one of the span elements contains the "The email field is required" message. I tried implementing it in Python and then use it as a keyword in RobotFramework, but i've got stuck at finding the current browser instance. The Parser.py file contains: from selenium.webdriver.common.by import By from selenium import webdriver def parse_alert_msg(elements, message): alerts = driver.find_elements(By.XPATH, elements) for item in alerts: if item.text == message: return True return False This is what i have in my robot file: Test Function Open Website Login Successfully as ${UserName} ${Password} ${message} Parser.Parse Alert Msg //div[@class='alert-content']/span[@class='alert-description'] You have logged in. Run Keyword If ${message}=${FALSE} Fail There is no such span with that text. [Teardown] Close Browser
has comment: http://stackoverflow.com/comment/84189929
has title: RobotFramework - How to parse each span element from the alert and check if it contains the text?
type: Question
tagged with: robotframework
has comment: http://stackoverflow.com/comment/84190133
has comment: http://stackoverflow.com/comment/84185894
has answer: http://stackoverflow.com/a/48601950
has comment: http://stackoverflow.com/comment/84193976
tagged with: python
accepted answer: http://stackoverflow.com/a/48597768
has answer: http://stackoverflow.com/a/48597768
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/48601950
answer count: 2
linked to: http://stackoverflow.com/q/23703870
tagged with: selenium
has comment: http://stackoverflow.com/comment/84190033

http://stackoverflow.com/comment/84085007
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48535471
type: Comment
has text: If I understand correctly, you want to fit a straight line to the points corresponding to the maximum x values of each "finger" - so isolating those points is the first step, and then fitting a straight line to theose points is the second step. Is this essentially correct?

http://stackoverflow.com/a/48640969
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48640535
has comment: http://stackoverflow.com/comment/84279135
type: Answer
has body: As @MPA suggested, this will provide with a list of candidates: from scipy import signal match = np.sum(template) tst = signal.convolve2d(x, template[::-1, ::-1], mode='valid') == match candidates = np.argwhere(tst) This gives (0, 2) and (0, 3) for your example. For binary matrices, one can do as @Paul suggests: from scipy import signal match = np.sum(template) tst = signal.convolve2d(x, (2 * template - 1)[::-1, ::-1], mode='valid') == match positions = np.argwhere(tst) This gives (0, 3) for your example.
downvote count: 0

http://stackoverflow.com/q/48525138
answer count: 0
score: 1
upvote count: 1
has title: Tensorflow: Efficiently solve Ax=b with constraint x >= 0
tagged with: tensorflow
favorite count: 0
has body: One component of a computational algorithm that I am moving from C++ to Tensorflow iteratively computes the solution to Ax=b subject to x>=0 with the following iterative method (in python pseudo-code): for t in range(64): for i in range(N): x[i] = b[i] for j in range(N): if i != j: x[i] -= A[i,j] * x[j] x[i] = max(x[i] / A[i,i], 0) For the given domain (A strongly positive definite, b positive), the iteration converges quickly with good results. A naive translation to Tensorflow like the following: for _ in range(64): X.assign(maximum(B - einsum('ij,j-&gt;i', Azerodiag, X), 0.0) / Adiag) is equivalent to: for t in range(64): for i in range(N): xp[i] = b[i] for j in range(N): if i != j: xp[i] -= A[i,j] * x[j] xp[i] = max(xp[i] / A[i,i], 0) for i in range(N): x[i] = xp[i] Unfortunately, these methods do not converge because the iteration needs the latest value of all the x's when computing a new x[i]. Inverting the matrix almost works (closer to correct), but doesn't take into account the constraint x>=0 so produces erroneous solutions for some inputs. What is the best way to tackle this in Tensorflow? I'd be perfectly satisfied to be able to do the same computations as the C++ version, but I do not see how to do that efficiently with the Tensorflow operators. It is very fast in the current C++ implementation even though you are looping 64 times because N ~ 64 and this competes very favorably with other methods even without any type of early stopping based on convergence. The computation is just part of a forward computation as part of a larger graph, so invoking session.run multiple times just to solve this part is not feasible performance-wise.
has comment: http://stackoverflow.com/comment/94007152
has comment: http://stackoverflow.com/comment/84404042
linked to: http://stackoverflow.com/q/48996893
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85063519
tagged with: c++
downvote count: 0

http://stackoverflow.com/comment/84169515
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48586179
has text: As I said, it is a reasonable guess, but my certainty is considerably less than 99% -- perhaps they want to know if a *substring* of `FPS` is in it so that `PS` is okay but `SP` isn't.
score: 0

http://stackoverflow.com/comment/84007012
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48505061
score: 0
has text: Probably. But using `0.99*m0` doesn't guarantee it won't go past `m0` if you run it again with different parameters. If your function is very smooth, the adaptive solver can take very big steps, and it might still go past `m0` when it gets near `0.99*m0`.

http://stackoverflow.com/comment/84190565
score: 0
type: Comment
has text: Thanks for explaining! I did have that in my original code.
type: AnswerComment
comment on: http://stackoverflow.com/a/48596722

http://stackoverflow.com/comment/84285307
score: 0
has text: Thanks for the suggestion, but it seems like all these libraries are too much slow for what I want it, maybe I'm not doing it correctly though.
comment on: http://stackoverflow.com/q/48631247
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84214479
has text: TLDR, there is no question at all here. Run `bash` with `-x` option to analyze the program flow.
type: Comment
comment on: http://stackoverflow.com/q/48608814
score: 2
type: QuestionComment

http://stackoverflow.com/q/48552061
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/84102256
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48556981
tagged with: python
tagged with: sorting
tagged with: data-structures
has body: I have an excel spreadsheet with sports data - a header row with things like Team, Result, Date, etc, and rows with all of the teams in them (for example, if baseball, the first 162 rows are individual games for one team, then the next 162 are for another, etc). I'm able to read these into python with XLRD easy enough, but i'm not sure exactly how to store them so that I can easily access information about a specific team. I can use a defaultdict(list) but i'm honestly not too sure how to actually access anything specific. For example: import xlrd import xlwt import os.path import math import pandas as pd from xlutils.copy import copy as xl_copy from collections import defaultdict result = defaultdict(list) workbook = xlrd.open_workbook("Sample.xls") worksheet = workbook.sheet_by_index(1) headers = worksheet.row(0) for index in range(worksheet.nrows)[1:]: for header, col in zip(headers, worksheet.row(index)): result[header.value].append(col.value) This stores everything I need in "Result" and the output (if I print it) is like this (example for a 3-row file): Team {'Boston Red Sox','Boston Red Sox','Boston Red Sox'} Score {'11-4','4-0','5-6'} Result {'W','W','L'} How can this information be better stored/sorted by team in order for me to easily access information pertaining to a specific team? **If I wanted to add up how many victories they had, for example, how would I even do that? Is deafultdict a good use for this situation? Thanks
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48553262
has title: How can I use Python to sort and store Sports Statistics from an Excel file?

http://stackoverflow.com/q/48633654
has comment: http://stackoverflow.com/comment/84264431
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48633961
has title: python - change x axis using data frame column
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 2
tagged with: pandas
upvote count: 2
accepted answer: http://stackoverflow.com/a/48633961
has answer: http://stackoverflow.com/a/48633864
possible better answer: http://stackoverflow.com/a/48633864
downvote count: 0
has body: I have a data frame, df I used to produce a plot of two series like so: year = [2002, 2002, 2002, 2002] month = ['Jan', 'Feb', 'Mar', 'Apr'] column1 = [3.3, 3.0, 3.1, 3.2, 2.9] column2 = [7.0, 7.1, 7.3, 6.9, 7.3] Dataset = list(zip(year, month, column1, column2)) df = DataFrame(data = Dataset, columns = ['year', 'month', 'column1', 'column2']) df['column1'].plot(legend = True, label = 'column1') df['column2'].plot(legend = True, label = 'column2', title = \ "Figure 1", style = '--', linewidth = 2.5) Which produces the following: I also have a column in my dataframe, df['year'] that has values that I would like to go along the x-axis. I tried the following plt.xticks(df['year']) But the following happened: Is there a way to use the column df['year'] and have its values as the x axis tick marks without manually listing them? I would like the final version to look like the first plot but with the unique values of df['year'] along the x-axis.
tagged with: plot
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84264804

http://stackoverflow.com/comment/84276593
type: Comment
type: QuestionComment
has text: Thanks, but which is the best method ? recommended one. In terms of memory and speed
comment on: http://stackoverflow.com/q/48639834
score: 0

http://stackoverflow.com/q/48558957
tagged with: python-2.7
score: 0
answer count: 0
tagged with: mysql
has body: Lately getting a lot of errors likes this: An error occurred in the current transaction. You can't " TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. the exceptions are not in context of tests (like in other stack overflow questions). these exception comes from many different views and apis together at some point of the day. I'm running Django 1.7.1, Python 2.7, MySql 5.7 (Google Cloud Managed) Could it be related to Django DB Sessions? I see this code in SessionStore.save() (\django\contrib\sessions\backends\db.py) with transaction.atomic(using=using): obj.save(force_insert=must_create, using=using) Could a Session save cause other requests to return TransactionManagementError this is the full stack trace: Traceback (most recent call last): File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view return view_func(*args, **kwargs) File "/opt/webapps/app/reports/api.py", line 573, in track_album_played albumStore = AlbumStore.objects.only('id').get(id=album_store_id) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/query.py", line 351, in get num = len(clone) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/query.py", line 122, in __len__ self._fetch_all() File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/query.py", line 966, in _fetch_all self._result_cache = list(self.iterator()) File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/query.py", line 265, in iterator for row in compiler.results_iter(): File "/opt/rh/python27/root/usr/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 700, in results_iter for rows …
type: Question
tagged with: django-sessions
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84119437
tagged with: django
has title: getting a lot of TransactionManagementError in production servers
tagged with: python
has comment: http://stackoverflow.com/comment/84113576

http://stackoverflow.com/q/48520176
tagged with: python
has answer: http://stackoverflow.com/a/48520819
accepted answer: http://stackoverflow.com/a/48520819
type: AnsweredQuestion
has title: How to remove help(?) in QWizard?
has comment: http://stackoverflow.com/comment/84035170
downvote count: 0
tagged with: pyqt
upvote count: 1
score: 1
answer count: 1
has body: How to remove that help(?) in the QWizard window. Example application Img Edit: Here is the code. This is simple application from Qt. I just want to disable that and have help button instead. I got to know how to add help buttons in each page but couldn't find solution to remove help (?) option from PyQt4.Qt import * def createIntroPage(): page = QWizardPage() page.setTitle("Introduction") label = QLabel("This wizard will help you register your copy of " "Super Product Two.") label.setWordWrap(True) layout = QVBoxLayout() layout.addWidget(label) page.setLayout(layout) return page def createRegistrationPage(): page = QWizardPage() page.setTitle("Registration") page.setSubTitle("Please fill both fields.") nameLabel = QLabel("Name:") nameLineEdit = QLineEdit() emailLabel = QLabel("Email address:") emailLineEdit = QLineEdit() layout = QGridLayout() layout.addWidget(nameLabel, 0, 0) layout.addWidget(nameLineEdit, 0, 1) layout.addWidget(emailLabel, 1, 0) layout.addWidget(emailLineEdit, 1, 1) page.setLayout(layout) return page def createConclusionPage(): page = QWizardPage() page.setTitle("Conclusion") label = QLabel("You are now successfully registered. Have a nice day!") label.setWordWrap(True) layout = QVBoxLayout() layout.addWidget(label) page.setLayout(layout) return page if __name__ == '__main__': import sys app = QApplication(sys.argv) wizard = QWizard() wizard.addPage(createIntroPage()) wizard.addPage(createRegistrationPage()) wizard.addPage(createConclusionPage()) wizard.setWindowTitle("Trivial Wizard") wizard.show() sys.exit(wizard.exec_()) Thanks in advance
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84036849
tagged with: pyqt4

http://stackoverflow.com/comment/84183556
comment on: http://stackoverflow.com/q/48593034
has text: @MitchWheat I guess what I'm primarily asking is, shouldn't deleting the object and then reinitializing it do the same thing as restarting the kernel? is it possible for information to be cached in a notebook?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48493054
has body: You didn't call the function to run. Add randomNumber() to the end of your program. Were you getting an error with your if statements? Please edit your post if you were. It is working fine for me.
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48492650

http://stackoverflow.com/a/48550698
score: 0
type: AcceptedAnswer
has body: do print str(PercentComplete)+"% complete" In your answer, you were printing two different things. Here you combine it into one item and print it
has comment: http://stackoverflow.com/comment/84097644
accepted answer of: http://stackoverflow.com/q/48550672
type: Answer
answers question: http://stackoverflow.com/q/48550672

http://stackoverflow.com/a/48502322
upvote count: 1
answers question: http://stackoverflow.com/q/48502217
downvote count: 0
score: 1
type: Answer
has body: import re string = "E/Exception ['thisdevice:JFW32-000001007.IdName = telephonepole (null) has no hope, magic will be discard']" final = re.sub(r'J[\w\d]+\-[\d]+', '', string) print final &gt;&gt;&gt;E/Exception ['thisdevice:.IdName = telephonepole (null) has no hope, magic will be discard']

http://stackoverflow.com/q/48577136
has answer: http://stackoverflow.com/a/48577171
has body: I want to return a specific value for each value in a list. list = ['sathya','varna','summi'] I want to return values such that if my key is 'sathya' return -5, if key is 'varna' return -4. As of now my code is: def return_value(): if key == 'sathya': return -5 if key == 'varna': return -4 But I don't want to use so many if conditions. can anyone help me in this
accepted answer: http://stackoverflow.com/a/48577236
answer count: 4
type: AnsweredQuestion
has title: Return specific value for each value in a list
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84150754
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48577176
has answer: http://stackoverflow.com/a/48577236
type: Question
has answer: http://stackoverflow.com/a/48577194
possible better answer: http://stackoverflow.com/a/48577171
tagged with: python

http://stackoverflow.com/q/48617123
tagged with: visual-c++
linked to: http://stackoverflow.com/q/32814134
tagged with: mod-wsgi
has answer: http://stackoverflow.com/a/74947183
has comment: http://stackoverflow.com/comment/84231075
has comment: http://stackoverflow.com/comment/84231092
answer count: 1
downvote count: 0
tagged with: pip
has title: while doing pip install mod_wsgi is failing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84230994
score: 5
has comment: http://stackoverflow.com/comment/84231123
type: UnansweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/84231162
tagged with: django
has body: I am trying to put my django site on apache and i am following these tutorial enter link description here In doing these by these command set "MOD_WSGI_APACHE_ROOTDIR=C:\xampp\apache pip install mod_wsgi I am getting these error. wsgi_apache.obj : error LNK2001: unresolved external symbol __imp_apr_conv_utf8_to_ucs2 wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_shared_make wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_shared_copy wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_free wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_alloc wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_shared_destroy wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_shared_split wsgi_interp.obj : error LNK2001: unresolved external symbol __imp_ap_show_mpm wsgi_interp.obj : error LNK2001: unresolved external symbol __imp_ap_get_server_description wsgi_interp.obj : error LNK2001: unresolved external symbol __imp_ap_get_server_built wsgi_metrics.obj : error LNK2001: unresolved external symbol __imp_ap_get_scoreboard_process wsgi_metrics.obj : error LNK2001: unresolved external symbol __imp_ap_get_scoreboard_worker_from_indexes wsgi_metrics.obj : error LNK2001: unresolved external symbol __imp_ap_exists_scoreboard_image wsgi_thread.obj : error LNK2001: unresolved external symbol __imp_apr_threadkey_private_get wsgi_thread.obj : error LNK2001: unresolved external symbol __imp_apr_threadkey_private_set build\lib.win-amd64-3.6\mod_wsgi\server\mod_wsgi.cp36-win_amd64.pyd : fatal error LNK1120: 101 unresolved externals error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1120 I had already tried other lot answers available on stackoverflow but nothing works.Every help will be appreciated
tagged with: python
has comment: http://stackoverflow.com/comment/84257620

http://stackoverflow.com/q/48502868
has answer: http://stackoverflow.com/a/52361194
has title: How to scrape a whole website using beautifulsoup
has comment: http://stackoverflow.com/comment/84003018
downvote count: 0
has body: I'm quite new to Programming and OO programming especially. Nonetheless, I'm trying to write a very simple Spider for web crawling. Here's my first approach: I need to fetch the data out of this page: http://europa.eu/youth/volunteering/evs-organisation_en Firstly, I do a view on the page source to find HTML elements? view-source:https://europa.eu/youth/volunteering/evs-organisation_en Note: I need to fetch the data that comes right below this line: EVS accredited organisations search results: 6066 I chose beautiful soup for this job - since it is very powerful: I Use find_all: soup.find_all('p')[0].get_text() # Searching for tags by class and id Note: Classes and IDs are used by CSS to determine which HTML elements to apply certain styles to. We can also use them when scraping to specify specific elements we want to scrape. See the class: "People need people" Zaporizhya oblast civic organisation of disabled families Zaporizhzhya, Ukraine Sending PIC no: 935175449 Read more so this leads to: # import libraries import urllib2 from bs4 import BeautifulSoup page = requests.get("https://europa.eu/youth/volunteering/evs-organisation_en") soup = BeautifulSoup(page.content, 'html.parser') soup Now, we can use the find_all method to search for items by class or by id. In the below example, we'll search for any p tag that has the class outer-text so we choose: soup.find_all(class_="col-md-4") Now I have to combine all. update: my approach: so far: I have extracted data wrapped within multiple HTML tags from a webpage using BeautifulSoup4. I want to store all of the extracted data in a list. And - to be more concrete: I want each of the extracted data as separate list elements separated by a comma (i.e.CSV-formated). To begin with the beginning: here we have the HTML content structure: <div class <h4 Data 1 <div class= Data 2 <p class= <i class= Data 3 <p class= Data 4 <p class= Data 5 Data 6 <div class= <a href="Data 7 Code to extract: for data in elem.find_all('span', class…
has comment: http://stackoverflow.com/comment/84006829
answer count: 1
has comment: http://stackoverflow.com/comment/84008469
has comment: http://stackoverflow.com/comment/84006656
favorite count: 0
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84033126
tagged with: python
score: 4
upvote count: 4

http://stackoverflow.com/a/48602057
type: Answer
score: 0
has body: The simplest solution is to move the creation of the temp dictionary inside the loop: data = {} # dict data still created here # other stuff for result in r: print(result) temp = {} # create new dict here temp['names'] = ast.literal_eval(result['names']) # list of strings temp['symbols'] = ast.literal_eval(result['symbols']) # list of strings temp['country'] = result['country'] # string data[result['id']] = temp print(data) # should show different dicts, one for each result
answers question: http://stackoverflow.com/q/48601786

http://stackoverflow.com/q/48574135
has comment: http://stackoverflow.com/comment/84165698
has comment: http://stackoverflow.com/comment/84162522
favorite count: 0
has comment: http://stackoverflow.com/comment/84156743
type: Question
upvote count: 2
score: 2
has body: I have a problem with running matlab code in python. When I run my easy code, I have this information in matlab console: Undefined function or variable 'messenger'. Error in matlabserver (line 7) messenger('init', socket_address); Matlab code: %% MATLAB function lol = yourfunc(args) arg1 = args.arg1; arg2 = args.arg2; lol = arg1 + arg2; end Python code: from pymatbridge import Matlab mlab = Matlab() mlab.start() res = mlab.run('...path\yourfunc.m', {'arg1': 3, 'arg2': 5}) print(res['result'])
downvote count: 0
has comment: http://stackoverflow.com/comment/84161291
tagged with: python
accepted answer: http://stackoverflow.com/a/48584481
tagged with: matlab
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48584481
has comment: http://stackoverflow.com/comment/84161502
has title: Run matlab script in python - error
answer count: 1

http://stackoverflow.com/comment/84064353
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48534389
score: 0
has text: Ahh my mistake. In my lexer I am not supposed to accept them. I will edit.

http://stackoverflow.com/comment/83985835
score: 0
has text: Possible duplicate of [How to read images from a directory? (Python OpenCV)](https://stackoverflow.com/questions/48001890/how-to-read-images-from-a-directory-python-opencv)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48496223

http://stackoverflow.com/comment/84190429
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48595269
has text: Hey @Arief, thanks! but i would like each item A, B, C to appear in the combination list at least once, meaning that there can't be all As, or 4As and 1B
type: Comment

http://stackoverflow.com/comment/84192867
comment on: http://stackoverflow.com/q/48594829
type: QuestionComment
type: Comment
score: 0
has text: There is no db interaction here, I am getting those device details by using script that should be dynamdynamic

http://stackoverflow.com/comment/84190781
type: Comment
score: 0
type: AnswerComment
has text: Also note that these functions are just concepts and will break if an empty array is passed to them, for example.
comment on: http://stackoverflow.com/a/48596822

http://stackoverflow.com/comment/84005649
has text: Yeah it actually is MUCH simpler with networkx. Thanks a lot.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48505748
type: AnswerComment

http://stackoverflow.com/comment/84248170
type: Comment
type: QuestionComment
has text: Thank you Nathan for the pointer. I did some experiment on it following this article: http://blog.christianperone.com/2013/09/machine-learning-cosine-similarity-for-vector-space-models-part-iii/. The problem I have is that the relatedness is measured by using the same bag of words in the example, while the relatedness I need isn't exactly the same words. For example, 1.1 and 1.2 use very different words, but they all talk about marketing.
score: 0
comment on: http://stackoverflow.com/q/48588361

http://stackoverflow.com/a/48526310
accepted answer of: http://stackoverflow.com/q/48526073
score: 2
answers question: http://stackoverflow.com/q/48526073
type: Answer
has comment: http://stackoverflow.com/comment/84051550
has comment: http://stackoverflow.com/comment/84051854
has body: Solution Sound like the case for a small helper function: def read_col(fname, col=1, convert=int, sep=None): """Read text files with columns separated by `sep`. fname - file name col - index of column to read convert - function to convert column entry with sep - column separator If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ with open(fname) as fobj: return [convert(line.split(sep=sep)[col]) for line in fobj] res = read_col('mydata.txt') print(res) Output: [34, 65, 106] If you want the first column, i.e. at index 0: read_col('mydata.txt', col=0) If you want them to be floats: read_col('mydata.txt', col=0, convert=float) If the columns are separated by commas: read_col('mydata.txt', sep=',') You can use any combination of these optional arguments. Explanation We define a new function with default parameters: def read_col(fname, col=1, convert=int, sep=None): This means you have to supply the file fname. All other arguments are optional and the default values will be used if not provide when calling the function. In the function, we open the file with: with open(fname) as fobj: Now fobj is an open file object. The file will be closed when we de-dent, i.e. here when we end the function. This: [convert(line.split(sep=sep)[col]) for line in fobj] creates a list by going through all lines of the file. Each line is split at the separator sep. We take only the value for the column with index col. We also convert the value in the datatype of convert, i.e. into an integer per default. Edit You can also skip the first line in the file: with open(fname) as fobj: next(fobj) return [convert(line.split(sep=sep)[col]) for line in fobj] Or more sophisticated as optional argument: def read_col(fname, col=1, convert=int, sep=None, skip_lines=0): # skip first `skip_lines` lines for _ in range(skip_lines): next(fobj) with open(fname) as fobj: return [convert(line.split(sep=sep)[col]) for line in fobj]
has comment: http://stackoverflow.com/comment/84051476
upvote count: 2
has comment: http://stackoverflow.com/comment/84051952
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84106711
score: 0
has text: I have a feeling the culprit is your `DataFrame`. `sep='\t' and my solution should both work. Heck, even WITHOUT either of these `to_csv()` should automatically quote items with commas in it. Perhaps post a sample of your `DataFrame` and code for more details
type: Comment
comment on: http://stackoverflow.com/a/48554976
type: AnswerComment

http://stackoverflow.com/q/48504023
type: Question
has answer: http://stackoverflow.com/a/48507453
tagged with: multiprocessing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84002984
downvote count: 0
has answer: http://stackoverflow.com/a/48504095
upvote count: 1
has comment: http://stackoverflow.com/comment/84003313
has title: How to communicate between processes while they're running
has answer: http://stackoverflow.com/a/48505183
has comment: http://stackoverflow.com/comment/84003411
has comment: http://stackoverflow.com/comment/84001762
has answer: http://stackoverflow.com/a/48506833
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48504095
score: 1
accepted answer: http://stackoverflow.com/a/48505183
tagged with: python
has body: I would like to have two processes which run parallel. The one gets input from the other, processes the data and sends the processed data back as output for the other. The other process does the same thing. Obviously there needs to be a starting point and an end point. How can I communicate between the processes while they're running? I only managed to run the two processes after each other. I tried to solve it with multiprocessing: from multiprocessing import Process, Queue, Array sentinel = -1 def process1(q, arr): # Receives data, modifies it and sends it back while True: data = q.get() # Receive data if data is sentinel: break data *= 2 # Data modification arr.append(data) # Data logging q.put(data) # Send data q.put(sentinel) # Send end signal def process2(q, arr): # Receives data, increments it and sends data back if q.empty(): data = 1 else: while True: data = q.get() # Receive data if data == sentinel: break data += 1 q.put(data) # Send data arr.append(data) # Data logging q.put(sentinel) # Send end signal if __name__ == "__main__": q = Queue() logbook = Array('i', 0) counter = 0 while counter &lt; 10: process_1 = Process(target=process1, args=(q, logbook)) process_2 = Process(target=process2, args=(q, logbook)) process_1.start() process_2.start() q.close() q.join_thread() process_1.join() process_2.join() counter += 1 print(logbook)
has comment: http://stackoverflow.com/comment/84001768
has comment: http://stackoverflow.com/comment/84001758
answer count: 4
has comment: http://stackoverflow.com/comment/84002899
favorite count: 0

http://stackoverflow.com/comment/84093014
comment on: http://stackoverflow.com/q/48531082
type: Comment
type: QuestionComment
score: 0
has text: Confirmed it works using gdal command line. `gdal_translate -srcwin 300 300 2000 2000 input.tif output.tif` [creates a cropped GeoTIFF 300 pixels cropped off top and left side and 2000 pixels high and long]. Weird the same thing doesn't work with the Python bindings....

http://stackoverflow.com/q/48613584
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84224177
tagged with: plot
has comment: http://stackoverflow.com/comment/84224790
has answer: http://stackoverflow.com/a/48613796
has comment: http://stackoverflow.com/comment/84224063
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: matplotlib
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84224026
has title: Python - Error scatter plotting with Matplotlib: Index out of range
tagged with: scatter-plot
has comment: http://stackoverflow.com/comment/84224091
has answer: http://stackoverflow.com/a/48614363
has body: I'm very new to Python, and I have a CSV file with three columns. They represent a transmission time in milliseconds, signal amplitude, and FM radio frequency in kHz. There's a lot of lines, but they look something like this: My task is to find out which radio frequency is generating random noise and which is a structured signal. For how to do this, I'm trying to first find the unique values in the frequency column of my data file (column 3) and then plot them individually to find the structured data. My guess is that the 71.231012 frequency is the white noise (it seemed less frequent in the file), and so I'm basically trying to plot both frequencies to see if my guess is somewhat correct. So far, this is my code: from __future__ import division import matplotlib.pyplot as mplot import numpy as np file=open("data.csv", "r") data=file.read() data=data.replace(" ", ",") data=data.split("\n") xscatter=[] yscatter=[] for row in data: row=row.split(",") row[2]=float(row[2]) if row[2] == 71.231012: xscatter.append(row[2]) yscatter.append(row[1]) mplot.scatter(xscatter, yscatter, color="blue", marker="o") mplot.show() But I keep getting this error: row[2]=float(row[2]) IndexError: list index out of range I'm not sure why this is the case; I thought that, with the split, I would have three indexes per row (0,1,2). And because I'm so new to Python, I'm also not sure how accurate or efficient my code is at doing what I want, but it's a start. I'd greatly appreciate some help. EDIT: Here is a sample of my output after splitting the file, before the for loop:
has comment: http://stackoverflow.com/comment/84224140
answer count: 2
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48519778
has body: Yes. It can be done like this. #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","user","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # sql = Query which will return your required rows try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: name = row[0] good_or_bad = row[1] color = row[2] breed = row[3] doggy(name, good_or_bad, color, breed) except: print "Error: unable to fecth data" # disconnect from server db.close()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48518568

http://stackoverflow.com/q/48631068
tagged with: python-3.x
score: 3
has body: I can add additional quotes to the beginning of a triple-quoted string, but not to the end. Why is that? This block of code: print("""" String that starts with quadruple quotes and ends with triple quotes """) Produces this output: " String that starts with quadruple quotes and ends with triple quotes Yet this code block doesn't work: print("""" String that starts with quadruple quotes and ends with quadruple quotes """") It produces this error: File "example.py", line 3 """") ^ SyntaxError: EOL while scanning string literal I don't ever need to use a quadruple-quote string, but I'm curious why Python won't let me do it. Can anyone help me understand?
answer count: 5
has answer: http://stackoverflow.com/a/48631130
tagged with: python
has answer: http://stackoverflow.com/a/48631137
has answer: http://stackoverflow.com/a/77270409
has answer: http://stackoverflow.com/a/48631216
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/84259327
downvote count: 0
possible better answer: http://stackoverflow.com/a/48631099
tagged with: string
has title: Why in Python 3 do quadruple quotes produce a Syntax error?
accepted answer: http://stackoverflow.com/a/48631216
has answer: http://stackoverflow.com/a/48631099
favorite count: 0
type: Question

http://stackoverflow.com/a/70479189
downvote count: 0
has comment: http://stackoverflow.com/comment/127052705
score: 3
has body: First thing, there is no range tag or function in django template. Answer- Pass the list to the render function. This was your problem: {% for i in range(1,10) %} &lt;h2&gt;{{i}}&lt;/h2&gt; {% endfor %} Replace it by passing the range function as generator in views.py context={ 'iterator':range(1,10) } return render(req,'anyname.html',context) Then in your template you can use by following: {% for i in iterator %} &lt;div&gt; {{i}} &lt;/div&gt; {% endfor %}
type: Answer
answers question: http://stackoverflow.com/q/48637178
upvote count: 3

http://stackoverflow.com/q/48631721
type: UnansweredQuestion
tagged with: python
has body: My code is: import sys import time import select import paramiko import pandas as pd paramiko.util.log_to_file('paramiko.log') ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('localhost', username='red', password='******') stdin, stdout, stderr = ssh.exec_command("last") out = stdout.read() print(pd.Series(out, index=['1', '2', '3', '4', '5'])) the output is this one as you can see, after Tue F... it just stops and doesn't show anything else. When the output in Terminal is completely different as it shows this one red pts/2 127.0.0.1 Tue Feb 6 02:12 - 03:45 (01:32) red tty1 /dev/tty1 Tue Feb 6 01:24 still logged in reboot system boot 4.13.0-32-generi Tue Feb 6 01:24 still running red tty1 /dev/tty1 Tue Feb 6 01:04 - 01:07 (00:03) reboot system boot 4.13.0-32-generi Tue Feb 6 01:04 - 01:07 (00:03) red tty1 /dev/tty1 Sat Feb 3 10:29 - crash (2+14:35) reboot system boot 4.13.0-32-generi Sat Feb 3 10:28 - 01:07 (2+14:38) red tty1 /dev/tty1 Sat Feb 3 08:10 - 10:10 (01:59) reboot system boot 4.13.0-32-generi Sat Feb 3 08:10 - 10:10 (02:00) red tty1 /dev/tty1 Fri Feb 2 04:35 - 21:27 (16:51) reboot system boot 4.13.0-32-generi Fri Feb 2 04:35 - 21:27 (16:51) red tty1 /dev/tty1 Fri Feb 2 03:10 - 04:35 (01:24) reboot system boot 4.13.0-21-generi Fri Feb 2 03:10 - 04:35 (01:24) wtmp begins Fri Feb 2 03:10:22 2018
has title: Pandas series in Python doesn't show the full output?
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48632111
favorite count: 0
type: Question

http://stackoverflow.com/a/60304855
downvote count: 1
has body: try String downloadFilepath ="\\sd-"; chromePrefs.put("download.default_directory", downloadFilepath);
type: Answer
score: -1
answers question: http://stackoverflow.com/q/48630484
upvote count: 0

http://stackoverflow.com/comment/84149257
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48567565
has text: Appreciate your concern and Thanks for the comment. I am now thinking I would have written some theory for choosing urlparse oevr regex. I will address leftover part of the actual question. Again, Thanks a lot.

http://stackoverflow.com/comment/84066967
comment on: http://stackoverflow.com/q/48535847
type: Comment
type: QuestionComment
has text: What is Karate?
score: 2

http://stackoverflow.com/a/48583986
accepted answer of: http://stackoverflow.com/q/48583922
type: Answer
has body: You can use behaviour NaN - np.nan == np.nan is False, so np.nan != np.nan is True: df = pd.DataFrame({'styleName':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'abv':[np.nan,np.nan,6,9,2,4], 'F':list('aaabbb')}) style = 'a' print (df.query("styleName == @style &amp; abv != abv")) B C D F abv styleName 0 4 7 1 a NaN a Or boolean indexing: print (df[(df['styleName'] == style) &amp; (df['abv'].isnull())]) B C D F abv styleName 0 4 7 1 a NaN a
answers question: http://stackoverflow.com/q/48583922
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84164714
score: 1

http://stackoverflow.com/comment/84174938
type: Comment
comment on: http://stackoverflow.com/a/48587835
score: 0
type: AnswerComment
has text: Thanks for pointing that out. I was a little unsure as to the differences. I'm looking to prevent SQL injection.

http://stackoverflow.com/a/48513156
has body: from documentation its from bs4 import BeautifulSoup and based on your code, it seems like you want to use it as bs() from bs4 import BeautifulSoup as bs
type: Answer
has comment: http://stackoverflow.com/comment/84022938
upvote count: 4
has comment: http://stackoverflow.com/comment/84022230
downvote count: 0
answers question: http://stackoverflow.com/q/48513111
score: 4
has comment: http://stackoverflow.com/comment/84038881
has comment: http://stackoverflow.com/comment/84022883

http://stackoverflow.com/q/48594666
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48594704
tagged with: python
tagged with: urllib
possible better answer: http://stackoverflow.com/a/48594704
type: Question
score: 2
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/48595984
has title: incomplete result in table scraping
has body: I am trying to scrape http://bifr.nic.in/asp/list.asp this page with beautifulsoup and get the table from it. Following is my code from bs4 import BeautifulSoup import urllib.request base_url = "http://bifr.nic.in/asp/list.asp" page = urllib.request.urlopen(base_url) soup = BeautifulSoup(page, "html.parser") table = soup.find("table",{"class":"forumline"}) tr = table.find_all("tr") for rows in tr: print(rows.get_text()) It shows no error, but when i execute it i am only able to get first row of content from the table. List of Companies Case No Company Name 359 2000 A & F OVERSEAS LTD. 359 2000 A & F OVERSEAS LTD. 359 2000 A & F OVERSEAS LTD. This is the result i am getting. I can't understand what's going on.
downvote count: 0
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48595984
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/comment/84230637
comment on: http://stackoverflow.com/q/48543070
score: 0
type: Comment
type: QuestionComment
has text: Sorry man, you are not helping solve your problem. there only an image in the page and you are trying to access input filelds which aren't present in the page in the first place.

http://stackoverflow.com/a/48513274
accepted answer of: http://stackoverflow.com/q/48512753
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48512753
has body: The cookie header is the key. When you send a request from xhr (aka your browser), relevant cookies are automatically appended to your request. These cookies are how sessions are usually managed, and the response message indicates that the server did not find a valid session cookie in your request. You will need to "authorize", via logging in or otherwise beginning this session, and then insert that session cookie into your request before sending it. After rereading, the token header is most likely not static either. My guess would be that this is engineered to prevent automated requests, and so may be difficult to circumvent. Update in response to OP comment: Use cookiejar or just read the urllib docs and figure out how to extract and then insert cookies. how to send cookies inside post request You will need to study the website’s behavior in your developer tools and see which request triggers a session cookie update, and then simulate that request before you simulate your post request. You’ve been provided three answers. Mark the question as correct and post another, more specific if you still have trouble.
has comment: http://stackoverflow.com/comment/84194495

joblib
tags question: http://stackoverflow.com/q/48500567
tag name: joblib
tags question: http://stackoverflow.com/q/48644137
type: Tag
tags question: http://stackoverflow.com/q/48634190

http://stackoverflow.com/comment/84187530
has text: Try `return self.index_item( item.copy() , type, item_id )`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48595155

http://stackoverflow.com/comment/84053747
has text: @freddykrueger I've updated my answer with benchmarks and fixed a bug in the original answer.
comment on: http://stackoverflow.com/a/48524661
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48534464
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: If you sort the list, you can use a binary search to get the answer quickly. The bisect_right function will return the index of the number you seek, or len(a) if the number is &gt;= the largest in the list. &gt;&gt;&gt; a.sort() &gt;&gt;&gt; a [1, 2, 3, 5, 6] &gt;&gt;&gt; import bisect &gt;&gt;&gt; bisect.bisect_right(a, 2) 2 &gt;&gt;&gt; bisect.bisect_right(a, 4) 3 &gt;&gt;&gt; bisect.bisect_right(a, 7) 5
accepted answer of: http://stackoverflow.com/q/48534034
type: Answer
answers question: http://stackoverflow.com/q/48534034

http://stackoverflow.com/a/48642784
has comment: http://stackoverflow.com/comment/84282808
has comment: http://stackoverflow.com/comment/84283473
has comment: http://stackoverflow.com/comment/84282957
answers question: http://stackoverflow.com/q/48642703
has comment: http://stackoverflow.com/comment/84282436
type: Answer
has comment: http://stackoverflow.com/comment/84283105
has comment: http://stackoverflow.com/comment/84282983
has comment: http://stackoverflow.com/comment/84282831
has comment: http://stackoverflow.com/comment/84282551
score: 0
has comment: http://stackoverflow.com/comment/84282923
has comment: http://stackoverflow.com/comment/84282871
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48642703
downvote count: 1
has comment: http://stackoverflow.com/comment/84308045
has body: Do indenation like this : def revisedRussianRoulette(doors): counter = 0 for i in range(0, len(doors), 2): i = int(i) if doors[i] == 1 &amp; counter == 0: counter += 1 elif doors[i] == 1 &amp; counter == 1: doors[i] = 0 doors[i-2] = 0 doors[i+2] = 0 elif doors[i] == 0 &amp; counter == 1: doors[i-2] = 0 return doors
has comment: http://stackoverflow.com/comment/84283161

http://stackoverflow.com/a/48635852
has body: You might consider using the curses module. This program updates the screen, waits 0.2 seconds, and updates the screen again: from curses import wrapper import time def main(stdscr): stdscr.clear() for i in range(5): for y in range(5): for x in range(5): stdscr.addstr(y, x, chr(ord('1')+i)) stdscr.refresh() time.sleep(0.2) stdscr.getkey() wrapper(main)
score: 0
answers question: http://stackoverflow.com/q/48635316
type: Answer

http://stackoverflow.com/q/48572951
score: 1
tagged with: pyspark
tagged with: python
has title: Issue printing PySpark dataframe as formatted table in Jupyter
tagged with: jupyter-notebook
linked to: http://stackoverflow.com/q/26873127
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/54633621
favorite count: 0
type: Question
has body: I have an PySpark dataframe (df) that I'd like to print as a nicely formatted table in my Jupyter notebook. As per this post, I thought the following code would work: import pandas as pd from IPython.display import display, HTML pandas_df = df.toPandas() display(HTML(pandas_df.to_html())) Unfortunately, this does not work. I get the following error: ERROR - failed to write data to stream: &lt;__main__.UnicodeDecodingStringIO object at 0x7f75c7a8e750&gt; Does anyone know how to resolve this issue? Thanks!

http://stackoverflow.com/a/48513167
answers question: http://stackoverflow.com/q/48512943
has body: You need either another for loop around your call to f.write(), or to write within your first for loop. You are only writing one 'product' to the file because that line of code is only executing once. Easiest solution is move f.write(price + "," + product_name.replace(",", "|") + "," + shipping + "\n") to right after shipping = shipping_container[0].text.strip() be sure to indent to match the rest of your for loop contents. Do yourself a favor and read the python docs. https://docs.python.org/3/
has comment: http://stackoverflow.com/comment/84021290
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/84021316

http://stackoverflow.com/q/48514347
accepted answer: http://stackoverflow.com/a/48520288
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48520288
tagged with: matplotlib
answer count: 1
has body: This is the equation that I'm trying to plot, but have not been successful for hours. XA is variable between 0 to 1. I'd like to plot it while I'm varying eA and n constants. I'm still learning Python and this is being too complicated for me. Any help will be very appreciable. XA = np.linspace(1e-2, 1-1e-2, 20) from scipy.integrate import quad def integrand(XA): return ((1+eA*XA)/(1-XA))**n p = lambda XA: quad(integrand, 1e-2, XA)[0] xs = 1-XA def func(n, eA): return (XA*((1+eA*XA)/(1-XA))**n)/(p) n = [1, 1, 2, 2] eA = [1, 2, 1, 2] ys = list(map(func, alps, e)) plt.plot(xs, ys) plt.show()
has title: Combination of Map and Integration
type: Question
tagged with: numpy
tagged with: python

http://stackoverflow.com/comment/83976561
score: 0
type: Comment
has text: @IAbstract: I have no idea what you mean by the picture demonstrating no window size. Clearly the windows have a size.
type: AnswerComment
comment on: http://stackoverflow.com/a/48489077

http://stackoverflow.com/comment/84307106
comment on: http://stackoverflow.com/a/48632820
score: 0
has text: Your proposed was do nicely! You said to me another way about signal. I thought signal implementation is better easy. So I want to know how to implement it.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84296599
has text: Hi, the formula above assumes that the point lies on a straight line. I don't think this is the case for shortest distance when it comes to lat/lon coordinates
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48642358
type: Comment

http://stackoverflow.com/q/48516751
tagged with: python
possible better answer: http://stackoverflow.com/a/48516950
has body: I'm trying to understand a program using an OOP approach, but that doesn't seem to be going to well. I'm able to follow the code below (that I found online) quite a bit, but I have some question about the relationship between root and my_gui (found below the class definition). import tkinter as tk class MyFirstGUI: def __init__(self, master): self.master = master master.title("A simple GUI") self.label = tk.Label(master, text="This is our first GUI!") self.label.pack() self.greet_button = tk.Button(master, text="Greet", command=self.greet) self.greet_button.pack() def greet(self): print("Greetings!") root = tk.Tk() my_gui = MyFirstGUI(root) root.mainloop() I know that the label and button objects in the init method each go into the master object (which is the root object), but what confuses me is differentiating my_gui and root after the init method has been executed. After the init method of the class executes, does my_gui and root become one and the same thing, or is root now a subset of my_gui? If they are essentially the same being after the init function executes, then there is no need for the my_gui object, is there? What exactly is self.master = master doing? I guess what I really want to know is the relationship between my_gui and root.
type: AnsweredQuestion
tagged with: python-3.x
tagged with: tkinter
answer count: 2
upvote count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/48516950
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48521114
has title: What is the difference between an object, and a tkinter object assigned to it?
has answer: http://stackoverflow.com/a/48521114
score: 1

http://stackoverflow.com/q/48527748
tagged with: matplotlib
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48532012
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48532012
has comment: http://stackoverflow.com/comment/84051531
has comment: http://stackoverflow.com/comment/84058415
type: Question
has title: Matplotlib Different Scaled Y-Axes
tagged with: python
has comment: http://stackoverflow.com/comment/84050735
has body: I have a dataframe with the data below. ex_dict = {'revenue': [613663, 1693667, 2145183, 2045065, 2036406, 1708862, 1068232, 1196899, 2185852, 2165778, 2144738, 2030337, 1784067], 'abs_percent_diff': [0.22279211315310588, 0.13248909660765254, 0.12044821447874667, 0.09438674840975962, 0.1193588387687364, 0.062100921139322744, 0.05875297161175445, 0.06240362963749895, 0.05085338590212515, 0.034877614941165744, 0.012263947005671703, 0.029227374323993634, 0.023411816504907524], 'ds': [dt.date(2017,1,1), dt.date(2017,1,2), dt.date(2017,1,3), dt.date(2017,1,4), dt.date(2017,1,5), dt.date(2017,1,6), dt.date(2017,1,7), dt.date(2017,1,8), dt.date(2017,1,9), dt.date(2017,1,10), dt.date(2017,1,11), dt.date(2017,1,12), dt.date(2017,1,13)], 'yhat_normal': [501853.9074623253, 1952329.3521464923, 1914575.7673396615, 1868685.8215084015, 1819261.1068672044, 1608945.031482406, 1008953.0123101478, 1126595.36037955, 2302965.598289115, 2244044.9351591542, 2171367.536396199, 2091465.0313570146, 1826836.562382966]} df_vis=pd.DataFrame.from_dict(ex_dict) I want to graph yhat_normal and revenue on the same y-axis and abs_percent_diff on a y-axis with a different scale. df_vis = df_vis.set_index('ds') df_vis'rev', 'yhat_normal'.plot(figsize=(20, 12)) I can easily graph rev and yhat_normal with the code above, but I am struggling to get abs_percent_diff on a different y-axis scale. I tried converting my columns to numpy arrays and doing this, but it looks terrible. npdate = df_vis.as_matrix(columns= ['ds']) nppredictions = df_vis.as_matrix(columns= ['yhat_normal']) npactuals = df_vis.as_matrix(columns= ['rev']) npmape = df_vis.as_matrix(columns=['abs_percent_diff']) fig, ax1 = plt.subplots() ax2 = ax1.twinx() fig.set_size_inches(20,10) ax1.plot_date(npdate, nppredictions, ls= '-', color= 'b') ax1.plot_date(npdate, npactuals, ls='-', color='g') ax2.plot_date(npdate, npmape, 'r-') ax1.set_xlabel('X data') ax1.set_ylabel('Y1 data', color='g') ax2.set_ylabel('Y2 data', color='b') plt.show() T…
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84059346
tagged with: pandas

http://stackoverflow.com/comment/84138767
comment on: http://stackoverflow.com/a/48568846
type: AnswerComment
has text: I think your test is fine, my point is that the ordering of the round() function makes little to no difference
score: 0
type: Comment

http://stackoverflow.com/a/48612723
answers question: http://stackoverflow.com/q/48600444
accepted answer of: http://stackoverflow.com/q/48600444
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I was able to get this working by using FormField. However, the documentation gives a default separator as -. Additionally, I explicitly identified separator='-', but only when I used . as a separator, when calling the class, did it work properly, ... even with separator='-'.
type: Answer

http://stackoverflow.com/comment/84240951
comment on: http://stackoverflow.com/a/48619734
score: 0
type: AnswerComment
has text: Cheers for that... I'll look into it. When I've got it covered I'll let you know how I solved it.
type: Comment

http://stackoverflow.com/comment/84066078
comment on: http://stackoverflow.com/a/48535291
score: 0
type: AnswerComment
has text: Hmm... then if you add the Unix-time with standardization, does a model determine the difference between time? As I mentioned, I'm worried that small difference makes learning confused.
type: Comment

http://stackoverflow.com/q/48620109
tagged with: dictionary
score: -4
has answer: http://stackoverflow.com/a/48626222
tagged with: list
has comment: http://stackoverflow.com/comment/84237030
answer count: 3
has comment: http://stackoverflow.com/comment/84240994
has answer: http://stackoverflow.com/a/48620298
tagged with: compare
has body: I have a list of dicts and list of tuples. List of dicts is sort of lookup table. Based on pairs I have to get the keys and for non-matches I need to get 'NA' key. e.g lookup_table = [ {"L" : (148, -1) }, {"D" : (148,440) }, {"N1" : (148,441)}, {"C" : (148,443) }] data= [(10,10),(15,15),(148,-1) ,(148,440),(148,443)] my result should be res = ['NA': (10,10), 'NA': (15,15),"L" : (148, -1),"D" : (148,440),"C" : (148,443) ] I know how to get the matches but I am struggling with the 'NA's Is this kind of approach even possible with python since I have multiple keys with the same name? Thank you
has comment: http://stackoverflow.com/comment/84237062
favorite count: 0
has comment: http://stackoverflow.com/comment/84237020
type: Question
downvote count: 4
has title: python compare list of dicts with list of tuples
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48620386
tagged with: python

linux
tags question: http://stackoverflow.com/q/48631746
tags question: http://stackoverflow.com/q/48642606
tags question: http://stackoverflow.com/q/48513591
tags question: http://stackoverflow.com/q/48562073
tags question: http://stackoverflow.com/q/48591476
tags question: http://stackoverflow.com/q/48578304
tag name: linux
tags question: http://stackoverflow.com/q/48598623
tags question: http://stackoverflow.com/q/48502300
tags question: http://stackoverflow.com/q/48608653
tags question: http://stackoverflow.com/q/48543993
tags question: http://stackoverflow.com/q/48572629
tags question: http://stackoverflow.com/q/48493695
tags question: http://stackoverflow.com/q/48642031
tags question: http://stackoverflow.com/q/48545491
tags question: http://stackoverflow.com/q/48566969
tags question: http://stackoverflow.com/q/48506824
tags question: http://stackoverflow.com/q/48604397
tags question: http://stackoverflow.com/q/48571792
tags question: http://stackoverflow.com/q/48615296
tags question: http://stackoverflow.com/q/48531883
tags question: http://stackoverflow.com/q/48644281
tags question: http://stackoverflow.com/q/48630158
tags question: http://stackoverflow.com/q/48597110
tags question: http://stackoverflow.com/q/48630919
tags question: http://stackoverflow.com/q/48544171
tags question: http://stackoverflow.com/q/48599100
tags question: http://stackoverflow.com/q/48563269
tags question: http://stackoverflow.com/q/48609015
tags question: http://stackoverflow.com/q/48610812
tags question: http://stackoverflow.com/q/48594892
type: Tag
tags question: http://stackoverflow.com/q/48545467
tags question: http://stackoverflow.com/q/48573376
tags question: http://stackoverflow.com/q/48640935
tags question: http://stackoverflow.com/q/48540578
tags question: http://stackoverflow.com/q/48568555
tags question: http://stackoverflow.com/q/48637327
tags question: http://stackoverflow.com/q/48593071
tags question: http://stackoverflow.com/q/48570058
tags question: http://stackoverflow.com/q/48632882
tags question: http://stackoverflow.com/q/48559589
tags question: http://stackoverflow.com/q/48524573
tags question: http://stackoverflow.com/q/48504746
tags question: http://stackoverflow.com/q/48569879
tags question: http://stackoverflow.com/q/48597930

bokeh
tags question: http://stackoverflow.com/q/48645409
tags question: http://stackoverflow.com/q/48576044
tags question: http://stackoverflow.com/q/48554855
tags question: http://stackoverflow.com/q/48631530
tags question: http://stackoverflow.com/q/48634933
tags question: http://stackoverflow.com/q/48631546
tags question: http://stackoverflow.com/q/48569756
tags question: http://stackoverflow.com/q/48582466
tags question: http://stackoverflow.com/q/48643657
tags question: http://stackoverflow.com/q/48606686
type: Tag
tags question: http://stackoverflow.com/q/48577271
tags question: http://stackoverflow.com/q/48614005
tags question: http://stackoverflow.com/q/48509741
tags question: http://stackoverflow.com/q/48645763
tags question: http://stackoverflow.com/q/48527785
tags question: http://stackoverflow.com/q/48558679
tags question: http://stackoverflow.com/q/48594862
tags question: http://stackoverflow.com/q/48511036
tags question: http://stackoverflow.com/q/48533046
tags question: http://stackoverflow.com/q/48584159
tags question: http://stackoverflow.com/q/48640667
tags question: http://stackoverflow.com/q/48566181
tags question: http://stackoverflow.com/q/48516981
tags question: http://stackoverflow.com/q/48525770
tags question: http://stackoverflow.com/q/48643710
tags question: http://stackoverflow.com/q/48547141
tags question: http://stackoverflow.com/q/48570102
tags question: http://stackoverflow.com/q/48629103
tags question: http://stackoverflow.com/q/48570334
tags question: http://stackoverflow.com/q/48610996
tag name: bokeh
tags question: http://stackoverflow.com/q/48528519

http://stackoverflow.com/comment/83971008
type: Comment
score: 0
type: AnswerComment
has text: Ah no, I get the following error: `FieldError: Cannot resolve expression type, unknown output_field`. Any ideas?
comment on: http://stackoverflow.com/a/48488955

http://stackoverflow.com/q/48618043
has comment: http://stackoverflow.com/comment/84233799
has body: I'm gettings this error when running "manage.py validate" in my application. Error: One or more models did not validate: ipn.paypalipn: Accessor for field 'custom' clashes with related field 'Actor.paypalipn_set'. Add a related_name argument to the definition for 'custom'. dashboard.paypalipn: Accessor for field 'custom' clashes with related field 'Actor.paypalipn_set'. Add a related_name argument to the definition for 'custom'. This is in an other model.py i got under Dashboard/ models.py @csrf_exempt def show_me_the_money(sender, **kwargs): ipn_obj = sender actor_id = ipn_obj.custom if actor_id == "Upgrade all users!": User.objects.update(paid=True) if ipn_obj.payment_status == "Completed": from actors.models import Actor from commerce.models import Transaction actor = Actor.objects.get(id=actor_id) accountdetails = actor.account_set.latest('pk') signupbonus = 0 transaction = Transaction() transaction.actor = actor transaction.amount = ipn_obj.mc_gross transaction.currency = ipn_obj.mc_currency transaction.transaction_flag = 'paid' transaction.transaction_type = 'deposit' transaction.payment_method = 'Paypal' transaction.payment_reference = ipn_obj.txn_id transaction.payment_message = 'OK' transaction.transaction_date = timezone.now() transaction.UserIp = actor_ip() transaction.save() currentamount = accountdetails.balance accountdetails.balance = float(signupbonus) + float(currentamount) + float(ipn_obj.mc_gross) accountdetails.save() payment_was_successful.connect(show_me_the_money) Here's in models.py, Actor class Actor(User): def create_actor_number(): try: return int(Actor.objects.order_by('-id')[0].actor_key) + 1 except: return 5001 ssn = models.CharField(max_length=32, default='', blank=True, help_text="Social security number") address = models.OneToOneField(ActorAddress, null=True, blank=True, help_text="Actor full address information") phone_number = models.CharField(max_length=32, default='', blank=True, help_text="Actor main phone number (Format: + and …
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48618853
has title: Error: One or more models did not validate, Add a related_name argument to the definition
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: django
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84232578

http://stackoverflow.com/comment/84052036
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48528477
has text: It should work if IDLE is using the same version of python that you installed with anaconda.
score: 0

http://stackoverflow.com/q/48528348
tagged with: indexing
tagged with: int
tagged with: pandas
has answer: http://stackoverflow.com/a/48554196
has answer: http://stackoverflow.com/a/48528670
tagged with: python
has answer: http://stackoverflow.com/a/48528454
has answer: http://stackoverflow.com/a/48528535
favorite count: 0
type: Question
has body: EDIT: The .mean() function works just right: renda['age'].mean() I'm still not sure why the errors mentioned below and in the answers happened, but this helps as a shortcut. I got a DataFrame renda in which there's a column age and I need to get the mean of the ages. I wrote t_age = renda['age'].sum() renda.index = renda.index.map(int) #intended solution last_id = renda.iloc(-1) print(t_age/last_id) Trying to adapt the answers from here. It still doesn't work though and this error is raised: TypeError: unsupported operand type(s) for /: 'int' and '_iLocIndexer' What can I do to solve this? Thank you! @ScottBoston: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in na_op(x, y) 657 result = expressions.evaluate(op, str_rep, x, y, --&gt; 658 raise_on_error=True, **eval_kwargs) 659 except TypeError: /opt/conda/lib/python3.6/site-packages/pandas/core/computation/expressions.py in evaluate(op, op_str, a, b, raise_on_error, use_numexpr, **eval_kwargs) 210 return _evaluate(op, op_str, a, b, raise_on_error=raise_on_error, --&gt; 211 **eval_kwargs) 212 return _evaluate_standard(op, op_str, a, b, raise_on_error=raise_on_error) /opt/conda/lib/python3.6/site-packages/pandas/core/computation/expressions.py in _evaluate_numexpr(op, op_str, a, b, raise_on_error, truediv, reversed, **eval_kwargs) 121 if result is None: --&gt; 122 result = _evaluate_standard(op, op_str, a, b, raise_on_error) 123 /opt/conda/lib/python3.6/site-packages/pandas/core/computation/expressions.py in _evaluate_standard(op, op_str, a, b, raise_on_error, **eval_kwargs) 63 with np.errstate(all='ignore'): ---&gt; 64 return op(a, b) 65 /opt/conda/lib/python3.6/site-packages/pandas/core/ops.py in &lt;lambda&gt;(x, y) 96 default_axis=default_axis, reversed=True), ---&gt; 97 rtruediv=arith_method(lambda x, y: operator.truediv(y, x), 98 names('rtruediv'), op('/'), truediv=True, TypeError: u…
has title: Convert index number to int (Python)
linked to: http://stackoverflow.com/q/35368645
answer count: 5
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48528367
score: 13
has comment: http://stackoverflow.com/comment/84052292
upvote count: 13

http://stackoverflow.com/comment/84099683
comment on: http://stackoverflow.com/q/48551460
score: 0
has text: @Dylan the program just terminates since I'm currently not returning it to anything
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48573871
type: Question
tagged with: xpath
linked to: http://stackoverflow.com/q/44912203
has answer: http://stackoverflow.com/a/48576293
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/84157295
tagged with: python
has body: there is a website with the following HTML-Code-snippet: Versteck bauen I want to click on this list item. The only list item with the img inside. I find the items with xpath. And tried to click on them. I tried it with the "li" token: xpath = "//img[@class='reward']/parent::*" With the img: xpath = "//img[@class='reward'] And with the "a href": xpath = "//img[@class='reward']//following::*" Then I'm trying to click on it with the following code: click_me = self.browser.find_element_by_xpath(xpath) click_me.click() But I get an Element is not clickable at point exception. So I tried it with an action: action = ActionChains(self.browser) action.move_to_element(click_me).click().perform() and with: action.move_to_element(click_me).move_by_offset(4,0).click().perform() I don't get an error with this but it still doesn't work. EDIT: Used chrome-driver 2.31. Switching to 2.34 solved my problem!
accepted answer: http://stackoverflow.com/a/48580555
has answer: http://stackoverflow.com/a/48575748
has title: Click on list item with selenium (python)
has answer: http://stackoverflow.com/a/48580555
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84147126
possible better answer: http://stackoverflow.com/a/48576293
tagged with: selenium

http://stackoverflow.com/q/48602629
tagged with: python
has comment: http://stackoverflow.com/comment/84201912
tagged with: class
has comment: http://stackoverflow.com/comment/84202416
downvote count: 0
has answer: http://stackoverflow.com/a/48602918
has comment: http://stackoverflow.com/comment/84202805
score: 1
upvote count: 1
answer count: 1
tagged with: methods
has title: pulling data from a list of lists if each list meets a condition
favorite count: 0
has body: I am trying to get a working method in a class I have constructed. This class accumulates a given student's course history. Each course is a list (name, grade, credits, etc) that's part of the total list of all courses for that student. Here is an example course history: [['English 1', 4, 3, 'Fall', '2009'], ['English 2', 3.7, 3, 'Spring', '2010'], ['English 3', 2.7, 3, 'Fall', '2010'], ['English 4', 3.0, 3, 'Spring', '2011'], ['English 5', 3.7, 3, 'Fall', '2011'], ['English 6', 3.3, 3, 'Spring', '2012'], ['Math 1', 3.3, 3, 'Fall', '2009'], ['Math 2', 2.7, 3, 'Spring', '2010'], ['Science 1', 3.7, 4, 'Fall', '2009'], ['Science 2', 4, 4, 'Spring', '2010']] I can figure out cumulative GPA, but I am finding it hard to determine a semester GPA. Here is my relevant code: class StudentInfo(object): def __init__(self, last, first, dob): self.last=last self.first=first self.dob=dob self.gradehist=[] def __add__(self, course): return self.gradehist.append(course) def cumulativegpa(self): cred = [item[2] for item in self.gradehist] grad = [item[1] for item in self.gradehist] gc = [grad[i]*cred[i] for i in range(len(grad))] hrs = sum(cred) gpasum = sum(gc) cumgpa = gpasum/hrs return cumgpa def semgpa(self, x, y): semcred=[] semgrad=[] for i in self.gradehist: if self.gradehist[3] == x and self.gradehist[4] == y: semcred.append([item[2] for item in self.gradehist]) for i in self.gradehist: if self.gradehist[3] == x and self.gradehist[4] == y: semgrad.append([item[1] for item in self.gradehist]) return semcred, semgrad` s1=StudentInfo('Bob','Dole', '1-1-1911') s1 + ['English 1', 4, 3, 'Fall', '2009'] s1 + ['English 2', 3.7, 3, 'Spring', '2010'] etc When I type s1.cumulativegpa() it returns the correct total gpa, but s1.semgpa('Fall','2009') returns "[],[]" Where am I going wrong? edit: updated def semgpa(self, x, y): to include for course in self.gradehist: if course[3] == x and course[4] == y: semcred.append([item[2] for item in course])
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84202437
has comment: http://stackoverflow.com/comment/84202863
has comment: http://stackoverflow.com/comment/84202169
type: UnansweredQuestion

http://stackoverflow.com/comment/83976873
type: Comment
type: QuestionComment
has text: Good idea - but not ideal; That only accounts for the previous row/minute. I would then need to precompute a column for each 'shift'/row which could work since usually a measly .5% increase usually seems to happen within 90 minutes = 90 additional columns - not out of the question though thanks!
comment on: http://stackoverflow.com/q/48491764
score: 0

http://stackoverflow.com/q/48525481
answer count: 4
has answer: http://stackoverflow.com/a/62392436
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48592511
downvote count: 0
tagged with: machine-learning
has answer: http://stackoverflow.com/a/52327133
possible better answer: http://stackoverflow.com/a/52327133
tagged with: python
tagged with: google-colaboratory
has body: Whenver I type any command in Colaboratory, I get following error: Failed to execute cell. Could not send execute message to runtime: CustomError: Timed out waiting for promise Why is this happening and what can I do to prevent it?
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52512147
tagged with: gpu
has title: Google Colaboratory: Timed out error
upvote count: 3
has answer: http://stackoverflow.com/a/48592511

http://stackoverflow.com/q/48493533
upvote count: 1
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/48512633
has comment: http://stackoverflow.com/comment/83980995
has comment: http://stackoverflow.com/comment/83980376
has comment: http://stackoverflow.com/comment/83981099
linked to: http://stackoverflow.com/q/22119255
has comment: http://stackoverflow.com/comment/83981095
tagged with: string
has comment: http://stackoverflow.com/comment/83980378
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has title: How to show a np polynomial in a string?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83980800
tagged with: tkinter
type: UnansweredQuestion
has body: I'm new to Python and I was wondering if anyone knew an effective way to display a poly1d polynomial in a string (to be put in tkinter.Label), since I can't add a numpy.lib.polynomial.poly1d object in a string and therefore in the text of a label. I've tried converting the numpy.lib object to an array, and then to a string, but it displays back only the coefficients. Any ideas would be appreciated, have a great night! Here's a mini version of my code: from tkinter import * import numpy as np root=Tk() p= np.poly1d([1, 2, 3]) parray=np.array(p) pchain=np.array2string(parray) printpoly=Label(root, text="Result: %s"%(pchain)) printpoly.grid(row=1, column=1, sticky="EW", rowspan=2, columnspan=1) root.mainloop() It doesn't work because it only shows the coefficients without exponents or x variables.
answer count: 1

http://stackoverflow.com/comment/84198247
has text: This works, and is more maintainable than a regexp (I'm upvoting even if I'm still wary of edge cases :-) ). It can also be adapted to complex JSON values with [this answer](https://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values)
type: AnswerComment
comment on: http://stackoverflow.com/a/48600555
score: 0
type: Comment

http://stackoverflow.com/a/64546861
has body: I had an almost identical problem. Fixed it by reinstalling tensorflow-gpu. conda uninstall tensorflow-gpu conda install tensorflow-gpu I think pip should work as well.
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48610132

http://stackoverflow.com/comment/84154653
score: 0
has text: Do you have `apps.py` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48579232

http://stackoverflow.com/comment/84272395
has text: Try `for row in myList: print('Row:', row)` to see what `row` actually is.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48638004
type: Comment

http://stackoverflow.com/q/48544161
upvote count: 1
accepted answer: http://stackoverflow.com/a/48544205
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48544205
has title: How to save values of json fields in a list using Python
tagged with: python
type: AnsweredQuestion
has body: I have the following JSON structure: { "Users": [ { "UserName": "Administrator", "CreateDate": "2018-01-26T13:07:28Z", "UserId": "YYYYY", }, { "UserName": "test_user1", "CreateDate": "2018-01-26T14:32:13Z", "UserId": "XXXXX", }, ] } I read this file this way: jsonIAMUsers = open('reports/1.16-IAM.json', 'r') IAMUsers = json.load(jsonIAMUsers) jsonIAMUsers.close() Ho do I save the values of every UserName field into a list in order to iterate over it? I mean how can I put Administrator and test_user1 in a list?
score: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48583776
accepted answer: http://stackoverflow.com/a/48593121
tagged with: pyqt5
has body: I have a Python 3.6.3 script that incorporates PyQt5. The GUI has a button that toggles play and pause of a video file. Pressing the spacebar also toggles play and pause. The button works fine all the time. The spacebar also works as intended, except at the very start of executing the script. I need to click some other event first (such as a button or slider bar) before the spacebar will correctly triggers the signal to pause or play the video. I want to start playing the video with the spacebar when the script starts up. Here is how I create the connections in the same __init__(self) function . As you can see, clicking on the button and pressing the spacebar both connect the signal to the same function (self.pauseVideo). self.btnPause = QtWidgets.QPushButton(self.centralwidget) self.btnPause.clicked.connect(self.pauseVideo) self.spacebar = QShortcut(QKeySequence(Qt.Key_Space), self) self.spacebar.activated.connect(self.pauseVideo) Suggestions on how to get the spacebar to trigger the signal when the script first starts?
tagged with: spacebars
has comment: http://stackoverflow.com/comment/84175847
type: Question
tagged with: signals
tagged with: pyqt4
has answer: http://stackoverflow.com/a/48593121
tagged with: python
linked to: http://stackoverflow.com/q/35046381
has comment: http://stackoverflow.com/comment/84165555
has comment: http://stackoverflow.com/comment/84167069
type: AnsweredQuestion
score: 0
has title: Key Press Connect at Start of Execution
has comment: http://stackoverflow.com/comment/84182952
has comment: http://stackoverflow.com/comment/84168323
answer count: 1

http://stackoverflow.com/comment/83975981
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48491412
score: 0
has text: The first numerical values in the 2 lists have `1.0` and `0.8`. What happens to them?

http://stackoverflow.com/q/48511912
type: Question
has comment: http://stackoverflow.com/comment/84019543
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm trying to achieve the following functionality using argparse. The example usage is given below: $ test.py -ip 17.208.127.143 --current &gt;&gt;&gt; OUTPUT1 $ test.py -ip 17.208.127.143 --set 25 &gt;&gt;&gt; OUTPUT2 OR $ test.py -ip 17.208.127.143 --set 25 --time 30 &gt;&gt;&gt; OUTPUT3 "current" argument requires no parameter. "set" argument requires a number to be passed to it. "current" and "set" arguments can't be used together. "time" argument can be used only if "set" argument is present. What's the best way to achieve this? I'm using the following currently: parser.add_argument("--ip", help="IP Address", required=True) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--current", help="Current setting", required=False, action="store_true") group.add_argument("--set", help="Set the value", required=False) parser.add_argument("--time", help="Time duration", required=False) args = parser.parse_args() Can this be further optimized?
has comment: http://stackoverflow.com/comment/84019021
downvote count: 0
tagged with: argparse
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84019106
has title: argparse mutual exclusive group issue
favorite count: 0

http://stackoverflow.com/comment/84047234
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48525873
has text: Amazing great. Also it gives the same numbers as in Meshlab. So If I understand correctly, v, vn and vt are all lines for vertices that should be counted also. Thanks for the clarification!

http://stackoverflow.com/comment/84215490
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48593671
has text: What version of conda do you have, and where is it installed?
type: Comment

http://stackoverflow.com/q/48596654
score: -2
has answer: http://stackoverflow.com/a/48596696
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84190157
upvote count: 0
answer count: 2
downvote count: 2
has title: What is the different between these two list comprehension calculations?
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48596722
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84190575
has body: I've been running my own statistical analyses, but I'm curious as to why there are different outputs for the following two list comprehensions. I am using Jupyter Notebook on Ubuntu LTS 16.04: Input: example = [[15, 16, 17], [18, 19, 20]] list1 = [item[0] + item[1] + item[2] for item in example] for item in example: list2 = [item[0] + item[1] + item[2]] list1, list2 Output: ([48, 57], [57]) Clearly the second function is printing the sum of the second row, but why not the first?

http://stackoverflow.com/comment/84063907
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48534139
has text: A non-destructive way might be to use another comprehension `new = {nested['age']: {**{k:v for k,v in nested if k!="age"} for name, nested in pet_dictionary.items()}`

http://stackoverflow.com/a/48574686
has comment: http://stackoverflow.com/comment/84146423
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84146196
answers question: http://stackoverflow.com/q/48574621
has comment: http://stackoverflow.com/comment/84146106
has comment: http://stackoverflow.com/comment/84146160
has comment: http://stackoverflow.com/comment/84146370
has comment: http://stackoverflow.com/comment/84146240
type: Answer
has comment: http://stackoverflow.com/comment/84146651
accepted answer of: http://stackoverflow.com/q/48574621
has comment: http://stackoverflow.com/comment/84146264
score: 0
has comment: http://stackoverflow.com/comment/84146401
has comment: http://stackoverflow.com/comment/84146492
has comment: http://stackoverflow.com/comment/84146342
has body: 1) Save the html to disk 2) get an xml tool like xmllint and a bunch of good tutorials on XPath. 3) Test and debug your XPath until you find the solution. 4) If you have concrete questions about XPath, ask them here. let's say the element you are interested in is &lt;div class="summary_text" itemprop="description"&gt; This documentary highlights the role of education professionals in the Second Republic of Spain as the first independent and free women who broke with the female prototype of that era. &lt;/div&gt; So the xpath could be //div[@itemprop="description"] or for the english version of the page //div[@itemprop="description"]/p/text()
has comment: http://stackoverflow.com/comment/84146510

http://stackoverflow.com/comment/84112046
score: 0
has text: @ShanthaDodmane why do you care about insertion order here ? The JSON spec clearly states that json objects are _unordered_ collections of key:value pairs. Also, your "toJSON" method should be named "to_dict", since what it returns is a Python dict, not a json string.
type: Comment
comment on: http://stackoverflow.com/q/48557406
type: QuestionComment

http://stackoverflow.com/q/48629866
linked to: http://stackoverflow.com/q/24832715
tagged with: python
has title: declaring matrix as np.float32(np.array())
has answer: http://stackoverflow.com/a/48629907
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
has body: matrix = np.float32(np.array([[0.0 for i in range(dimension)] for j in range(dimension)])) If I want to do matrix operation in single precision, is the declaring array as above sufficient, or do I have to truncate for every arithmetic operation as follows? np.float32(matrix[a][b] op matrix[c][d])

http://stackoverflow.com/comment/84191038
comment on: http://stackoverflow.com/a/48566186
type: AnswerComment
has text: Update: It worked with datetime.time.today() function in date filter, maybe for my model type field.
score: 0
type: Comment

http://stackoverflow.com/comment/84043130
has text: @Jean-FrançoisFabre which is exactly why I want to avoid customizing the compiler :)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48524099
type: Comment

aes
tag name: aes
tags question: http://stackoverflow.com/q/48595705
type: Tag

http://stackoverflow.com/q/48575518
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
has body: when I use the django if function in the html template to set changes to the selected option tag, but its keep selecting the --SELECT-- option &lt;form method="post"&gt; &lt;select name="name"&gt; &lt;option &gt;--SELECT--&lt;/option&gt; {% for job in all_pekerjaan%} &lt;option value="{{job.id}}" {% if job.id == current_name %}selected="selected"{% endif %}&gt; {{job.name}} &lt;/option&gt; {% endfor %} &lt;/select&gt; {% csrf_token %} &lt;input type="submit" class="btn btn-success" value="submit" &gt; &lt;/form&gt; and this is my views.py from django.http import HttpResponse from .models import daftartabel, Pekerjaan from .forms import form1, form2 from django.template import loader from django.shortcuts import render def index(request): if request.method == 'POST': #print(request.POST['name']) current_name=request.POST['name'] all_datas = daftartabel.objects.filter(pekerjaan_id=request.POST['name']) else: all_datas = daftartabel.objects.all() all_pekerjaan = Pekerjaan.objects.all() template = loader.get_template('tabel/index.html') #print(all_datas) #print(all_pekerjaan) context = { 'all_datas' : all_datas, 'all_pekerjaan' : all_pekerjaan, 'current_name' : request.POST['name'], } #print (context) print(type(context['current_name'])) return HttpResponse(template.render(context, request)) my forms.py class class form2(forms.Form): name = forms.CharField(max_length=100) anyone know how to fix this issue?
possible better answer: http://stackoverflow.com/a/48575624
favorite count: 0
type: Question
tagged with: html-select
score: 6
tagged with: django
has title: Django : Maintaining option selected in HTML template
tagged with: python
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48575624
accepted answer: http://stackoverflow.com/a/48614263
tagged with: django-templates
answer count: 2
has answer: http://stackoverflow.com/a/48614263

http://stackoverflow.com/comment/84042271
comment on: http://stackoverflow.com/q/48523726
type: QuestionComment
has text: What is `CalcDistance`?
score: 1
type: Comment

http://stackoverflow.com/comment/84000732
has text: I had an error, the string should have been 14500.
type: QuestionComment
comment on: http://stackoverflow.com/q/48502998
score: 0
type: Comment

http://stackoverflow.com/q/48594998
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84187050
tagged with: pandas
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/84186972
has answer: http://stackoverflow.com/a/48596835
favorite count: 0
type: Question
has title: Getting xlsx file from an .aspx webpage in python
has comment: http://stackoverflow.com/comment/84186966
has comment: http://stackoverflow.com/comment/84188423
type: UnansweredQuestion
score: -2
has body: I'm trying to read an .xlsx file from the following URL, but pd.read_excel is giving an error even though the file can be successfully downloaded from the browser. http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0 import numpy as np import pandas as pd data=pd.read_excel("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0") The traceback is &gt;&gt;&gt; data=pd.read_excel("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; [...] xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\x1f\x8b\x08\x00}\xceuZ'

http://stackoverflow.com/a/48607001
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48606935
score: 1
type: Answer
has body: You are wrong that it is an array of a specific type. A Python list is implemented as an array of references to (directly or indirectly, memory addresses of) other Python objects. There is more to it than that because there is a lot of housekeeping stuff as well.

http://stackoverflow.com/comment/84282788
comment on: http://stackoverflow.com/a/48638894
score: 0
has text: Ok, my bad. I usually mistake true for false in `if` statements. This time its mistaking `/0.0125` for `/80`! I would do it like this: `round(x*80)/80`
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48513102
tagged with: ctypes
tagged with: dll
type: UnansweredQuestion
has body: Interop.zkemkeeper.dll function error No matter what I do,function 'BackupData' not found,help me,Thanks! code: # -*- coding: utf-8 -*- from __future__ import unicode_literals from ctypes import * zk = WinDLL('Interop.zkemkeeper.dll') r = zk.BackupDat print zk,r result: E:\Workspace\pycharm\door\Scripts\python.exe E:/Workspace/pycharm/door/mydoor/demo.py Traceback (most recent call last): File "E:/Workspace/pycharm/door/mydoor/demo.py", line 6, in &lt;module&gt; r = zk.BackupDat File "c:\python27\Lib\ctypes\__init__.py", line 375, in __getattr__ func = self.__getitem__(name) File "c:\python27\Lib\ctypes\__init__.py", line 380, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'BackupDat' not found Process finished with exit code 1
linked to: http://stackoverflow.com/q/47496315
tagged with: python
has comment: http://stackoverflow.com/comment/84021154
answer count: 0
score: 1
downvote count: 0
has title: How to call functions from .dll using python ctypes
upvote count: 1
has comment: http://stackoverflow.com/comment/84105441
has comment: http://stackoverflow.com/comment/84082060
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84132300

http://stackoverflow.com/q/48559167
has body: I create an array in numpy as a = np.ones([5 , 5]) I will then get an output as 5x5 array full of 1s. I would like to keep the outer elements as 1, and inner elements as 0. So I would like output to be: [[ 1. 1. 1. 1. 1.] [ 1. 0. 0. 0. 1.] [ 1. 0. 0. 0. 1.] [ 1. 0. 0. 0. 1.] [ 1. 1. 1. 1. 1.]] Is there any way with which we could do this in a single line? (I have read about inner() but I dont know how to get it working with this single array)
accepted answer: http://stackoverflow.com/a/48559229
tagged with: python
has answer: http://stackoverflow.com/a/48559229
score: 2
tagged with: numpy
type: AnsweredQuestion
upvote count: 2
tagged with: arrays
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Numpy array change value of inner elements

http://stackoverflow.com/q/48589505
accepted answer: http://stackoverflow.com/a/48602420
answer count: 1
type: Question
tagged with: python-3.x
tagged with: statsmodels
tagged with: python
has title: How to avoid statsmodels installation errors on windows ?
type: AnsweredQuestion
has body: It has been a few days I've been searching a way to install statsmodel. I want to use ggplot library. It dependencies are stated in the web site; matplotlib pandas scipy numpy statsmodels matplotlib, pandas, scipy and numpy are successfully installed in my computer. Then I type pip install --upgrade --no-deps statsmodels on command prompt and after a while I get the following error; Exception: Cython-generated file 'statsmodels/nonparametric/linbin.c' not found. Cython is required to compile statsmodels from a development branch. Please install Cython or download a source release of statsmodels. I've installed the cython using pip with the following command; pip install cython I've tried installing and once again and I get the same error. Then I've cloned the source code to my computer from github with the following command; git clone git://github.com/statsmodels/statsmodels.git I've navigated to the installation path and tried installing from setup.py file; python setup.py install From this installation I get the following error ; File "C:\user\AppData\Local\Programs\Python\Python35\lib\encodings\cp1254.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 330: character maps to Does anyone have an idea to over come this problem ? Python Version : 3.5.2 matplotlib version : 2.0.2 scipy version : 1.0.0 numpy version : 1.14.0 pandas version : 0.22.0
score: 0
has answer: http://stackoverflow.com/a/48602420

http://stackoverflow.com/q/48507168
tagged with: python
has comment: http://stackoverflow.com/comment/84091060
has body: I have a pyqt application that opens some data files. The files are displayed in a list. I want to add windows explorer right click context menu for the opened file. Something like this. I don't want to add anything in the windows explorer right click context menu. The actions listed in menu should behave like they do in actual windows explorer right click menu. Thanks
has comment: http://stackoverflow.com/comment/84017027
score: 3
has comment: http://stackoverflow.com/comment/84101663
answer count: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84021064
upvote count: 3
tagged with: pywin32
downvote count: 0
has comment: http://stackoverflow.com/comment/84024107
has title: 'Windows Explorer file right click menu' in a PyQt application
has comment: http://stackoverflow.com/comment/84021012
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/84206758
type: AnswerComment
comment on: http://stackoverflow.com/a/48605058
type: Comment
has text: Why the `lambda`? Why not simply `print(list(map(sum, x)))`. Adding the `lambda` seems to just complicate the expression and slow it down.
score: 0

http://stackoverflow.com/q/48620151
has answer: http://stackoverflow.com/a/48620349
possible better answer: http://stackoverflow.com/a/48620349
has body: Is there a way to capture and write very fast serial data to a file? I'm using a 32kSPS external ADC and a baud rate of 2000000 while printing in the following format: adc_value (32bits) \t millis() This results in ~15 prints every 1 ms. Unfortunately every single soulution I have tried fails to capture and store real time data to a file. This includes: Processing sketches, TeraTerm, Serial Port Monitor, puTTY and some Python scripts. All of them are unable to log the data in real time. Arduino Serial Monitor on the other hand is able to display real time serial data, but it's unable to log it in a file, as it lacks this function. Here's a printscreen of the serial monitor in Arduino with the incoming data:
has comment: http://stackoverflow.com/comment/84237845
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: serial-port
tagged with: python
has comment: http://stackoverflow.com/comment/84237079
upvote count: 2
tagged with: export-to-csv
type: AnsweredQuestion
answer count: 2
has title: Writing fast serial data to a file (csv or txt)
has answer: http://stackoverflow.com/a/48662224
accepted answer: http://stackoverflow.com/a/48662224
score: 1
tagged with: arduino
downvote count: 1

http://stackoverflow.com/a/48637601
has comment: http://stackoverflow.com/comment/84271511
answers question: http://stackoverflow.com/q/48637559
type: Answer
score: 4
has body: Use parameter format, reference: df["timestamp"] = pd.to_datetime(df['Invoice Date'], format='%d-%b-%y %H.%M.%S.%f %p') print (df) Invoice Date timestamp 0 16-MAR-16 11.35.27.000000000 AM 2016-03-16 11:35:27 1 05-APR-16 05.21.14.000000000 PM 2016-04-05 05:21:14 2 16-FEB-16 09.56.36.000000000 AM 2016-02-16 09:56:36 3 16-MAR-16 11.35.27.000000000 AM 2016-03-16 11:35:27 4 16-MAR-16 09.28.11.000000000 AM 2016-03-16 09:28:11 5 19-MAY-16 03.50.38.000000000 PM 2016-05-19 03:50:38 If want 2 separate columns for dates and times: d = pd.to_datetime(df['Invoice Date'], format='%d-%b-%y %H.%M.%S.%f %p') df['date'] = d.dt.date df['time'] = d.dt.time print (df) Invoice Date date time 0 16-MAR-16 11.35.27.000000000 AM 2016-03-16 11:35:27 1 05-APR-16 05.21.14.000000000 PM 2016-04-05 05:21:14 2 16-FEB-16 09.56.36.000000000 AM 2016-02-16 09:56:36 3 16-MAR-16 11.35.27.000000000 AM 2016-03-16 11:35:27 4 16-MAR-16 09.28.11.000000000 AM 2016-03-16 09:28:11 5 19-MAY-16 03.50.38.000000000 PM 2016-05-19 03:50:38
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48637559
upvote count: 4
has comment: http://stackoverflow.com/comment/84271485
has comment: http://stackoverflow.com/comment/84271572
has comment: http://stackoverflow.com/comment/84271599

http://stackoverflow.com/a/48640172
has body: After doing a lot of google searches pip install --upgrade beautifulsoup4 worked for me.
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48637930
downvote count: 0

http://stackoverflow.com/comment/84105445
has text: Please see my second edit which adds an example and explains what is the problem. The whole point is, without adjusting `i` and `j` correctly, we will train less batches when we apply the same formula to re-adjust `i` and `j`.
comment on: http://stackoverflow.com/a/48494523
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48638730
score: 2
type: AnsweredQuestion
tagged with: structured-logging
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48639029
tagged with: amazon-web-services
tagged with: logging
favorite count: 0
type: Question
has body: I use structured logging (hence: logging json strings) and I use a log identifier. So in my code, each log message has a unique identifier so that I can search in both directions: When I see a log message, I know where it comes from and when I expect log messages, I can search for this identifier. My log-strings look like this: {"log-id": "##_foo_bar-1", "message": "some explanation", "customer_id": 123} I'm not too sure if I need to do something else with Cloudwatch, as it looks like this: [2018-02-06 08:34:09,946]:[INFO]: {"log-id": "##_foo_bar-1", "message": "some explanation", "customer_id": 123} Recently, I was looking for my identifier ##_foo_bar-1 and Cloudwatch told me: I also tried: {$.log-id = "##_foo_bar-1"} No sucess. But it is for sure in the logs (I have seen it, after manually going through it). How can I find it with the search function?
tagged with: python
has answer: http://stackoverflow.com/a/48639029
has title: How can I make a full-text search through AWS Cloudwatch?
tagged with: amazon-cloudwatch

http://stackoverflow.com/comment/84102587
has text: Don't escape the backslash in your `replace()` call.
type: Comment
comment on: http://stackoverflow.com/q/48552918
score: 1
type: QuestionComment

http://stackoverflow.com/q/48572606
has body: I have a dataframe with values that change over time. Every row has current value, maximum acceptable value, minimum acceptable value and label. I would like to find for each row's 'Value' first NEXT row with value that satisfies conditions determined by Max_Val and Min_Val columns (it means first row that satisfies: Min_Val &lt; Value &lt; Max_Val). Having this column I would like to get an access to Label of that row (Then I would create additional column with future labels and join it to this DataFrame). Is it possible to do it using some pandas (or any other library) built in methods in elegant way and avoid tons of loops? import pandas as pd max_next_values = [4.5, 2.6, 13.1, 9.6, 13.1] min_next_values = [1.2, 3.3, 7.8, 4.4, 15.2] values = [1.2, 2.3, 4.4, 8.9, 16.2] labels = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'] df = pd.DataFrame({'Label': labels, 'Value': values, 'Max_Next_Val': max_next_values, 'Min_Next_Val': min_next_values}) Sample content of the dataframe: Label Max_Next_Val Min_Next_Val Value 0 monday 4.5 1.2 1.2 1 tuesday 2.6 3.3 2.3 2 wednesday 13.1 7.8 4.4 3 thursday 9.6 4.4 8.9 4 friday 13.1 15.2 16.2 Desired output: Label Max_Next_Val Min_Next_Val Value Next_Label 0 monday 4.5 1.2 1.2 tuesday 1 tuesday 2.6 3.3 2.3 2 wednesday 13.1 7.8 4.4 thursday 3 thursday 9.6 4.4 8.9 4 friday 13.1 15.2 16.2 NaN Description: 0 - we are looking for row with: 4.5 > Value > 1.2. First row after 0-indexed row has value 2.3. We take it's label 'tuesday' and put in Next_Label column 1 - 2.6 > Value > 3.3 does not exist we put nothing. 2 - we are looking for row with: 13.1 > Value > 7.8. First row (with index 3) has value that satisfies this condition we put it's label 'thursday' into Next_Label And so on... Maybe there is a better option to store min and max values that would ease computations?
type: Question
has answer: http://stackoverflow.com/a/48572736
has comment: http://stackoverflow.com/comment/84142059
has comment: http://stackoverflow.com/comment/84142453
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/84142613
has comment: http://stackoverflow.com/comment/84142519
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84142539
tagged with: python
has title: Built-in methods to work with pandas.DataFrame rows in for-each manner

http://stackoverflow.com/comment/84183576
type: AnswerComment
comment on: http://stackoverflow.com/a/48593008
type: Comment
has text: Maybe the "indexes()" module it is talking about uses this method from an inheritance that is not up to date on your platform, but has the same name ? Look into the source code of the library. It is easy finding specific keywords in random code.
score: 0

http://stackoverflow.com/comment/83993568
comment on: http://stackoverflow.com/a/48499923
score: 0
type: AnswerComment
has text: No, nothing confidential.
type: Comment

http://stackoverflow.com/a/48514100
answers question: http://stackoverflow.com/q/48503275
score: 0
has body: Levenshtein is very expensive, and I wouldn't recommend using it in fuzzy matching on this many documents (unless you want to build a levenshtein automata to generate an index of tokens n steps away from every word in your files). Trigram indexing should be fast and accurate on its own for words of a certain length, although you mention names and if that means multiple words, chunks need to be indexed as well then that needs to be implemented. If you try trigram indexing on its own, and aren't satisfied with the accuracy, you can try adding a trigram chunk index aka (Ban, ana, nan) as a tuple in addition to Ban, nan, and ana as individual trigrams, but in a separate index. This will have an even larger decrease in accuracy as character length decreases, and so that should be accounted for. Key here is that levenshtein executes at O(length of query^length of word in file*number of words in files) while token/trigram/chunk indexing executes at O(log(number of words in files)*number of tokens/chunks/trigrams in query).
type: Answer

http://stackoverflow.com/comment/83985073
score: 0
comment on: http://stackoverflow.com/q/48496032
has text: you run a different code. The line `for x1,y1,x2,y2 in lines[0]:` was changed by you to `for line in lines: for x1,y1,x2,y2 in line:`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48605374
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48605313
accepted answer of: http://stackoverflow.com/q/48605313
type: Answer
has body: There is no url or api_id variable in the scope of pass_for_request. You probably meant to access self.url and self.api_id, in python you have to use self. to access members unlike in other languages where using this. is optional. Also another thing I spotted is when you're trying to create a Price in Coindesk you are passing in api_id and the other arguments as if they are arguments with defaults, which they are not. You'd need to call it as: Price("coindesk", "https://mylinktocoindesk", "['time']['updated']") Here's some reading on OOP in python that you might find helpful: https://docs.python.org/3/tutorial/classes.html https://www.tutorialspoint.com/python/python_classes_objects.htm
score: 1

http://stackoverflow.com/comment/84059950
comment on: http://stackoverflow.com/q/48531883
type: Comment
type: QuestionComment
score: 0
has text: I tried `sock.send(cmd.encode())` and `subprocess.Popen(data.decode('utf-8'), shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)` but it still gives error.

http://stackoverflow.com/a/48491794
score: 0
has body: You need to pre-compute the max values for each letter and keep it for later. You can use a Dictionary for it: dict = {} for i in len(y): for j in len(y[i]): c = y[i][j] if not c in dict: dict[c] = x[i][j] else: dict[c] = max([dict[c], x[i][j]]) Finally just use the dict to generate z from y: z = [] for a in len(y): arr = [] for c in a: arr.append( dict[ c ] ) z.append(arr)
type: Answer
answers question: http://stackoverflow.com/q/48491493

http://stackoverflow.com/q/48631087
favorite count: 0
type: Question
tagged with: outlook
has body: Desired Outcome: I'm trying to find every message in my outlook inbox that is older than 30 days and delete those messages. Issue: The issue is, I end up trying to compare time with datetime.datetime. So I searched and found that I might need to use .strptime(). But now I'm getting this error msg: ValueError: time data '12/06/17 16:53:43' does not match format '%m/%d/%Y %H:%M:%S'. How can I get the result I'm looking for? Is there a better solution? Here is my code: for folder in default_folders: print( "Processing %s" % folder.Name ) item = folder.Items msg = item.GetFirst() print type(msg.CreationTime) #this gives 'time' instance print msg.CreationTime # prints like: 12/7/17 10:50:05 recv_time = datetime.strptime(str(msg.CreationTime), "%m/%d/%Y %H:%M:%S").date() # &lt;-- problem #datetime.replace(recv_time) i think this should be here past30days=datetime.now()-timedelta(days=30) # the date 30 days ago if recv_time &gt; past30days: # if the recv_time date is greater than 30 days, do something pass
has answer: http://stackoverflow.com/a/48632064
upvote count: 2
tagged with: time
downvote count: 0
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48632064
score: 2
type: AnsweredQuestion
tagged with: datetime
has title: python outlook delete messages greater than 30days old

http://stackoverflow.com/comment/83980487
type: Comment
comment on: http://stackoverflow.com/a/48492976
type: AnswerComment
has text: Alright then. If I use a combination of ttk and tkinter elements (spinboxes and intvars are not supported), will that affect anything? @Bryan Oakley. If not how deep can customizable go in tkinter so I can remove the pretty ugly style of most elements?
score: 0

http://stackoverflow.com/comment/84103016
type: QuestionComment
has text: @M4cJunk13 but this is iPython so it's possible to trample a built-in "permanently" which may also have happened. You may need to clear the namespace.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48553222

http://stackoverflow.com/q/48627270
linked to: http://stackoverflow.com/q/11140163
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84301563
score: 0
linked to: http://stackoverflow.com/q/41699494
answer count: 0
has title: Matplotlib 3D effects not overlapping correctly
has comment: http://stackoverflow.com/comment/84251714
tagged with: matplotlib
has body: Does anyone know how to make the arrow from the image in this post appear correctly? In places where the sphere should be behind the arrow, it appears in front. Not sure if this is a limitation of Matplotlib, but help would be greatly appreciated! See image here
type: Question

http://stackoverflow.com/a/48543040
answers question: http://stackoverflow.com/q/48542954
has comment: http://stackoverflow.com/comment/84081432
has comment: http://stackoverflow.com/comment/84081167
type: Answer
has body: List = ((0L, datetime.date(2018, 1, 29)), (0L, datetime.date(2018, 1, 30)), (1L, datetime.date(2018, 1, 31))) currentdate = time.strftime("%Y/%m/%d") cd_dt = datetime.strptime(currentdate, '%Y/%m/%d').date() return cd_dt in List Try above code. It works.
has comment: http://stackoverflow.com/comment/84081078
score: 0

http://stackoverflow.com/a/48540437
score: 0
answers question: http://stackoverflow.com/q/48540267
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84077086
has body: Edit the query in one of the following way Following query will return the data for current year, current month total_trans_today = Addfuel.objects.filter( date_created__year=datetime.today().date().year, date_created__month=datetime.today().date().month, ) Following query will return the data which was created in current month irrespective of the year total_trans_today = Addfuel.objects.filter( date_created__month=datetime.today().date().month, ) To order a queryset use order_by in ascending order, use the following query total_trans_today = Addfuel.objects.filter( date_created__year=datetime.today().date().year, date_created__month=datetime.today().date().month, ).order_by('date_created') To order a queryset in descending order, add a - sign in following total_trans_today = Addfuel.objects.filter( date_created__year=datetime.today().date().year, date_created__month=datetime.today().date().month, ).order_by('date_created') Django documentation
type: Answer
accepted answer of: http://stackoverflow.com/q/48540267

http://stackoverflow.com/a/48604520
answers question: http://stackoverflow.com/q/48604370
type: Answer
has body: You can use numpy.block: In [27]: a Out[27]: array([[1, 2], [3, 4]]) In [28]: x Out[28]: array([[4], [5]]) In [29]: y Out[29]: array([1, 2]) In [30]: z Out[30]: 4 In [31]: np.block([[a, x], [y, z]]) Out[31]: array([[1, 2, 4], [3, 4, 5], [1, 2, 4]])
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48604370
downvote count: 0
score: 6
upvote count: 6

http://stackoverflow.com/comment/84252277
score: 0
type: Comment
has text: What do you mean by open? Do you want to use something like webbrowser?
type: QuestionComment
comment on: http://stackoverflow.com/q/48612813

http://stackoverflow.com/a/48546527
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48545999
has body: It's a string, just as any other string like "Hello World!". However, it's written in a different way. In computers, each character corresponds to a number, called a code-point, according to an encoding. One such encoding that you might have heard of is ASCII, another is UTF-8. To give an example, in both encodings, the letter H corresponds to the number 72. In Python, one usually specifies a string using the matching letters, like "Hello World!". However, it is also possible to use the code-points. In python, this can be denoted with \xab, where ab is replaced with the hexadecimal form of the code-point. So H would become '\x48', because 48 is the hexadecimal notation for 72, the code-point for the letter H. In this notation, "Hello World!" becomes "\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21". The string you specify consists of the hexadecimal code-point 5b (decimal 91, the code-point for the character [), followed by the code-point 4d (M), etc., leading to the full string [MoviePlay]\r\nFileName0=C:\\. Here \r and \n are special characters together representing a line-break, so one could also read it as: [MoviePlay] FileName0=C:\\ In principle this notation is not necessarily found in viruses, but that kind of programming often requires very specific manipulation of numbers in memory without a lot of regard for the actual characters represented by those numbers, so that could explain why you'd see it arise there.
answers question: http://stackoverflow.com/q/48545999
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/84240922
has text: looks better one
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48622253

http://stackoverflow.com/a/62606761
type: Answer
has body: Here is the solution that I used to get the output, I think it will help import cv2 import os cap = cv2.VideoCapture(vidoname) time_skips = float(2000) #skip every 2 seconds. You need to modify this count = 0 success,image = cap.read() while success: cv2.imwrite("frame%d.jpg" % count, image) cap.set(cv2.CAP_PROP_POS_MSEC, (count*time_skips)) # move the time success,image = cap.read() count += 1 # release after reading cap.release()
downvote count: 0
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48517774

http://stackoverflow.com/a/48604570
type: AcceptedAnswer
downvote count: 0
has body: In Python 3.x, you may use below List Comprehension to achieve this in one line as: my_keys = ['val_a', 'val_b'] # List of keys you want to fetch val_a, val_b = [my_dict[key] for my_dict in [io.loadmat(filename)] for key in my_keys] # wrapped `dict` inside `list` in order to allow your ^ # dict available within the *list comorehension* Sample Example: &gt;&gt;&gt; my_keys = ['a', 'b'] &gt;&gt;&gt; [my_dict[key] for my_dict in [{'a': 1, 'b': 2, 'c': 3, 'd':4}] for key in my_keys] [1, 2] # returned values corresponding to 'a' , 'b' # `my_dict` can't be referenced outside the scope &gt;&gt;&gt; my_dict Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'my_dict' is not defined PS: The above code will execute on the Python 2.x too, but there will be memory leakage for the variables defined within the list comprehension. Which means, reference to my_dict will be available outside the list comprehension consuming the memory.
upvote count: 1
has comment: http://stackoverflow.com/comment/84205801
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48604495
has comment: http://stackoverflow.com/comment/84205894
accepted answer of: http://stackoverflow.com/q/48604495

http://stackoverflow.com/a/48527282
score: 7
has comment: http://stackoverflow.com/comment/84050116
type: Answer
has comment: http://stackoverflow.com/comment/84050091
has comment: http://stackoverflow.com/comment/84049638
accepted answer of: http://stackoverflow.com/q/48527267
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84050157
downvote count: 1
answers question: http://stackoverflow.com/q/48527267
upvote count: 8
has body: Square and round braces don't have the same meaning. Square braces are used to specify "any one of the chars inside". Note also that if you want to match "an", you don't want the capture to stop at "a", which means you have to reverse the order. What you want instead of [a|(an)|(the)]+ seems to be (an|a|the)+ or maybe just (an|a|the) or (less readable) (an?|the) (yes, there are often many regexes for one problem)

http://stackoverflow.com/comment/84088888
has text: In your example `n` is a list - I assume you meant `n = int(raw_input())` ?
comment on: http://stackoverflow.com/q/48546571
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83996745
type: Comment
has text: Nope sir, not that. Your script does scroll to the bottom and throws timeout exception. I don't need to scroll up or down while your script is running. However, Just a little movement (nowhere specific) of my mouse (while your scraper is running) can parse those items. I barely noticed your solution fails in many different cases.
type: AnswerComment
comment on: http://stackoverflow.com/a/48500183
score: 0

http://stackoverflow.com/comment/84219403
type: AnswerComment
comment on: http://stackoverflow.com/a/48611462
type: Comment
has text: It says `'Message' object has no attribute 'update'`. FYI I am using Django 1.11. And thumbs up for the primary key correction.
score: 0

http://stackoverflow.com/q/48545494
score: 0
has answer: http://stackoverflow.com/a/48545603
answer count: 3
has answer: http://stackoverflow.com/a/48545707
has answer: http://stackoverflow.com/a/48545746
has comment: http://stackoverflow.com/comment/84086666
tagged with: python
has comment: http://stackoverflow.com/comment/84086694
possible better answer: http://stackoverflow.com/a/48545603
has title: Python Replace string in certain line
type: Question
has body: In txt file projections.txt like this 0001|AA|17.12.2017.|20:30|21:00|ponedeljak|For a few dolars more|150|true 0002|BB|19.12.2017.|19:30|21:15|sreda|March on the Drina|300|true 0003|GG|20.12.2017.|18:00|19:00|cetvrtak|A fistful of Dolars|500|true 0004|GG|21.12.2017.|21:15|00:00|petak|The Good, the Bad and the Ugly|350|true How to change string "true" with "false" (delete) in certain line. For example, if I input 0002, how to change in 2nd line. I tried something like this, but it's not working... def delete_projection(): with open('projections.txt') as projections: #projections = open('users.txt', 'r').readlines() delete = input("Input projection code you want to delete: ") for i in projections: projection = i.strip("\n").split("|") if delete == projection[0]: projection[8]="false" #projections.close() with open('projections.txt', 'w+') as projections: projections.write("false") projections.close()
tagged with: file
tagged with: string
tagged with: text
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48545707

http://stackoverflow.com/comment/84195605
has text: Why do you have such a data structure? Did you create this yourself? What is the main problem you are trying to solve that lead you to get to this type of data structure?
score: 4
comment on: http://stackoverflow.com/q/48599380
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48545657
score: 3
upvote count: 3
type: Answer
has body: You can use multi index i.e idx = pd.MultiIndex.from_arrays(sortedd.reset_index().values.T) idx.tolist() [('chr1', 784344, 800125, 1), ('chr1', 784344, 800124, 2)]
downvote count: 0
answers question: http://stackoverflow.com/q/48545535

http://stackoverflow.com/comment/84206998
type: Comment
comment on: http://stackoverflow.com/q/48605245
score: 0
has text: `return sorted(nums1 + nums2)`
type: QuestionComment

http://stackoverflow.com/comment/84229085
score: 0
has text: Sure, but it's still the same script. And if you're running an OS where spawning a child is expensive then you're just slowing things down.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48616071

http://stackoverflow.com/a/48540014
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48539919
has body: I'd build a lookup dictionary at first: mylist = [{'name': 'Delivered-To', 'value': '123'}, {'name': 'Received', 'value': 'abc'}, {'name': 'Payload', 'value': 'xxxxxx'}] lookup_dict = dict((d['name'], d['value']) for d in mylist) &gt;&gt;&gt; print lookup_dict {'Received': 'abc', 'Delivered-To': '123', 'Payload': 'xxxxxx'} &gt;&gt;&gt; print lookup_dict['Received'] abc Of course, this works if there are no duplicate names. Alternative syntax: lookup_dict = {d['name']: d['value'] for d in mylist}
answers question: http://stackoverflow.com/q/48539919
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/48814422
upvote count: 1
answers question: http://stackoverflow.com/q/48634431
has body: The solution is to not use the 2-figure-in-1 method (as originally posted), but to create 2 separate figures. For my needs, I've rewritten the initial code such that each figure is in it's own class, and then simply placed them in a new frame side by side. I don't think using the sync_camera function is possible without such a separation, since it requires two separate figures as inputs. The result is basically identical. I successfully implemented the sync_camera function as follows: import sys, os, time import numpy as np os.environ['ETS_TOOLKIT'] = 'qt4' from pyface.qt import QtGui, QtCore from traits.api import HasTraits, Instance, on_trait_change, Str, Float, Range from traitsui.api import View, Item, HSplit, Group from mayavi import mlab from mayavi.core.api import PipelineBase, Engine from mayavi.core.ui.api import MayaviScene, MlabSceneModel, SceneEditor class Mayavi1(HasTraits): scene = Instance(MlabSceneModel, ()) @on_trait_change('scene.activated') def update_plot(self): Mayavi1.fig1 = mlab.figure(1) self.scene.mlab.clf(figure=Mayavi1.fig1) x, y, z, s = np.random.random((4, 100)) splot = self.scene.mlab.points3d(x, y, z, s, figure=Mayavi1.fig1) #splot.actor.actor.scale = np.array([25,25,25]) #if plot-types different view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=300, width=300, show_label=False), resizable=True ) class Mayavi2(HasTraits): scene = Instance(MlabSceneModel, ()) @on_trait_change('scene.activated') def update_plot(self): Mayavi2.fig2 = mlab.figure(2) self.scene.mlab.clf(figure=Mayavi2.fig2) x, y, z, s = np.random.random((4, 100)) cplot = self.scene.mlab.points3d(x, y, z, s, figure=Mayavi2.fig2) #cplot.actor.actor.position = np.array([1,1,1]) #if plot-types different view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=300, width=300, show_label=False), resizable=True ) class P1(QtGui.QWidget): def __init__(self, parent=None): super(P1, self).__init__(parent) layout = QtGui.QGridLayout(sel…
type: Answer
accepted answer of: http://stackoverflow.com/q/48634431
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48595073
downvote count: 0
tagged with: web-scraping
favorite count: 0
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/48595224
has comment: http://stackoverflow.com/comment/84196593
has answer: http://stackoverflow.com/a/48595298
has title: Web scraping a .htm page with preformatted text and no tags
has answer: http://stackoverflow.com/a/48595224
tagged with: http://stackoverflow.com/tag/html
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/84188320
accepted answer: http://stackoverflow.com/a/48595298
answer count: 2
has body: I'm a newbie working on a web scraping project. I need to get these election results into a dataframe (or Excel) in order to analyze it. What's been most tricky is that it is a .htm file with all the data as one big text block in between "Preformatted Text" (PRE) tags, and no individual tags on the data itself. I am only interested in the parts of the data that are set up like tables: https://www.stlouisco.com/portals/8/docs/document%20library/elections/eresults/el140805/EXEC.htm I have been attempting it in Python with BeautifulSoup. However, if you view the source code at the URL, you can see why BeautifulSoup isn't getting me very far -- because the data isn't structured using tags. The structure looks like this, basically: COUNTY EXECUTIVE PRIMARY ELECTION OFFICIAL FINAL RESULTS ST. LOUIS COUNTY, MISSOURI RUN DATE:08/18/14 01:20 PM TUESDAY, AUGUST 5, 2014 STATISTICS WITH 681 OF 681 PRECINCTS REPORTING TOTAL PERCENT TOTAL PERCENT 01 = REGISTERED VOTERS - TOTAL 661,393 05 = BALLOTS CAST - LIBERTARIAN 1,121 .58 02 = BALLOTS CAST - TOTAL 192,495 06 = BALLOTS CAST - CONSTITUTION 314 .16 03 = BALLOTS CAST - DEMOCRATIC 129,918 67.49 07 = BALLOTS CAST - NONPARTISAN 6,225 3.23 04 = BALLOTS CAST - REPUBLICAN 54,917 28.53 08 = VOTER TURNOUT - TOTAL 29.10 - - - - - - - - - - - - - - - - - - - - - - - - 01 02 03 04 05 06 07 08 - - - - - - - - - - - - - - - - - - - - - - - - 0101 AP1,2,7,43 1317 . 298 . 214 . 69 . . 3 . . 1 . 11 22.63 0103 AP3,27 NRW2,8,15,29 1453 . 186 . 179 . . 5 . . 1 . . 0 . . 1 12.80 0104 AP4 231 . 51 . 34 . . 4 . . 0 . . 0 . 13 22.08 0105 AP5,18,21,39 1289 . 268 . 198 . 47 . . 4 . . 1 . 18 20.79 0106 AP6 2 . . 1 . . 0 . . 0 . . 0 . . 0 . . 1 50.00 0108 AP8,20 586 . 142 . 86 . 44 . . 4 . . 0 . . 8 24.23 0109 AP9,25 533 . 119 . 85 . 29 . . 2 . . 3 . . 0 22.33 0110 AP10 1044 . 158 . 114 . 34 . . 2 . . 0 . . 8 15.13 ... 2832 WH32,38,44 296 . 51 . 23 . 28 . . 0 . . 0 . . 0 17.23 2834 WH34,43 2043 . 609 . 267 . 321 . . 1 . . 0 . 20 29.81 2835 WH35 543 . 173 .…
upvote count: 3

http://stackoverflow.com/q/48492164
type: UnansweredQuestion
tagged with: machine-learning
has title: TensorFlow - IndexError: index 2 is out of bounds for axis 1 with size 2
has comment: http://stackoverflow.com/comment/83977506
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/83977615
tagged with: tflearn
tagged with: python
type: Question
score: 0
has body: I was walking through this tutorial, and tried to evaluate the model as follows: model.evaluate(test_x, test_y) I however get the following error: return [x[start] for x in X] IndexError: index 2 is out of bounds for axis 1 with size 2 Why is that? How can I solve this issue? EDIT This is the size of my test data: test_x: (36, 9, 6, 1) test_y: (36, 2) Would that be an issue? Thanks.
answer count: 0
tagged with: deep-learning

http://stackoverflow.com/q/48643212
has body: I am searching to validate my idea on the decision tree algorithm. That is why I have installed Anaconda3 and try to understand where I should modify (I am a beginner user of python language). I have understood that modification should be on the file _criterion.pyx under site-packages/sklearn/tree. Infact, under this path there is only _criterion.pyd which is already the compiled file of _criterion.pyx. My question is how to recompile the .pyx file and how to use the configuration file (setup.py) in order to take into account the added modifications when using the DecisionTreeClassifier class.
has comment: http://stackoverflow.com/comment/84284608
tagged with: scikit-learn
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84287488
upvote count: 3
has comment: http://stackoverflow.com/comment/84282926
score: 3
has comment: http://stackoverflow.com/comment/84283290
tagged with: python
has comment: http://stackoverflow.com/comment/84284420
has comment: http://stackoverflow.com/comment/84285182
has title: how can I compile a modification on the file _criterion.pyx under the sklearn library of python
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84102510
type: AnswerComment
comment on: http://stackoverflow.com/a/48552373
has text: Thanks @Suraj Kothari. This is the closest I got. It is returning an empty line after every handle instead of just the handle. Is there any way to remove these empty lines?
type: Comment
score: 0

http://stackoverflow.com/comment/84005560
comment on: http://stackoverflow.com/a/48505183
score: 0
type: Comment
has text: This solution covers what I intended to do! I didn't think about using two queues for this purpose. Thank you very much.
type: AnswerComment

http://stackoverflow.com/comment/84036647
score: 0
type: AnswerComment
has text: got an error `'Timedelta' object has no attribute 'dt'`, no idea why
comment on: http://stackoverflow.com/a/48520603
type: Comment

http://stackoverflow.com/comment/84119526
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48561909
has text: @Mawg nope, `Tokenizer` is a class in the `keras.preprocessing.text` module
type: Comment

http://stackoverflow.com/q/48517476
has comment: http://stackoverflow.com/comment/84029885
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48559495
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/84031149
type: UnansweredQuestion
has title: Find angle between normal and perspective images
tagged with: math
tagged with: python
tagged with: computer-vision
linked to: http://stackoverflow.com/q/36590516
has answer: http://stackoverflow.com/a/48547680
score: 2
answer count: 2
upvote count: 3
has body: I have 2 photos of chessboard from camera. I need to find angle between planes on 2 images. For example we have normal "chessboard" image, after some transformations we got a new image in perspective "chessboard2". Is it possible to find angle between those planes? Normal chessboard: Normal Perspective chessboard: Perspective For understanding: i try to find angle φ between planes.image φ I've tried to solve this by python(opencv) program. I used cv2.getPerspectiveTransform() function to find transformation matrix, but i can't pull out the angles I need :( Thank you!

http://stackoverflow.com/q/48640937
has comment: http://stackoverflow.com/comment/84280877
tagged with: loops
upvote count: 1
favorite count: 0
type: Question
score: 1
has answer: http://stackoverflow.com/a/48643044
tagged with: python
tagged with: survival-analysis
type: AnsweredQuestion
has body: In my dataset data1, I have a column Region, with 3 categories:Asia, Europe, North America. Now I'm trying to fit in a KM model for survival analysis of certain machine parts belonging to these 3 regions. The variable being used is number of hours of operation before the machines collapse. I've used the following code, which runs fine: T=data1['op_hours'] Region_Asia=(data1['Region'] == 'ASIA') Region_EUROPE=(data1['Region'] == 'EUROPE') Region_NORTH=(data1['Region'] == 'NORTH AMERICA') from lifelines import KaplanMeierFitter kmf = KaplanMeierFitter() ax = plt.subplot(111) kmf.fit(T[Region_Asia], label="Asia") kmf.plot(ax=ax,ci_force_lines=False) kmf.fit(T[Region_EUROPE], label="Europe") kmf.plot(ax=ax, ci_force_lines=False) kmf.fit(T[Region_NORTH], label="North America") kmf.plot(ax=ax, ci_force_lines=False) plt.ylim(0, 1); plt.title("Lifespans of different machines") I get the following plot: Now, I'm trying to create a function so that I won't have to write separate lines of codes for each of the categories in order to obtain the KM fit. I've tried this: def Kaplan(c): a=[] u=[] u=c.unique() T=data1['op_hours'] from lifelines import KaplanMeierFitter kmf = KaplanMeierFitter() ax = plt.subplot(111) for i in range(len(u)): a=u[i] kmf.fit(T[a]) kmf.plot(ax=ax,ci_force_lines=False) plt.ylim(0, 1); plt.title("Lifespans of different machines") Kaplan(data1.Region) I'm getting: KeyError: 'ASIA' Can somebody help me out here, I'm still a newbie in coding. Thanks a lot.
accepted answer: http://stackoverflow.com/a/48643044
has title: Function to run KaplanMeier model(Python)
tagged with: function
has comment: http://stackoverflow.com/comment/84279231
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84168842
has text: @Wen unfortunately I do not see that there is an array or a list used to adress certain rows. Please correct me if I am wrong.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48585708
score: 0

http://stackoverflow.com/comment/84112374
has text: Possible solution is create html and modify it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48558213
type: Comment

http://stackoverflow.com/a/48596742
answers question: http://stackoverflow.com/q/48596542
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48596542
score: 8
upvote count: 8
has body: You don't need enumerate in order to check the elements of your lists are continuous. You can simply achieve it via creating a function using zip and all as: def check_continuity(my_list): return all(a+1==b for a, b in zip(my_list, my_list[1:])) Same result can be achieved by any with zip as (similar to all but with not and != for comparision): def check_continuity(my_list): return not any(a+1!=b for a, b in zip(my_list, my_list[1:])) Above functions will return True/False depending upon whether your list is continuous or not. Sample run: # Continuous Lists &gt;&gt;&gt; check_continuity([3, 4, 5]) True &gt;&gt;&gt; check_continuity([7, 8, 9]) True &gt;&gt;&gt; check_continuity([1, 2, 3]) True # Non Continuous Lists &gt;&gt;&gt; check_continuity([9, 1, 0]) False &gt;&gt;&gt; check_continuity([3, 2, 4]) False &gt;&gt;&gt; check_continuity([5, 5]) False In order to print "YES"/"NO", you may make a simple if..elsecheck outside the function call as: &gt;&gt;&gt; "YES" if check_continuity([1, 2, 3]) else "NO" 'YES' # OR update the return statement in your function to # return "NO" if any(a+1!=b for a, b in zip(my_list, my_list[1:])) else "YES"
type: Answer

http://stackoverflow.com/a/48492635
has comment: http://stackoverflow.com/comment/117333264
accepted answer of: http://stackoverflow.com/q/48492451
upvote count: 11
has comment: http://stackoverflow.com/comment/117333858
has body: There is open Pandas issue describing this error. AFAIK currently there is no solution/workaround provided, except reducing the data set
answers question: http://stackoverflow.com/q/48492451
type: AcceptedAnswer
downvote count: 0
score: 11
has comment: http://stackoverflow.com/comment/117333044
has comment: http://stackoverflow.com/comment/118181129
type: Answer
has comment: http://stackoverflow.com/comment/117333663
has comment: http://stackoverflow.com/comment/118184239
has comment: http://stackoverflow.com/comment/117333962

http://stackoverflow.com/a/48619832
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48619194
has body: You can try with: df['timestamp'] = df['timestamp'].str[1:-1] df['timestamp'] = pd.to_datetime(df['timestamp'] )

http://stackoverflow.com/q/48521184
has comment: http://stackoverflow.com/comment/84043276
answer count: 1
has comment: http://stackoverflow.com/comment/84038803
has comment: http://stackoverflow.com/comment/84037250
has comment: http://stackoverflow.com/comment/84042574
has comment: http://stackoverflow.com/comment/84038470
has comment: http://stackoverflow.com/comment/84040598
has comment: http://stackoverflow.com/comment/84043301
has comment: http://stackoverflow.com/comment/84043661
has comment: http://stackoverflow.com/comment/84039810
has comment: http://stackoverflow.com/comment/84040211
has comment: http://stackoverflow.com/comment/84039629
tagged with: socket.io
has comment: http://stackoverflow.com/comment/84037299
has comment: http://stackoverflow.com/comment/84043163
has comment: http://stackoverflow.com/comment/84037527
has comment: http://stackoverflow.com/comment/84038283
has comment: http://stackoverflow.com/comment/84038715
favorite count: 0
has comment: http://stackoverflow.com/comment/84037380
tagged with: android-studio
type: Question
has comment: http://stackoverflow.com/comment/84039127
has title: Android handler bufferedreader.read() closes the app when recieving data
has comment: http://stackoverflow.com/comment/84041846
has body: hi im new in android programming and in sockets im trying to recieve a data from the client, when i use .readline() my textview only updates when i close the client program in python so i use .read() the app closes what could be the problem? this is the code: class Mythread implements Runnable{ Handler h = new Handler(); @Override public void run() { Socket s; ServerSocket ss; InputStreamReader ist; BufferedReader bufferedReader; try { ss = new ServerSocket(21600); s = ss.accept(); ist = new InputStreamReader(s.getInputStream()); bufferedReader = new BufferedReader(ist); while (true){ final String message = bufferedReader.readLine(); Log.d("message", "message: " + message); h.post(new Runnable() { @Override public void run() { ballscollect.setText(message); } }); } }catch (IOException e) { e.printStackTrace(); } } } this is my python client code where every time the switch is clicked it will send a output string to the app: import socket from nanpy import (ArduinoApi, SerialManager) import time import thread import Adafruit_CharLCD as LCD import math lcd_rs = 26 lcd_en = 19 lcd_d4 = 13 lcd_d5 = 6 lcd_d6 = 5 lcd_d7 = 11 lcd_backlight = 4 lcd_columns = 16 lcd_rows = 2 lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight) lcd.message ('Balls Collected') ledpin = 13 buttonpin = 12 buttonpin1 = 2 buttonpin2 = 3 buttonstate1 = 1 buttonstate2 = 1 buttonstate3 = 1 connection = SerialManager() a = ArduinoApi(connection = connection) a.pinMode(ledpin, a.OUTPUT) a.pinMode(buttonpin, a.INPUT) a.pinMode(buttonpin1, a.INPUT) a.pinMode(buttonpin2, a.INPUT) host = '192.168.1.7' port = 21600 sock = socket.socket() sock.connect((host,port)) def count(): add = 0 while True: buttonstate1 = a.digitalRead(buttonpin) buttonstate2 = a.digitalRead(buttonpin1) buttonstate3 = a.digitalRead(buttonpin2) if buttonstate1: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) lcd.message ('\n'+s) sock.sen…
has comment: http://stackoverflow.com/comment/84037101
upvote count: 2
has comment: http://stackoverflow.com/comment/84043645
has comment: http://stackoverflow.com/comment/84043024
has comment: http://stackoverflow.com/comment/84038306
has comment: http://stackoverflow.com/comment/84037005
tagged with: sockets
has comment: http://stackoverflow.com/comment/84040301
has comment: http://stackoverflow.com/comment/84038386
has comment: http://stackoverflow.com/comment/84039746
tagged with: android
has comment: http://stackoverflow.com/comment/84042722
has comment: http://stackoverflow.com/comment/84043303
downvote count: 0
has comment: http://stackoverflow.com/comment/84038581
has comment: http://stackoverflow.com/comment/84040222
has comment: http://stackoverflow.com/comment/84043697
has comment: http://stackoverflow.com/comment/84037908
has comment: http://stackoverflow.com/comment/84037691
has comment: http://stackoverflow.com/comment/84036935
has comment: http://stackoverflow.com/comment/84041298
tagged with: python
linked to: http://stackoverflow.com/q/35660738
has comment: http://stackoverflow.com/comment/84038120
accepted answer: http://stackoverflow.com/a/48524480
has comment: http://stackoverflow.com/comment/84043031
has comment: http://stackoverflow.com/comment/84040339
has comment: http://stackoverflow.com/comment/84039077
has comment: http://stackoverflow.com/comment/84037843
has answer: http://stackoverflow.com/a/48524480
has comment: http://stackoverflow.com/comment/84040163
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84038768
has comment: http://stackoverflow.com/comment/84038555
has comment: http://stackoverflow.com/comment/84037702
has comment: http://stackoverflow.com/comment/84043421
has comment: http://stackoverflow.com/comment/84037142

http://stackoverflow.com/q/48492341
accepted answer: http://stackoverflow.com/a/48494715
has body: I can't even get a task queue to fire a simple print statement. I don't know if my app structure is incorrect or not... What's the most simple example of a task queue and the structure for it? Because this isn't working for me: @app.route('/task', methods=["GET", "POST"]) def testtask(): print "Hi, I'm calling the task" taskqueue.add( url='/execute_task' ) return "I called the task" @app.route('/execute_task', methods=["GET", "POST"]) def execute_task(): print "I'm executing the task" return "I excecuted the task" both routes are in the app.yaml file: - url: /execute_task script: app.app login: admin - url: /task script: app.app login: admin in terminal: Hi, I'm calling the task INFO 2018-01-28 23:00:49,521 module.py:788] default: "GET /task HTTP/1.1" 200 17 http://localhost:8000/taskqueue shows: Queue Name Maximum Rate Bucket Size Oldest Task (UTC) Tasks in Queue default 5.00/s 5 2018/01/28 22:59:59(0:04:44 ago) 2
has answer: http://stackoverflow.com/a/48494715
answer count: 1
tagged with: task-queue
favorite count: 0
type: Question
upvote count: 2
tagged with: google-app-engine
downvote count: 0
tagged with: python
has title: Simple Google App Engine Task Queue tutorial? Flask/ Python/ GAE
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/48618827
tagged with: ubuntu
type: AnsweredQuestion
downvote count: 2
answer count: 1
has body: What is it the best way to create a log that resume the percentage of resources (ram, cpu ...) used in each execution of python script.
upvote count: 1
accepted answer: http://stackoverflow.com/a/48619245
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48619245
has title: Log with % resources used on python script
tagged with: python
score: -1

http://stackoverflow.com/q/48603283
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48603305
has title: pandas - intersect dataframes by index.name
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48604405
score: 2
has answer: http://stackoverflow.com/a/48603314
answer count: 3
tagged with: pandas
upvote count: 3
has body: I have two dataframes that share (some) ids (specified in index.name) and I want to intersect them. So given: dfA.index.name = 'id' dfB.index.name = 'id' and dfA being like: count id 1 15 3 16 8 1 and dfB being like: owns id 1 True 3 False 12 False I want to obtain dfC being like: count owns id 1 15 True 3 16 False I tried s1 = pd.merge(dfA, dfB, how='inner', on=['id']) without success
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/48548039
type: UnansweredQuestion
tagged with: python
has body: After reading this which works with Python 3.5, spaCy version 1.1.2. I tried doing this from spacy.lang.en import English nlp = spacy.load('en') text2 = u'he has a ph.D. in tacology' nlp.Defaults.tokenizer_exceptions['Ph.D.'] = [{'F':'Ph.D.'}] tokens = parser(text2) tokens = [token.orth_ for token in tokens if not token.orth_.isspace()] This gives: [u'he', u'has', u'a', u'ph', u'.', u'D.', u'in', u'tacology'] when I was expecting: [u'he', u'has', u'a', u'ph.D.', u'in', u'tacology'] Why does tokenizer_exceptions not work? Is it because I'm using version 2 and it is implemented differently? How would I do the equivalent in v2? NB I did look at Tokenizer.add_special-case in the v2 spacy docs here but I couldn't figure out a solution
score: 0
tagged with: tokenize
has title: segment sentences with spaCy tokenizer exceptions changed in v2?
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/48568284
tagged with: spacy

http://stackoverflow.com/comment/84082035
score: 0
type: Comment
has text: Thanx for your suggestion! My data comes as a numpy array, numpy operations (like np.real or np.real_if_close) return numpy data types. That's why I ruled out lists. What do you mean by "using a look"? Still, I'd like to understand the "non-empty format string passed to object.__format__" error message and why I'm getting it in only one of the cases described above.
comment on: http://stackoverflow.com/a/48542245
type: AnswerComment

http://stackoverflow.com/comment/105246140
score: 0
comment on: http://stackoverflow.com/a/52614420
type: Comment
type: AnswerComment
has text: @Mr-Programs `pipenv lock -r` as opposed to `pip freeze` gets you sha256 hashes for packages, which I prefer as my code is more reproducible. From [the docs](https://pipenv.readthedocs.io/en/latest/basics/#example-pipfile-pipfile-lock): "Note If you’d like a requirements.txt output of the lockfile, run $ pipenv lock -r. This will include all hashes, however (which is great!). To get a requirements.txt without hashes, use $ pipenv run pip freeze."

http://stackoverflow.com/a/48529998
type: Answer
has body: Review your csv file. It is hard to say without seeing what's in the file, but the most likely explanation (according to the error message) is that you have a line for which the forth value is empty, e.g: 2018-01-30,5,12, So the rf variable would be empty when parsing that line, and the you would get that ValueError when trying to cast the value as a float. Also, some advice on how to do it better: You may want to split your line first, then count how many data fields it has, and then discarding it before assigning the whole line to date, l, h, rf. Something like this: ` for line in infile: # Get data from line. Use strip() to avoid whitespace items = line.strip().split(',') if len(items) != 4: # skip the iteration - do nothing with that malformed line continue date, l, h, rf = items ` You may want to have a look at the csv module for reading/writing csv files easily.
score: 0
answers question: http://stackoverflow.com/q/48528775

http://stackoverflow.com/a/48632125
score: 1
type: Answer
has body: Assuming you don't want to use numpy. matrix = [[True, False, False], [True, True, True], [False, True, True]] valid_choices = [(i,j) for i, x in enumerate(matrix) for j, y in enumerate(x) if not y] random.choice(valid_choices) With list comprehensions, you can change the if condition (if not y) to suit your needs. This will return the coordinate that is randomly selected, but optionally you could change the value part of the list comprehension (i,j) in this case to: y and it'd return false, though thats a bit redundant in this case.
answers question: http://stackoverflow.com/q/48631962
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48589994
type: Answer
answers question: http://stackoverflow.com/q/48589734
has body: You should look into pytz Python: display the time in a different time zone will be helpful too
score: 0

http://stackoverflow.com/comment/84207215
type: Comment
type: QuestionComment
has text: You should update your post with the code, not a comment
comment on: http://stackoverflow.com/q/48605066
score: 0

http://stackoverflow.com/comment/83975110
has text: The question is not really clear. What is the input and what is the output?
type: Comment
comment on: http://stackoverflow.com/q/48491018
type: QuestionComment
score: 4

http://stackoverflow.com/comment/84261565
has text: Possible duplicate of [pickle.PicklingError: Can't pickle '\_subprocess\_handle' object: <\_subprocess\_han dle object at 0x00AAAAAAA>](https://stackoverflow.com/questions/32003657/pickle-picklingerror-cant-pickle-subprocess-handle-object-subprocess-han)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48632225
type: QuestionComment

http://stackoverflow.com/a/48559869
has body: A bit long and not the most efficient, but it gets the job done: def getData(): loc_keys = {} with open(FILE_PATH, 'r') as f: next(f) for line in f: line = line.split() loc, key = line[0], line[1] if loc not in loc_keys: loc_keys[loc] = set([]) loc_keys[loc].add(key) return loc_keys def is_adjacent(loc1, loc2): if int(loc1[-1]) == int(loc2[-1]) + 1 or \ int(loc1[-1]) == int(loc2[-1]) - 1 or \ ord(loc1[-4]) == ord(loc2[-4]) + 1 or \ ord(loc1[-4]) == ord(loc2[-4]) - 1: return True else: return False def find_matches(loc, loc_keys): if loc not in loc_keys: return None keys = loc_keys[loc] # Set of keys for the input location matches = set([]) for i in loc_keys.keys(): # {*()} is an empty set literal if is_adjacent(loc, i) and loc_keys[i].intersection(keys) != {*()}: matches.add(i) return matches # Call find_matches( &lt;some LocationIndex&gt;, getData() )
answers question: http://stackoverflow.com/q/48557624
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84119434
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48557624
has comment: http://stackoverflow.com/comment/84137970
type: Answer
has comment: http://stackoverflow.com/comment/84145523
has comment: http://stackoverflow.com/comment/84151176

http://stackoverflow.com/comment/84161834
score: 0
comment on: http://stackoverflow.com/q/48574572
type: Comment
type: QuestionComment
has text: @BradleyO'Hara : I have updated my answer for you new error

http://stackoverflow.com/comment/84133542
has text: I figured it out. I renamed `Widget.model` to self.model and was able to access it from within `on_data_changed` by calling `self.model.table_data`. Thanks again so much!
type: Comment
comment on: http://stackoverflow.com/a/48566755
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84109977
comment on: http://stackoverflow.com/q/48556651
type: Comment
type: QuestionComment
score: 0
has text: and what is the issue you are facing currently?

http://stackoverflow.com/comment/83988842
score: 0
has text: @WarrenWeckesser. Ok. At first I though I had a `from .stats import *` in scipy/__init__.py, which would have explained why I got no error. Actually the script that led me to think that `import scipy as sc;sc.stats` was universally working, relies on [PySAL](http://pysal.readthedocs.io/en/latest/). In one of its script, i.e. [common.py](https://pypkg.com/pypi/pysal/f/pysal/common.py) it reads `import scipy as sp;import scipy.stats as stats`. And doing `print(sp.stats)` afterwards fallaciously works.
type: Comment
comment on: http://stackoverflow.com/q/48491649
type: QuestionComment

bash
tags question: http://stackoverflow.com/q/48605957
tags question: http://stackoverflow.com/q/48508668
tags question: http://stackoverflow.com/q/48551165
tags question: http://stackoverflow.com/q/48597930
tags question: http://stackoverflow.com/q/48524196
tags question: http://stackoverflow.com/q/48562073
tags question: http://stackoverflow.com/q/48514410
tags question: http://stackoverflow.com/q/48571960
tags question: http://stackoverflow.com/q/48639666
type: Tag
tags question: http://stackoverflow.com/q/48630276
tags question: http://stackoverflow.com/q/48578285
tags question: http://stackoverflow.com/q/48573376
tags question: http://stackoverflow.com/q/48597496
tags question: http://stackoverflow.com/q/48524846
tags question: http://stackoverflow.com/q/48644937
tags question: http://stackoverflow.com/q/48571792
tags question: http://stackoverflow.com/q/48614244
tags question: http://stackoverflow.com/q/48573443
tags question: http://stackoverflow.com/q/48563269
tags question: http://stackoverflow.com/q/48502300
tags question: http://stackoverflow.com/q/48608814
tags question: http://stackoverflow.com/q/48609015
tags question: http://stackoverflow.com/q/48504316
tags question: http://stackoverflow.com/q/48516449
tags question: http://stackoverflow.com/q/48519014
tags question: http://stackoverflow.com/q/48515595
tag name: bash
tags question: http://stackoverflow.com/q/48574132
tags question: http://stackoverflow.com/q/48571463
tags question: http://stackoverflow.com/q/48509732
tags question: http://stackoverflow.com/q/48630180

http://stackoverflow.com/q/48593203
has title: Why can't I simulate a right click here? (with Python)
tagged with: right-click
answer count: 1
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48597028
type: UnansweredQuestion
tagged with: python
tagged with: mouseevent
has body: I'm very new to programing so please forgive me if this has an obvious answer and just so you know I tried to write a program that performs a fishing glitch in the game Terraria. In the last bit of my code [Main Program] I used the function gui.rightClick(). The function itself works but not in the game. I also tried it with the mouse library where I used the function mouse.right_click() and came to the same result so I figured that it has to do something with the game. Can someone tell me why that is and if there is a way around that? It would really help me so thanks in advance!!! :D Oh and if you know how to improve my code please go right ahead and tell me. Thanks again. import pyautogui as gui import keyboard, _thread, sys, time # Global variable for shutting down the program shutDown = False # Position of disposable stuff in the inventory item_x, item_y = 279, 233 # Function that tells the main thread to shut down def pClose(): global shutDown while True: try: if keyboard.is_pressed("alt+c"): shutDown = True sys.exit() except: continue # Function that checks if it's supposed to shut down the main thread def pQuit(sD): if sD == True: sys.exit() # Initializing thread with pClose() _thread.start_new_thread(pClose,()) # Start Position of the Cursor while True: try: if keyboard.is_pressed("alt+p"): start_x, start_y = gui.position() break except: continue time.sleep(2) # Main Program for i in range(10): pQuit(shutDown) gui.press("e") pQuit(shutDown) gui.moveTo(item_x, item_y, duration= 0.25) pQuit(shutDown) gui.rightClick() pQuit(shutDown) gui.moveTo(start_x, start_y, duration= 0.25) pQuit(shutDown) gui.rightClick() pQuit(shutDown) gui.press("e") pQuit(shutDown) time.sleep(0.5) More Info: I can't simulate any kind of mouse click with these two libraries in Terraria but with the program SpeedAutoClicker it does (but that's no really helpful)
score: 0

timedelta
tags question: http://stackoverflow.com/q/48534114
type: Tag
tag name: timedelta
tags question: http://stackoverflow.com/q/48536493
tags question: http://stackoverflow.com/q/48602892
tags question: http://stackoverflow.com/q/48627387

http://stackoverflow.com/comment/84062594
score: 0
type: Comment
type: QuestionComment
has text: Yes. I'm using Pandas.
comment on: http://stackoverflow.com/q/48533422

http://stackoverflow.com/a/53579531
answers question: http://stackoverflow.com/q/48547660
upvote count: 5
type: Answer
score: 5
downvote count: 0
has body: run these 3 lines at the start of your colab notebook !pip install Pillow==4.0.0 !pip install PIL !pip install image I was also struggling with the same issue. But this has worked for me. https://pillow.readthedocs.io/en/3.1.x/reference/Image.html

http://stackoverflow.com/q/48526360
answer count: 1
downvote count: 0
tagged with: pip
score: 11
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51088908
has title: Should we put all required and their dependent packages on requirement.txt or only required packages
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51088908
tagged with: python
upvote count: 11
type: AnsweredQuestion
tagged with: python-2.7
has body: If I install one package Eg: pip install bpython on newly created virtualenv what I receive when I execute pip freeze Output: blessings==1.6.1 bpython==0.17 certifi==2018.1.18 chardet==3.0.4 curtsies==0.2.11 greenlet==0.4.12 idna==2.6 Pygments==2.2.0 requests==2.18.4 six==1.11.0 urllib3==1.22 wcwidth==0.1.7 Question: Should we need to put all these in requirement.txt file or just bpython==0.17 Once i was asked to clean up requirement.txt file, so i did updated the code from pip freeze &gt; requirement.txt TO comm -12 &lt;(pip list --format=freeze --not-required) &lt;(pip freeze) &gt; requirements.txt And I am still not sure whether I should put all packages what i receive form pip freeze or it's okay/better to put only those required packages without dependent packages. Reading the Document of PIP what I found closest is: Requirements files are used to force pip to properly resolve dependencies. As it is now, pip doesn't have true dependency resolution, but instead simply uses the first specification it finds for a project. I am still as confused as I was earlier, HELP will be appreciated...
has comment: http://stackoverflow.com/comment/84047869

http://stackoverflow.com/a/48563281
downvote count: 0
type: AcceptedAnswer
score: 16
upvote count: 16
accepted answer of: http://stackoverflow.com/q/48562935
answers question: http://stackoverflow.com/q/48562935
has body: An email message consists of a single MIME part, or a multipart structure with multiple MIME parts. If there is no multipart structure, the message is compatible with pre-MIME RFC822 messages, and the Content-type: etc headers are optional (if you don't spell out a content type and encoding, Content-type: text/plain; charset="us-ascii" and Content-transfer-encoding: 7bit are implied, but they are still good to spell out for human readers; before MIME, inferring the type and encoding of content was more of a wild west best-guess situation). There is no strict hierarchy or guidance for how exactly to use multipart messages. MIME simply defines a way to collect multiple payloads into a single email message. One of the original motivations I believe was to be able to embed pictures in text; but being able to attach binaries to a text message, and more generally, being able to create structured messages with payloads which are related in arbitrary ways is something which has simply been there for applications to use in whatever way they see fit. A common misunderstanding is postulating a hierarchy into a "main part" and "subordinate" parts. It's certainly possible to create this structure, but it is by no means universally done. In fact, most multipart messages simply have a sequence of parts without any hierarchy. The user's email client will commonly pick one of the "inline" parts as the preferred "main" part to display in a message pane, but this is by no means dictated by the standard, or possible to enforce by the sending party. Each MIME part has a set of headers which tell you the type, encoding, and disposition; for parts of type text/* the default disposition is "inline" (so it is often not explicitly spelled out) whereas most other parts have a default disposition of "attachment". You'll need to refer to the pertinent standards for a strict definition, but probably take it with a grain of salt, because many real-world applications are not particularly RFC-confo…
type: Answer
has comment: http://stackoverflow.com/comment/133885454
has comment: http://stackoverflow.com/comment/97264539

http://stackoverflow.com/q/48513371
upvote count: 4
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48513687
has answer: http://stackoverflow.com/a/48513687
has title: Using IFTTT to check JSON content and send Email or Text Message
tagged with: ifttt
tagged with: python
score: 4
has body: I am trying to learn how to use the new WebHooks service on IFTTT, and I'm struggling to figure out how it is supposed to work. Most of the projects I can find online seem to refer to a deprecated "maker" service, and there are very little resources for interpreting the new channel. Let's say I want to check the value of "online" every ten minutes in the following json file: https://lichess.org/api/users/status?ids=thibault I can write a Python script that extracts this value like so: response = urlopen('https://lichess.org/api/users/status?ids=thibault') thibault = response.read() data = json.loads(thibault) status = data[0]['online'] If the status is equal to "true", I would like to receive a notification via email or text message. How do I integrate the python script and the webhooks service? Or do I even need to use this script at all? I assume I need some kind of cron job that regularly runs this Python script, but how do I connect this job with IFTTT? When I create a new applet on IFTTT I am given the ability to create a trigger with a random event name, but it's unclear what that event name corresponds to.

http://stackoverflow.com/q/48524920
has title: Django CBV - get url variable for use in class, error self s not defined
type: Question
accepted answer: http://stackoverflow.com/a/48525334
has answer: http://stackoverflow.com/a/48525327
has body: I am passing and trying to use site_id in my add form. I want to pre fill and hide the site_data field with the site ID in the url. and then use that variable to pass some more information to the context too. my CBV is as such: class AddSubnet(CreateView): model = SiteSubnets template_name = "sites/edit_subnet.html" fields = ['device_data', 'site_data', 'subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc'] site_id = self.kwargs['site_id'] site = get_object_or_404(SiteData, pk=site_id) @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet'))) def dispatch(self, *args, **kwargs): return super(AddSubnet, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_subnets", args = (site_id,)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=site_id context['SiteName']=site.location context['active_subnets']='class="active"' # return context this currently yields with: File "/itapp/itapp/sites/urls.py", line 2, in &lt;module&gt; from . import views File "/itapp/itapp/sites/views.py", line 984, in &lt;module&gt; class AddSubnet(CreateView): File "/itapp/itapp/sites/views.py", line 988, in AddSubnet site_id = self.kwargs['site_id'] NameError: name 'self' is not defined EDIT: url is as such url(r'^site/add_subnet/(?P&lt;site_id&gt;[0-9]+)$', views.AddSubnet.as_view(), name='add_subnet'),
has answer: http://stackoverflow.com/a/48525334
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48525327

http://stackoverflow.com/q/48491241
has comment: http://stackoverflow.com/comment/83975883
tagged with: python
tagged with: linear-programming
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48491356
has comment: http://stackoverflow.com/comment/83977252
score: 1
has answer: http://stackoverflow.com/a/48491356
has body: I'm trying to write a simple LP in Python to solve rock paper scissors, here is my code before: from scipy.optimize import linprog obj = [0, 0, 0, -1] A = [[0, 1, -1, -1], [-1, 0, 1, -1], [1, -1, 0, -1], [1, 1, 1, 0]] b = [0, 0, 0, 1] pb = (0.0, 1) wb = (None, None) res = linprog(obj, A_ub=A, b_ub=b, bounds=(pb,pb,pb,wb),options={"disp": True}) print(res) Unfortunately when I run this, I get the following message: 'Optimization failed. The problem appears to be unbounded.' But considering my LP is as follows: f = -w pp - ps - w = 0 -pr + -ps - w = 0 pr - pp - w = 0 pr + pp + ps = 1 0 &lt; pr, pp, ps &lt; 1 I don't see why this is unbounded. If I'm either messing up the construction of my LP or there is a syntax error could someone let me know.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83975669
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
has title: python linprog, lp appears to be unbounded

http://stackoverflow.com/q/48525733
tagged with: amazon-s3
answer count: 1
has body: I am executing a Python-Tensorflow script on Amazon Sagemaker. I need to checkpoint my model to the S3 instance I am using, but I can't find out how to do this without using the Sagemake Tensorflow version. How does one checkpoint to an S3 instance without using the Sagemaker TF version?
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84046645
tagged with: python
has answer: http://stackoverflow.com/a/48531968
tagged with: amazon-sagemaker
score: 0
has title: TensorFlow Checkpoints to S3

http://stackoverflow.com/q/48596923
has body: I'm opening a CSV file and I need to check if the file empty or not, I already know about checking using getsize(). I would like a way by using DictReader. This is my code infocsv = open('nyfile.csv', 'a') reader = csv.DictReader(infocsv)
tagged with: python
score: 0
answer count: 2
has title: Check if CSV file is empty or not after reading with DictReader
has answer: http://stackoverflow.com/a/48596967
has answer: http://stackoverflow.com/a/48597276
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/84191711
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48595821
has text: Unfortunately, I don't think that's it. I"ve posted the code for creating the CSV files in the original post as an edit. `header = None` was never used. However, I noticed that, when generating the `nodes_tags` list of lists to put into the DataFrame before doing `DataFrame.to_csv()` I only explicitly added a nested list to the tables that are working correctly now when I query them. The headers for the others are provided solely by the DataFrame header definition. Perhaps that did it? I'll give it a try and see if anything improves.

webvtt
tags question: http://stackoverflow.com/q/48640490
tag name: webvtt
type: Tag

http://stackoverflow.com/a/48534406
score: 0
answers question: http://stackoverflow.com/q/48534389
has comment: http://stackoverflow.com/comment/84064306
has body: Try anchoring your expression: r'^[A-Za-z][A-Za-z0-9_]*$' This requires that the entire identifier matches the expression, not just part of it because you are anchoring the expression to the beginning and end of the string. This prevents part of the string from matching.
type: Answer

http://stackoverflow.com/q/48611425
accepted answer: http://stackoverflow.com/a/48616158
tagged with: socket.io
favorite count: 0
tagged with: eventlet
type: AnsweredQuestion
tagged with: flask-socketio
tagged with: webserver
tagged with: python
has title: Handle concurrent requests or threading Flask SocketIO with eventlet
has body: I’ve started working a lot with Flask SocketIO in Python with Eventlet and are looking for a solution to handle concurrent requests/threading. I’ve seen that it is possible with gevent, but how can I do it if I use eventlet?
has comment: http://stackoverflow.com/comment/84219567
type: Question
upvote count: 2
score: 2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48612866
possible better answer: http://stackoverflow.com/a/48612866
has answer: http://stackoverflow.com/a/48616158

http://stackoverflow.com/q/48603981
favorite count: 0
has comment: http://stackoverflow.com/comment/84204709
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84204727
has title: Handle Key-Error whilst scraping
score: 1
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/48609524
accepted answer: http://stackoverflow.com/a/48609524
tagged with: data-extraction
downvote count: 0
upvote count: 1
answer count: 1
tagged with: error-handling
has body: I am currently working on a script to scrape data from ClinicalTrials.gov. To do this I have written the following script: def clinicalTrialsGov (id): url = "https://clinicaltrials.gov/ct2/show/" + id + "?displayxml=true" data = BeautifulSoup(requests.get(url).text, "lxml") studyType = data.study_type.text if studyType == 'Interventional': allocation = data.allocation.text interventionModel = data.intervention_model.text primaryPurpose = data.primary_purpose.text masking = data.masking.text enrollment = data.enrollment.text officialTitle = data.official_title.text condition = data.condition.text minAge = data.eligibility.minimum_age.text maxAge = data.eligibility.maximum_age.text gender = data.eligibility.gender.text healthyVolunteers = data.eligibility.healthy_volunteers.text armType = [] intType = [] for each in data.findAll('intervention'): intType.append(each.intervention_type.text) for each in data.findAll('arm_group'): armType.append(each.arm_group_type.text) citedPMID = tryExceptCT(data, '.results_reference.PMID') citedPMID = data.results_reference.PMID print(citedPMID) return officialTitle, studyType, allocation, interventionModel, primaryPurpose, masking, enrollment, condition, minAge, maxAge, gender, healthyVolunteers, armType, intType However, the following script won't always work as not all studies will have all items (ie. a KeyError will occur). To resolve this, I could simply wrap each statement in a try-except catch, like this: try: studyType = data.study_type.text except: studyType = "" but it seems a bad way to implement this. What's a better/cleaner solution?
tagged with: web-scraping

http://stackoverflow.com/q/48512115
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
tagged with: python-behave
tagged with: python
upvote count: 3
answer count: 1
downvote count: 0
has title: How can I find unused step definitions in my test suite?
has answer: http://stackoverflow.com/a/48512116
has body: When I run my test suite, the default output of behave shows where the steps come from, which is all fine and dandy, except that using this output to find the step definitions that are not used would require me to manually mark off the steps that are used in order to discover those that aren't. Can behave be invoked in a way that makes it automatically report the step definitions that are not used in the test suite?

http://stackoverflow.com/a/57702150
downvote count: 0
score: 1
has body: The python thread is the OS thread which is controlled by the OS which means it's a lot heavier since it needs context switch, but green threads are lightweight and since it's in userspace the OS does not create or manage them. I think you can use gevent, Gevent = eventloop(libev) + coroutine(greenlet) + monkey patch. Gevent give you threads but without using threads with that you can write normal code but have async IO. Make sure you don't have CPU bound stuff in your code.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48608845

http://stackoverflow.com/q/48513729
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/84022187
tagged with: python
has comment: http://stackoverflow.com/comment/84022306
has body: I basically have 3 classes. Card, Deck, and Player. The Deck is a list of cards. I am trying to remove a card from the deck. But I am getting a ValueError saying that the card is not in the list. From my understanding, it is and I am passing the correct object through the removeCard function. I am not sure why I am getting a ValueError. So in short, the problem is that I need to remove an object (Card) from a list of Cards. My issue is that when I try to remove a card from the deck I get an error like this: ValueError: list.remove(x): x not in list This is what I have so far: Card class: import random class Card(object): def __init__(self, number): self.number = number Deck class (the error is thrown here, in the removeCard function): class Deck(object): def __init__(self): self.cards = [] for i in range(11): for j in range(i): self.cards.append(Card(i)) def addCard(self, card): self.cards.append(card) def removeCard(self, card): self.cards.remove(card) def showCards(self): return ''.join((str(x.number) + " ") for x in self.cards) Player class: class Player(object): def __init__(self, name, hand): self.name = name self.hand = hand main function: def main(): deck = Deck() handA = [Card(6), Card(5), Card(3)] handB = [Card(10), Card(6), Card(5)] playerA = Player("A", handA) playerB = Player("B", handB) print("There are " + str(len(deck.cards)) + " cards in the deck.") print("The deck contains " + deck.showCards()) for i in handA: deck.removeCard(i) print("Now the deck contains " + deck.showCards()) main()
linked to: http://stackoverflow.com/q/11456637
tagged with: class
has title: Remove an object from a list of objects
tagged with: list
has comment: http://stackoverflow.com/comment/84022139
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48513851
has answer: http://stackoverflow.com/a/48513851
answer count: 1

http://stackoverflow.com/comment/84173436
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48586840
type: QuestionComment
has text: Have you read http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#declare-a-mapping

http://stackoverflow.com/comment/84224819
has text: @Ratha the code you posted does not enable me to reproduce the problem or test a solution. Please see https://stackoverflow.com/help/mcve for help creating a minimal, complete, verifiable example
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48613715

http://stackoverflow.com/q/48640853
favorite count: 0
type: Question
tagged with: centos
has body: I am using the yum check-update command in centos to get an update list and also to show obsolete packages. Below is the centos command to get the update list, and you can see a list below. [root@CentOS7-G2-3 ~]# yum check-update Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.xmission.com * extras: linux.mirrors.es.net * updates: mirror.web-ster.com Obsoleting Packages python-gobject-base.x86_64 3.22.0-1.el7_4.1 updates pygobject3-base.x86_64 3.14.0-3.el7 @anaconda rdma-core.i686 13-7.el7 base rdma.noarch 7.3_4.7_rc2-6.el7_3 @updates rdma-core.x86_64 13-7.el7 base rdma.noarch 7.3_4.7_rc2-6.el7_3 @updates But when I run the python scripts below, it is not showing any obsolete packages. Can you see why it is not showing obsolete packages? Is there any way to get that obsolete package list? The python code below was not able to scan the obsolete patches for centos. import yum from distutils import version yumObj = yum.YumBase() YUM_VER = version.StrictVersion(yum.__version__) YUM_MAJOR = YUM_VER.version[0] if YUM_MAJOR == 2: yumObj.doTsSetup() yumObj.doRepoSetup() yumObj.doRepoSetup() updates = yumObj.doPackageLists('updates').updates print "updates:"+str(updates) output of executing script given below: [root@CentOS7-G2-3 ~]# python Python 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import yum &gt;&gt;&gt; yumObj = yum.YumBase() &gt;&gt;&gt; from distutils import version &gt;&gt;&gt; YUM_VER = version.StrictVersion(yum.__version__) &gt;&gt;&gt; YUM_VER StrictVersion ('3.4.3') &gt;&gt;&gt; YUM_MAJOR = YUM_VER.version[0] &gt;&gt;&gt; YUM_MAJOR 3 &gt;&gt;&gt; updates = yumObj.doPackageLists('updates').updates Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.xmission.com * extras: linux.mirrors.es.net * updates: mirror.web-ster.com &gt;&gt;&gt; print "updates:"+str(u…
has comment: http://stackoverflow.com/comment/84279078
has comment: http://stackoverflow.com/comment/84278367
has title: Python yum module unable to scan for obsolete patches
tagged with: python
has comment: http://stackoverflow.com/comment/84488368
upvote count: 4
has comment: http://stackoverflow.com/comment/84280684
tagged with: yum
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84279157
score: 4

http://stackoverflow.com/comment/84225612
has text: So, is that means I cannot reconnect to the loop and change the window content if I exit the loop right?
type: Comment
comment on: http://stackoverflow.com/a/48592473
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84283703
type: Comment
has text: @DavidB. I tried it again but it shows the same error. The code seems to work fine when I change the limit from 50 to 10 or 20.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48608910

http://stackoverflow.com/q/48645003
has answer: http://stackoverflow.com/a/48645036
downvote count: 1
favorite count: 0
type: Question
has body: I am new to Python and Conda. I am trying to install a package called DavGIS. I downloaded this package and I downloaded Anaconda. Then I opened Anaconda Prompt and tried to install the package with the command conda install davgis. This gave an error message regarding not begin available on current channels. Then I tried pip install davgis, but this gives an error as well. In the picture the commands and errors are showed. I am using Windows 10 64-bit and Anaconda with Python 3.6 Errors installing package:
linked to: http://stackoverflow.com/q/9714635
tagged with: channel
tagged with: python
tagged with: conda
has comment: http://stackoverflow.com/comment/84331515
score: -1
upvote count: 0
type: UnansweredQuestion
tagged with: package
answer count: 1
has title: Install packages with conda - channel error

http://stackoverflow.com/comment/84103226
type: Comment
has text: The only thing to change is ( ) for the print statement on the last line. The problem error you are getting is because you are running it on an IDE and not an actual console... try running in an actual console.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48550155

http://stackoverflow.com/a/48629375
type: Answer
score: 4
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48620355
has comment: http://stackoverflow.com/comment/84273538
has body: The way you're doing this is slow because you are using an O(n²) algorithm: each row looks at every other row. Georgy's answer, while introducing vectorization, does not solve this fundamental inefficiency. I'd recommend loading your data points into a kd-tree: this data structure provides a fast way of finding nearest neighbours in multiple dimensions. Construction of such a tree is in O(n log n) and a query takes O(log n), so total time is in O(n log n). If your data is localized to a geographic region that can be well-approximated by a plane, project your data and then perform the lookup in two dimensions. Otherwise, if your data is globally dispersed, project into spherical cartesian coordinates and perform the look-up there. An example of how you might do this appears as follows: #/usr/bin/env python3 import numpy as np import scipy as sp import scipy.spatial Rearth = 6371 #Generate uniformly-distributed lon-lat points on a sphere #See: http://mathworld.wolfram.com/SpherePointPicking.html def GenerateUniformSpherical(num): #Generate random variates pts = np.random.uniform(low=0, high=1, size=(num,2)) #Convert to sphere space pts[:,0] = 2*np.pi*pts[:,0] #0-360 degrees pts[:,1] = np.arccos(2*pts[:,1]-1) #0-180 degrees #Convert to degrees pts = np.degrees(pts) #Shift ranges to lon-lat pts[:,0] -= 180 pts[:,1] -= 90 return pts def ConvertToXYZ(lonlat): theta = np.radians(lonlat[:,0])+np.pi phi = np.radians(lonlat[:,1])+np.pi/2 x = Rearth*np.cos(theta)*np.sin(phi) y = Rearth*np.sin(theta)*np.sin(phi) z = Rearth*np.cos(phi) return np.transpose(np.vstack((x,y,z))) #For each entry in qpts, find the nearest point in the kdtree def GetNearestNeighbours(qpts,kdtree): pts3d = ConvertToXYZ(qpts) #See: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.KDTree.query.html#scipy.spatial.KDTree.query #p=2 implies Euclidean distance, eps=0 implies no approximation (slower) return kdtree.query(pts3d,p=2,eps=0) #Generate uniformly-distributed test points on a…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48620355
has comment: http://stackoverflow.com/comment/84257856
has comment: http://stackoverflow.com/comment/84346026
has comment: http://stackoverflow.com/comment/84256112

http://stackoverflow.com/q/48512098
tagged with: function
upvote count: 0
accepted answer: http://stackoverflow.com/a/48512410
tagged with: python
score: -1
tagged with: nearest-neighbor
type: AnsweredQuestion
has title: Function reads np.array - produces the mean for k nn to number p in np.array
answer count: 1
has answer: http://stackoverflow.com/a/48512410
downvote count: 1
favorite count: 0
tagged with: knn
type: Question
tagged with: numpy
has body: I need to defina a function which reads a numpy array and produces the mean for k nearest points to number p in the array. Example: array= np.array([1, 2, 3, 4, 5, 6, 7, 50, 24, 32, 9, 11, 12, 10]) p= 15 (**Note this is not a number in the array, I will need to find the number closest to p or p number itself) k = 3 In this case, I would need to generate the mean for ([11, 12, 10)] as they are closest to p = 15 With the above numbers, I will need to find the mean for k number of points closest to p and p can be explicitly stated in the array or may not be. I am new and very confused at this point and feel I have exhausted my resources. I feel this question has been asked before but the answers are much too complex for what I need. Thanks in advance.
has comment: http://stackoverflow.com/comment/84019113
has comment: http://stackoverflow.com/comment/84019109
has comment: http://stackoverflow.com/comment/84019112

http://stackoverflow.com/comment/84021742
has text: Wonderful answer... very impressive.
comment on: http://stackoverflow.com/a/48512602
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48550324
has answer: http://stackoverflow.com/a/48551153
has comment: http://stackoverflow.com/comment/84097233
tagged with: sql-server
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84097106
score: 0
has comment: http://stackoverflow.com/comment/84097052
tagged with: conditional-statements
tagged with: list
tagged with: filter
has comment: http://stackoverflow.com/comment/84097204
has comment: http://stackoverflow.com/comment/84097349
answer count: 1
has comment: http://stackoverflow.com/comment/84097164
type: Question
has comment: http://stackoverflow.com/comment/84097144
has comment: http://stackoverflow.com/comment/84097534
has title: MSSQL: WHERE Field Does Not Equal List of Strings
accepted answer: http://stackoverflow.com/a/48551153
has comment: http://stackoverflow.com/comment/84097008
tagged with: python
has body: ------------UPDATED______________ I want to remove rows of a data table if column A is equal to a list of strings. I am able to do this in Python code but don't know how to do it in MSSQL. The screenshot below shows a sample of the table I have vs. the table I want. I want to remove the row if the value is between 4800 and 4900. Column A is comprised of all string values though. Please see my Python code below: import numpy as np df_adhoc_1_final['A'] = df_adhoc_1_final['A'].astype(str) aircraft_num = np.arange(4888, 4903).astype(str) for i in aircraft_num: df_adhoc_1_final = df_adhoc_1_final[df_adhoc_1_final['A'].str.contains(i) == False]
has comment: http://stackoverflow.com/comment/84097170

http://stackoverflow.com/q/48561457
tagged with: while-loop
answer count: 1
has body: As you can see I'm pretty new and I even had trouble phrasing my problem, but my issue is say type is "A" when you quit the loop it prints out items and total twice when I only need items and total. Secondly when type is "T" I only want the total to print when I quit the loop but it prints out the above statements that I need for my first loop. def ar(type): total = 0 items = "" print("Input an integer to add to the total or \"Q\" to quit") while type == "A": user_input = input("Enter an integer or \"Q\": ") if user_input.isdigit(): items += user_input + "\n" total += int(user_input) elif user_input == "q": break elif user_input == "Q": break else: print(user_input, " is not an invalid input") print("Items \n" + items) print("\nTotal \n" + str(total)) while type == "T": user_input = input("Enter an integer or \"Q\": ") if user_input.isdigit(): total += int(user_input) elif user_input == "q": break elif user_input == "Q": break else: print(user_input, " is not an invalid input") print("\nTotal \n" + str(total)) This is what the output should look like: Input an integer to add to the total or "Q" to quit Enter an integer or "Q": 3 Enter an integer or "Q": 6 Enter an integer or "Q": 24 Enter an integer or "Q": 17 Enter an integer or "Q": 61 Enter an integer or "Q": nine nine is invalid input Enter an integer or "Q": q Items 3 6 24 17 61 Total 111 call with "T"(print only the total) Input an integer to add to the total or "Q" to quit Enter an integer or "Q": 5 Enter an integer or "Q": 7 Enter an integer or "Q": Quit Total 12 This is what my output looks like: If i call ar("A") Input an integer to add to the total or "Q" to quit Enter an integer or "Q": 3 Enter an integer or "Q": 6 Enter an integer or "Q": 24 Enter an integer or "Q": 17 Enter an integer or "Q": 61 Enter an integer or "Q": nine nine is invalid input Enter an integer or "Q": q Items 3 6 24 17 61 Total 111 Total 111 if i call with ar("T") Input an integer to add to the total or "Q" to quit Items Total 0 Ent…
has answer: http://stackoverflow.com/a/48562195
has comment: http://stackoverflow.com/comment/84120435
type: Question
type: UnansweredQuestion
tagged with: python
has title: How can I fix unnecessary print statements from being printed while i run this function containing two while loops?
score: 0
tagged with: printing

http://stackoverflow.com/a/48535429
downvote count: 0
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/102392137
type: Answer
answers question: http://stackoverflow.com/q/48535236
has body: Setting SPARK_LOCAL_IP environment variable to localhost solved my error.

http://stackoverflow.com/q/48537563
has comment: http://stackoverflow.com/comment/84070061
favorite count: 0
has comment: http://stackoverflow.com/comment/84070144
type: Question
has answer: http://stackoverflow.com/a/48538263
has answer: http://stackoverflow.com/a/48537860
tagged with: multidimensional-array
tagged with: arrays
score: -3
tagged with: python
accepted answer: http://stackoverflow.com/a/48537968
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48537860
has answer: http://stackoverflow.com/a/48537968
has comment: http://stackoverflow.com/comment/84070107
has comment: http://stackoverflow.com/comment/84070254
has body: I'm trying to produce a program that will check the highest sum value of a 2D array.Then it needs to compare each value against each other to output which is the largest of all the sums for each position in the array. I'm able to do this for a set number of elements but i would like to do this for an unlimited number of elements depending on how many elements the user inputs. Person = [123,321,213] TotalMorn =[[3,5,6,4,5,3,7], [2,1,1,2,3,4,5], [3,4,5,6,7,6,5]] TotalAft =[[8,7,6,2,6,7,5], [4,3,2,3,4,3,2], [1,1,1,1,2,3,1]] def WeeklyTotal(K): Total = 0 for j in range(7): TotalM = TotalMorn[K][j] TotslA = TotalAft[K][j] Total = TotalM + TotalA + Total return Total Total1 = WeeklyTotal(0) Total2 = WeeklyTotal(1) Total3 = WeeklyTotal(2) if Total1 &gt; Total2 and Total1 &gt; Total3: print 'Person', (Person[0]), 'Has produced the most profit with ', Total1 elif Total2 &gt; Total1 and Total2 &gt; Total3: print 'Peron', (Person[1]), 'Has produced the most profit with ', Total2 elif Total3 &gt; Total1 and Total3 &gt; Total2: print 'Person', (Person[2]), 'Has produced the most profit with ', Total3
upvote count: 0
has answer: http://stackoverflow.com/a/48539181
has title: Comparing an unlimited number of values taken from a 2D array to see which element has the largest sum
has comment: http://stackoverflow.com/comment/84070100
downvote count: 3

http://stackoverflow.com/q/48589991
has body: I'm a newbie to cx_Freeze, so I tried to make an executable for a program (I'm trying to make a compiler) that uses a the module sys with this setup.py script: from cx_Freeze import setup, Executable base = None executables = [Executable("main.py", base=base)] options = { 'build_exe': { }, } setup( name = "&lt;any name&gt;", options = options, version = "0.1", description = '&lt;any description&gt;', executables = executables ) I'm using python 3.5, and when I open the generated .exe throws me this error: Fatal Python error: Py_Initialize: unable to load the file system codec ImportError: No module named 'codecs' How i can fix that error?
answer count: 1
has comment: http://stackoverflow.com/comment/84183370
type: Question
tagged with: cx-freeze
has answer: http://stackoverflow.com/a/48593055
linked to: http://stackoverflow.com/q/47738236
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47223944
tagged with: python
has title: cx_Freeze isn't working
score: 0

http://stackoverflow.com/comment/83986268
comment on: http://stackoverflow.com/q/48496308
has text: Oops, didn't read your comments :) still simplified your approach.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84167873
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48584427
type: QuestionComment
has text: Infact all the necessary libraries should be on LD_LIBRARY_PATH

http://stackoverflow.com/q/48492129
type: AnsweredQuestion
tagged with: nltk
tagged with: python
linked to: http://stackoverflow.com/q/19790188
tagged with: nlp
accepted answer: http://stackoverflow.com/a/48492759
has title: How to get an exact word match to convert words re-using the solution below?
score: 1
has answer: http://stackoverflow.com/a/48492759
answer count: 1
downvote count: 0
upvote count: 1
has body: The solution below was provided on Stack Overflow here: expanding-english-language-contractions-in-python It works great for contractions. I tried to extend it to handle slang words but ran into an issue per below. Also, I'd prefer to use 1 solution to handle all word conversions (e.g.: expansions, slang, etc.) I extended the contractions_dict to also correct slang, see 3rd entry below: contractions_dict = { "didn't": "did not", "don't": "do not", "ur": "you are" } However, when I do so on words that include a slang term (ur) like "surprise" I get "syou areprise" The "you" and "are" embedded above are where the "ru" use to be. How do you get an exact match on a key in the contractions_dict? In my code below I tried embedding a more exact word match regex around the "replace" function but received an error "TypeError: must be str, not function". The code: import re contractions_dict = { "didn't": "did not", "don't": "do not", "ur": "you are" } contractions_re = re.compile('(%s)' % '|'.join(contractions_dict.keys())) def expand_contractions(s, contractions_dict=contractions_dict): def replace(match): return contractions_dict[match.group(0)] return contractions_re.sub(replace, s) result = expand_contractions("surprise") print(result) # The result is "syou areprise". # --- # Try to fix it below with a word match regex around the replace function call. contractions_re = re.compile('(%s)' % '|'.join(contractions_dict.keys())) def expand_contractions(s, contractions_dict=contractions_dict): def replace(match): return contractions_dict[match.group(0)] return contractions_re.sub(r'(?:\W|^)'+replace+'(?!\w)', s) # On the line above I get "TypeError: must be str, not function" result = expand_contractions("surprise") print(result)
favorite count: 0
type: Question

http://stackoverflow.com/comment/84134212
type: Comment
comment on: http://stackoverflow.com/a/48568270
type: AnswerComment
has text: Hi @Wen it worked but I did get the warning ` RuntimeWarning: invalid value encountered in greater_equal if __name__ == '__main__':`. I'm also curious about if you have an answer to @roganjosh
score: 0

http://stackoverflow.com/comment/84026157
score: 0
type: Comment
has text: @AdamBeňko Updated solution. You can use a while loop
type: AnswerComment
comment on: http://stackoverflow.com/a/48515779

http://stackoverflow.com/comment/83988555
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48497090
has text: print link[1] or link[0]

http://stackoverflow.com/comment/84124978
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48564391
has text: the reason is that.. i am making a text file for the non coders to write the credentials and that symbol just gives them the clearity and separation in the text file
type: Comment

http://stackoverflow.com/comment/84125489
has text: it is working!!!!! nice but i don't understand what you're saying about dictionnaries I cannot jsonify an object?
score: 0
comment on: http://stackoverflow.com/a/48562157
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84263817
comment on: http://stackoverflow.com/q/48633293
has text: If this is your first time, why wouldn't you read the `plt.contour` documentation and have a look at some examples before rolling your own code?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48491952
type: Answer
has body: Define a list with the note positions (notes) and iterate over this list in your while loop to move and draw the notes and also for the collision detection in the event loop. import pygame pygame.init() gameDisplay = pygame.display.set_mode((800, 600)) clock = pygame.time.Clock() cont = True red = (255, 0, 0) userColor = (0, 255, 0) grey = (224, 224, 224) speed = 5 notes = [0, 100, 200] while cont: # Event handling. for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: userColor = (0, 150, 0) # Use enumerate to get the index and the # item at the same time. for i, noteY in enumerate(notes): # If the player rect collides with a note. if noteY &gt; 420 and noteY &lt; 490: notes[i] -= 660 # Reset the position. elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: userColor = (0, 255, 0) elif event.type == pygame.QUIT: cont = False # Game logic. for i in range(len(notes)): # Loop over the notes. notes[i] += speed # Move the note. if notes[i] &gt;= 600: # If below the screen ... notes[i] -= 660 # reset the position. # Draw everything. gameDisplay.fill(grey) pygame.draw.rect(gameDisplay, userColor, [375, 430, 50, 50]) for noteY in notes: pygame.draw.rect(gameDisplay, red, [385, noteY, 30, 30]) pygame.display.update() clock.tick(60) pygame.quit() You could also put pygame.Rects into the list instead of just the y-position. They have some handy collision detection methods and attributes.
downvote count: 0
answers question: http://stackoverflow.com/q/48490948
score: 3
upvote count: 3

http://stackoverflow.com/q/48536023
has body: I got an error,TypeError: bad argument type for built-in operation . I wrote codes in data.py, import os import cv2 import argparse import numpy as np import math parser = argparse.ArgumentParser(description='') parser.add_argument('input_dir' ,help='input directory') parser.add_argument('output_dir' ,help='out directory') args = parser.parse_args() def find_all_files(directory): for root, dirs, files in os.walk(directory): for file in files: p=os.path.join(root, file) p=p.split("/")[len(p.split("/"))-2] name, ext = os.path.splitext(p) yield os.path.join(root, file) dirname=args.output_dir if not os.path.exists(dirname): os.mkdir(dirname) folder_img = find_all_files(args.input_dir) im =cv2.imread(folder_img) cv2.imwrite(args.output_dir ,im) When I run python data.py ./photo ./copy_photo ( I wanna read images from photo folder and put output images in copy_photo folder),the error happens.How should I fix this?What is wrong in my code?I wrote print(folder_img) under folder_img variable &amp; find_all_files method but the print statement is not shown. Traceback says Traceback (most recent call last): File "data.py", line 175, in &lt;module&gt; im =cv2.imread(folder_img) TypeError: bad argument type for built-in operation
tagged with: python
accepted answer: http://stackoverflow.com/a/48536434
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84067517
has answer: http://stackoverflow.com/a/48536434
score: 2
upvote count: 2
downvote count: 0
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/123198
has title: TypeError: bad argument type for built-in operation What is wrong in my code?
has comment: http://stackoverflow.com/comment/84067267

http://stackoverflow.com/q/48538625
upvote count: 2
has answer: http://stackoverflow.com/a/48539171
has answer: http://stackoverflow.com/a/48538837
tagged with: interface
downvote count: 0
tagged with: python
tagged with: ubuntu
has body: I've created a few python scripts that I have to run every once in a while, but now I constantly have to type or search the location to the script in order to execute it. I have been looking for simple software to create an app with buttons, but without success. I have also seen "python?" scripts with an interface where you can select options with arrow keys, but also for this I have not found how it is done. Is there anyone who knows how I can make one of these that I can open the interface and select the script I want to execute? It would really save me a lot of time.
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48539171
has title: Ubuntu python: interface for running multiple script
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48538837
answer count: 2

http://stackoverflow.com/comment/84105405
has text: List comprehensions and lambda+map don't push the work into C.
type: Comment
comment on: http://stackoverflow.com/q/48554495
score: 1
type: QuestionComment

http://stackoverflow.com/a/48551835
type: Answer
has body: In [45]: ...: image = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) ...: image_padded = numpy.zeros((image.shape[0] + 2, image.shape[1] + 2)) ...: 1:-1 is a slice excluding the outer 2 items. It starts with 1, and ends before the last -1: In [46]: image[1:,:] Out[46]: array([[4, 5, 6], [7, 8, 9]]) In [47]: image[:-1,:] Out[47]: array([[1, 2, 3], [4, 5, 6]]) In [48]: image[1:-1,:] Out[48]: array([[4, 5, 6]]) Same applies to the 2d indexing. In [49]: image_padded[1:-1, 1:-1] Out[49]: array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) In [50]: image_padded[1:-1, 1:-1] = image In [51]: image_padded[1:-1, 1:-1] Out[51]: array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) In [52]: image_padded Out[52]: array([[0., 0., 0., 0., 0.], [0., 1., 2., 3., 0.], [0., 4., 5., 6., 0.], [0., 7., 8., 9., 0.], [0., 0., 0., 0., 0.]]) Adjacent differences are taken with expressions like image[1:] - image[:-1].
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48551554
score: 1

http://stackoverflow.com/comment/84161566
has text: Hi Welcome to Stack Overflow. This does not look like an answer to the original question, it is more of a "Me too" comment that is not an answer.
comment on: http://stackoverflow.com/a/48582386
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/48621431
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/48621710
downvote count: 1
tagged with: floating-point
has title: Extract float from csv python
has answer: http://stackoverflow.com/a/48622636
accepted answer: http://stackoverflow.com/a/48622636
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I have a csv file like this (name,floatNumber): quirrell,0,000281885 flamel,0,000175286 quirrells,0,000154252 I would like to get from it all the float numbers. for filename in os.listdir('output'): with open("output/"+filename, 'rt') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: print(row[0],row[1],row[2]) Using delimiter=',', I have this output quirrell 0 000281885 flamel 0 000175286 quirrells 0 000154252 where the number is splitted. How can I get this output and put all the float inside some variables? quirrell, 0,000281885 flamel 0,000175286 quirrells 0,000154252
has answer: http://stackoverflow.com/a/48621710
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/84252443
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48627444
type: Comment
has text: I know I can do this. But the question is about flask. How can specify python version while running "flask run"?

http://stackoverflow.com/comment/84143839
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48573126
type: QuestionComment
has text: I understand why this gives errors... code is not formatted as a starter. I'm missing the reference to the original code and the effort in finding a solution to your problem. You should mention something about what you tried! And finish the tour!

http://stackoverflow.com/a/48494523
has comment: http://stackoverflow.com/comment/84074877
type: Answer
has comment: http://stackoverflow.com/comment/84105445
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83984191
upvote count: 1
answers question: http://stackoverflow.com/q/48493936
has comment: http://stackoverflow.com/comment/84076284
has body: If you want to keep decayed learning rate same on Machine B as it was on A, you can tweak other parameters of the function tf.train.exponential_dacay . For Example, you can change decay rate on the new machine. In order to find that decay_rate you need to know how exponential_decay is computed. decay_learning_rate = learning_rate * decay_rate ^ (global_step/decay_steps) global_step/decay_step yields an pure integer if staircase==True Where decay_steps is your sub_iteration and global_step is from Machine A. You can change the decay_rate in such a way that new learning rate on machine B is same or close to what you would expect from machine A at that global_step. Also, you can change the initial learning rate for machine B so as to achieve uniform exponential rate decay from machine A to B. So in short while importing from A to B you have changed 1 variable (sub_iteration), and kept global_step same. You can adjust the other 2 variables of exponential_decay(..)in such a way that your output learning rate from the function is same as you would expect from Machine A at that global_step.

http://stackoverflow.com/comment/84056106
type: QuestionComment
comment on: http://stackoverflow.com/q/48529524
has text: @gasman Excellent idea, I will try that. Thanks!
score: 1
type: Comment

http://stackoverflow.com/q/48551523
has comment: http://stackoverflow.com/comment/84099340
tagged with: dynamic-programming
has answer: http://stackoverflow.com/a/48562713
has answer: http://stackoverflow.com/a/48570234
favorite count: 0
type: Question
has body: I have an integer S and a collection A of integers. I need to find a set of integers from the collection where the sum of those integers is equal to S. It could be 1 integer or 50 - it doesn't matter. I'm trying to do this like this: I have an array res and an array grp res starts with [0], grp is the initially given collection, and S is the sum we're trying to find, S is global my function takes (res, grp) I want to do this : (and example) - and stop when the sum of the res elements is equal to S but I suck with recursion and I have no idea what I should be doing this is my code S = 7 grp = [0,5,6,4,3] def sumFinder(res,grp): if grp == []: return grp #in case no pair was found [] is returned if sum(res) == S: return res for i in range (0,len(grp)): print(res) print(grp[i]) res += [grp[i]] newgrp = grp[:i] newgrp += grp[i+1:] return sumFinder(res,newgrp) print(sumFinder([0],grp)) UPDATE: thank you everyone for you answers thank you englealuze for giving me a beter idea about approaching the problem thanks o you i got to this: 1 - this is for finding the first combination and returning it (this was my goal) grp = [1,0,1,0,1,2,6,2,3,5,6,7,8,9,2,1,1,9,6,7,4,1,2,3,2,2] S = 55 grps = [] def findCombination(comb,grp): for i in range (0,len(grp)): comb += [grp[i]] newgrp = grp[:i] newgrp += grp[i+1:] if sum(comb) == S: return comb if newgrp not in grps: grps.append(newgrp) res = findCombination([],newgrp) if res != None: return res print(findCombination([],grp)) 2- this is for finding all the combinations: (this is the problem englealuze talked about, but i didn't understand his method that well even though it seems better) grp = [1,0,1,1,9,6,7,4,1,2,3,2,2] S = 12 grps = [] combinations = [] def findAllCombinations(comb,grp): global combinations for i in range (0,len(grp)): comb += [grp[i]] newgrp = grp newgrp = grp[:i] newgrp += grp[i+1:] if sum(comb) == S and tuple(comb) not in combinations: combinations.append(tuple(comb)) if newgrp not in grps: grps.append(newgrp) find…
has comment: http://stackoverflow.com/comment/84099745
has title: recursion on each element of array
upvote count: 2
accepted answer: http://stackoverflow.com/a/48562713
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/48551920
tagged with: python
linked to: http://stackoverflow.com/q/45878288
tagged with: recursion
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84099195
has comment: http://stackoverflow.com/comment/84145555
tagged with: list
answer count: 3
linked to: http://stackoverflow.com/q/2438938
possible better answer: http://stackoverflow.com/a/48551920

http://stackoverflow.com/a/48511445
accepted answer of: http://stackoverflow.com/q/48511285
type: Answer
has body: I can't do this in a repl quite yet but this may work for you mask = df['P/E'] &lt;= df['P/E'].quantile(0.1) df.loc[mask, 'pe_cond'] = 1 df.loc[~mask, 'pe_cond'] = 0 This is using .loc to find the subset of the DataFrame that fulfills the logic defined in the mask variable. The ~ (unary) operator negates that. So essentially, where the condition is true give it a 1. Where the condition is false give it a 0. -- Edit -- You should totally use @djk47463 comment. It's very concise. df['pe_cond'] = (df['P/E'] &lt;= df['P/E'].quantile(0.1)).astype(int)
score: 0
has comment: http://stackoverflow.com/comment/84046386
answers question: http://stackoverflow.com/q/48511285
type: AcceptedAnswer

http://stackoverflow.com/comment/84066767
score: 0
type: AnswerComment
has text: No，big one isn't
type: Comment
comment on: http://stackoverflow.com/a/48534480

http://stackoverflow.com/comment/84074583
has text: you can try for list of two dicts .
comment on: http://stackoverflow.com/q/48539701
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48542701
type: Answer
upvote count: 1
has body: Let me break up this problem in a few steps, so you understand what needs to be done here. First of all, you need to get all the products from a page. Then, you need to get all the pages and repeat the first step on each and every page. Now I do not know Python, so I will try to do this as much in a generic way as I can. First, you need to create an int with value 0. After that you need to get the number of pages. To do so, check: numberOfPagesString = browser.find_element_by_xpath('//span[@class='pagnDisabled']').text numberOfPages = int(numberOfPagesString) i = 0 Then you need to create a loop. In the loop, you are going to increment the int where you set the value 0, to a maximum of 400. So now your loop, each time the int is NOT equal to 400, is going to click on next page and get all products, and do what you want it to do. This will result in something like: while i &lt; numberOfPages **Here, as long as the value of i is less than 400, do this loop** **code to get all products on page here** **click on next page link** browser.find_element_by_id('pagnNextString').click i++ **here your i will become 1 after first page, 2 after second etc** So to conclude, first thing you are doing is, determine how many pages are there on the page. Then you are going to create an int from that string you get back from the browser. Then you create an int with value 0, which you are going to use to check if you have reached the amount of maximum pages, every time you iterate through the loop. After that you are going to first get all the products from the page (if you do not do that, it is going to skip the first page). And at last, its going to click on the next page button. To finish it, you int i is going to get an increment with ++, so after every loop, it increases by 1.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48541117

http://stackoverflow.com/comment/84284942
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48644156
has text: What does it mean that it does not work?

http://stackoverflow.com/q/48622395
score: 0
answer count: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84258663
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/84264351
type: Question
has comment: http://stackoverflow.com/comment/84264390
type: UnansweredQuestion
has body: I am trying to paint on QPainter manually. I understand that if QWidget is the paintdevice, then QPainter has to operate inside the method paintEvent(). And also that paintEvent() gets called everytime the widget is updated. What I am trying to do is take an array of coordinates from file and draw rectangles based on the coordinate array. class timeline(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.createUI() def createUI(self): self.setGeometry(0, 700, 2000, 100) self.setWindowTitle('Colors') #self.show() def paintEvent(self, event): print(event.type()) qp = QtGui.QPainter() qp.begin(self) print("error2") self.drawRectangles(qp) qp.end() def drawRectangles(self, qp): Y = 700 for i in range(self.rows): randArr = np.random.randint(0, 256, size=(3,1)) qp.fillRect(QtCore.QRect(self.tldata[i,6], Y, self.tldata[i,7], 5), QtGui.QColor(randArr[0], randArr[1], randArr[2])) self.tldata is the coordinate file that I will read in. Currently, this is how the colored rectangle looks (in the dark blue). Essentially I want to be able have a multicolored rectangle. Each color within the larger rectangle will represent a specific time range EDIT 1: when I run my full program, it continues to print("error2") as well as call self.drawRectangle(qp) when I move my window around. However, the event.type() returns 12 which is a Paint event. Table of event types So I'm guessing that somehow resizing the mainwindow is causing a Paint event. What can potentially cause this behavior? Any help would be much appreciated! Thank you!
has comment: http://stackoverflow.com/comment/84264401
has title: manually paint on QPainter
tagged with: python
tagged with: qt5
has comment: http://stackoverflow.com/comment/84283232
has comment: http://stackoverflow.com/comment/84243510
tagged with: qt

http://stackoverflow.com/q/48496659
upvote count: 0
downvote count: 2
has title: Creating new pairs based on existing pairs and their relationships
has comment: http://stackoverflow.com/comment/83988270
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83986427
has body: I am working on a dataset with 2 million pairs which are arranged like this. pair_relation item1_id item2_id 1 100 101 1 101 102 1 102 103 0 103 104 Here pair_relation shows equality relation between item1 and item2 in binary form. Now I want to generate new pairs based on existing information in a way that if item100 is equal to item101 and item101 is equal to item102 and item102 is equal to item103 but item103 is not equal to item104 , it means item104 is also not equal to item102, item101 and item100. pair_relation item1_id item2_id 1 100 101 1 101 102 1 102 103 0 103 104 0 102 104 0 101 104 0 100 104 In short it's a way of saying if A equals B and B not_equals C then A is also not_equals C. I have implemented a naive code in python involving three loops. It takes hours to run and sometimes goes out of memory and crashes. In Python, there must be an efficient and sophisticated way to achieve that.
score: -2
has comment: http://stackoverflow.com/comment/83987418
has answer: http://stackoverflow.com/a/48497662
tagged with: python
accepted answer: http://stackoverflow.com/a/48497662
type: AnsweredQuestion

http://stackoverflow.com/q/48528477
has comment: http://stackoverflow.com/comment/84054217
type: UnansweredQuestion
tagged with: package
has comment: http://stackoverflow.com/comment/84058800
has answer: http://stackoverflow.com/a/48535641
has comment: http://stackoverflow.com/comment/84067016
has answer: http://stackoverflow.com/a/51107999
tagged with: python
tagged with: python-idle
has comment: http://stackoverflow.com/comment/84058926
has comment: http://stackoverflow.com/comment/84052036
has comment: http://stackoverflow.com/comment/84066216
answer count: 2
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84054690
has title: how can i get IDLE (Python) to use packages installed by anaconda (windows 7 32bit)?
has body: The title says it all i want to be able to use the packages that are installed with anaconda with idle so are there any ways of making this work? When i try to import packages with idle that i installed using anaconda it says package not found. I need some help please and thank you in advance.
favorite count: 0
type: Question
tagged with: anaconda

http://stackoverflow.com/a/57264970
score: 3
type: Answer
has body: To get the top five most common names: dataframe['name'].value_counts().head()
answers question: http://stackoverflow.com/q/48590268
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48637148
type: Question
has answer: http://stackoverflow.com/a/48669889
has body: Hi I am trying setup my project on docker. The structure looks like this Project -- docker-compose.yml -- docker -- app -- Dockerfile -- my-project-0.1.tar.gz -- db -- Dockerfile -- db_dump.dump The docker-compose file looks like this: version: '3' services: db: build: ./docker/db ports: - "5432:5432" app: build: ./docker/app depends_on: - db command: getdatacommand restart: always app/Dockerfile looks like this FROM python:3 COPY myproject-0.1.tar.gz /tmp WORKDIR /tmp RUN pip install myproject-0.1.tar.gz # SETUP DB ENVIROMENT VARIABLES ENV DB_DRIVER='postgres' ENV DB_HOST='db' ENV DB_PORT='5432' ENV DB_USERNAME='myuser' ENV DB_PASSWORD='secretpass' ENV DB_DBNAME='db-dev' ... EXPOSE 5000 I refered to: https://docs.docker.com/engine/examples/postgresql_service/ for creating my postgres Dockerfile my db dockerfile: FROM ubuntu # SETUP DB ENVIROMENT VARIABLES ENV BB_DB_PORT='5432' ENV BB_DB_USERNAME='myuser' ENV BB_DB_PASSWORD='secretpass' ENV BB_DB_DBNAME='db-dev' COPY bb-dev.dump /tmp WORKDIR /tmp RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" &gt; /etc/apt/sources.list.d/pgdg.list RUN apt-get update &amp;&amp; apt-get install -y python-software-properties software-properties-common postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3 USER postgres # Start postgres create db and restore dump RUN /etc/init.d/postgresql start &amp;&amp;\ psql --command psql --command "CREATE USER ${BB_DB_USERNAME} WITH SUPERUSER PASSWORD '${BB_DB_PASSWORD}';" &amp;&amp;\ createdb -O ${BB_DB_USERNAME} ${BB_DB_DBNAME} &amp;&amp;\ psql ${BB_DB_DBNAME} &lt; bb-dev.dump # Adjust PostgreSQL configuration so that remote connections to the # database are possible. RUN echo "host all all 0.0.0.0/0 md5" &gt;&gt; /etc/postgresql/9.3/main/pg_hba.conf # And add ``listen_addresses`` to ``/etc/postgresql/9.3/main/postgresql.conf`` RUN echo "listen_add…
has comment: http://stackoverflow.com/comment/84288764
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84282855
downvote count: 0
tagged with: python
tagged with: docker
tagged with: postgresql
score: 3
tagged with: docker-compose
upvote count: 3
has comment: http://stackoverflow.com/comment/84282949
has title: Docker, postgres, sqlalchemy - could not connect to server: Cannot assign requested address
answer count: 1
has comment: http://stackoverflow.com/comment/84270848
favorite count: 0

http://stackoverflow.com/q/48503463
downvote count: 1
answer count: 1
has body: I have a csv file which is too large to completely fit into my laptop's memory (about 10GB). Is there a way to truncate the file such that only the first n entries are saved in a new file? I started by trying df = pandas.read_csv("path/data.csv").as_matrix() but this doesn´t work since the memory is too small. Any help will be appreciated! Leon
favorite count: 0
type: Question
has title: Truncating a large csv-file in Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84000596
tagged with: python
has answer: http://stackoverflow.com/a/48503619
upvote count: 2
linked to: http://stackoverflow.com/q/25962114
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1

http://stackoverflow.com/comment/84185410
type: QuestionComment
has text: provide expected output and your efforts what you tried and didn't work out.
comment on: http://stackoverflow.com/q/48593893
score: 0
type: Comment

http://stackoverflow.com/a/48622833
score: 0
answers question: http://stackoverflow.com/q/48577398
type: Answer
has body: After some trials and errors, I think I got it right. Here is an example using httpbin. I found out that using the json.dumps() is quite handy since it automatically writes False as 'false' and None as 'null'. import json import win32com.client h = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1') h.Open('POST', 'http://httpbin.org/post', True) h.SetRequestHeader('Referer', 'http://example.com/analysis.aspx?ID=527776455') h.SetRequestHeader('Cookie', 'ASP.NET_SessionId=51jrf2r') payload = dict( Id = 8974552, Action = "Analysis", somebool = False, missing_parameter = None ) h.Send(json.dumps(payload)) print(h.responseText) Here is the output of the print command, with IP address removed: { "args": {}, "data": "{\"Id\": 8974552, \"Action\": \"Analysis\", \"somebool\": false, \"missing_parameter\": null}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Connection": "close", "Content-Length": "83", "Content-Type": "text/plain; Charset=UTF-8", "Cookie": "ASP.NET_SessionId=51jrf2r", "Host": "httpbin.org", "Referer": "http://example.com/analysis.aspx?ID=527776455", "User-Agent": "Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)" }, "json": { "Action": "Analysis", "Id": 8974552, "missing_parameter": null, "somebool": false }, "origin": "###.###.###.###", "url": "http://httpbin.org/post" }

http://stackoverflow.com/a/48612766
has comment: http://stackoverflow.com/comment/84222218
has comment: http://stackoverflow.com/comment/84222203
has comment: http://stackoverflow.com/comment/84222198
has body: Regex is usually never the best way to scrape HTML. For instance, an alternative would be to use BeautifulSoup: from bs4 import BeautifulSoup s = ''' Gus’s World Famous Fried Chicken South City Kitchen - Midtown ''' s = BeautifulSoup(s, 'lxml') results = [i.text for i in s.find_all('span')] Output: [u'Gus’s World Famous Fried Chicken', u'South City Kitchen - Midtown'] However, a simple regex solution: import re s = ''' Gus’s World Famous Fried Chicken South City Kitchen - Midtown ''' final_results = re.findall('(.*?)', s) Output: ['Gus’s World Famous Fried Chicken', 'South City Kitchen - Midtown']
type: Answer
has comment: http://stackoverflow.com/comment/84373318
has comment: http://stackoverflow.com/comment/84222240
answers question: http://stackoverflow.com/q/48612635
has comment: http://stackoverflow.com/comment/84222194
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/84222404
has comment: http://stackoverflow.com/comment/84383471
has comment: http://stackoverflow.com/comment/84222273
downvote count: 1

http://stackoverflow.com/comment/84032908
comment on: http://stackoverflow.com/a/48518234
has text: Documentation says: PORT 15672 for RabbitMQ version 3.x PORT 55672 for RabbitMQ pre 3.x
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48622174
score: 0
has comment: http://stackoverflow.com/comment/84244584
has body: Create base model Child with children relationship and use with_polymorphic: son_and_daughter = with_polymorphic(Child, [Son, Daughter], flat=True) then use it the following: session.query(Parent).options( joinedload(Parent.children.of_type(son_and_daughter)) ) See Inheritance loading
has comment: http://stackoverflow.com/comment/84283035
type: Answer
answers question: http://stackoverflow.com/q/48621715
has comment: http://stackoverflow.com/comment/84245687

http://stackoverflow.com/a/48525307
type: Answer
has body: This is harder than what I thought , but following will do the job v=np.concatenate([pd.date_range(x['StartTime'],x['EndTime'],freq='10Min') for _,x in remove.iterrows()]) df=df[~df.Timestamp.isin(v)] df Out[36]: Timestamp A B C D 0 1900-01-01 00:00:00 10 10 10 10 1 1900-01-01 00:10:00 10 25 2 1900-01-01 00:20:00 10 25 3 1900-01-01 00:30:00 25 4 1900-01-01 00:40:00 25 5 1900-01-01 00:50:00 25 25 25 25 6 1900-01-01 01:00:00 30 30 30 30 7 1900-01-01 01:10:00 42 42 42 42 10 1900-01-01 01:40:00 40 40 40 11 1900-01-01 01:50:00 35 35 v2=df.set_index('Timestamp').stack().swaplevel(1,0).sort_index(level=0) v3=v2[v2==''].to_frame().reset_index(level=1) v3['New']=v3.Timestamp.diff().astype('timedelta64[m]').ne(10).cumsum() v3.groupby([v3.index.get_level_values(level=0),v3.New]).Timestamp.agg(['first','last']).reset_index() Out[74]: level_0 New first last 0 A 1 1900-01-01 00:10:00 1900-01-01 00:40:00 1 A 2 1900-01-01 01:50:00 1900-01-01 01:50:00 2 B 3 1900-01-01 00:10:00 1900-01-01 00:40:00 3 B 4 1900-01-01 01:40:00 1900-01-01 01:50:00 4 C 5 1900-01-01 00:30:00 1900-01-01 00:40:00
score: 0
answers question: http://stackoverflow.com/q/48524552

http://stackoverflow.com/comment/84037527
score: 0
comment on: http://stackoverflow.com/q/48521184
type: Comment
type: QuestionComment
has text: Dont let us guess please. Edit your post so we can see where you have it.

http://stackoverflow.com/a/48619619
has body: I have found out how to do it. That's the code: def element_clicked(event): item = tree.focus() print(tree.item(item, "values"))
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48619011

http://stackoverflow.com/q/48497809
type: Question
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48498327
tagged with: python
has answer: http://stackoverflow.com/a/48498327
has title: pandas select conditionally specific columns in dataframe with another condition results in concatenation
accepted answer: http://stackoverflow.com/a/48497863
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/48497863
downvote count: 0
favorite count: 0
has body: I want to select specific columns by their name using loc, since i want to do it with another condition. I get weird behavior trying to achieve this using df.loc[,conditionOne | conditionTwo] one of the conditions is whether a column name is in a specific list of names, and the second condition is another condtion (here is the median of the column): df = pd.DataFrame({'A' : [0,0,0,0], 'B' : [1,2,3, 5], 'C' : [10,20,30, 50]}) df.columns.values keepColumnsNames = ['A', 'c'] condtionOne = df.mean()&gt;2 print(condtionOne) "#A False" "#B True" "#C True" "#dtype: bool" condtionTwo=pd.DataFrame(df.columns.values).iloc[:,0].isin(keepColumnsNames) print(condtionTwo) "#A False" "#B True" "#C True" Now when i want to do an or operator between the two conditions i get the next weird behavior: print(condtionOne | condtionTwo ) "#0 False" "#1 False" "#2 False" "#A False" "#B True" "#C True" "#dtype: bool" while I would expect to get "#False" "#True" "#True"

http://stackoverflow.com/comment/84148251
has text: Why is `1234567.1` okay? It has 8 digits even though there are 7 whole numbers? In the later sample you said `1.123456` should be the expected result of `1.12345678`.
score: 0
comment on: http://stackoverflow.com/q/48574375
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84010747
type: QuestionComment
comment on: http://stackoverflow.com/q/48507940
has text: OP probably means that the nested dictionary values in SET_A and SET_B respectively refer to single dict per nesting level, which is obvious if one reads what `dict.fromkeys()` does with the 2nd argument.
score: 0
type: Comment

text-classification
tags question: http://stackoverflow.com/q/48643395
tag name: text-classification
type: Tag
tags question: http://stackoverflow.com/q/48570417

http://stackoverflow.com/q/48508714
has title: python nltk module is creating it's own bugs
tagged with: nltk
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84018314
tagged with: python
has body: I have an error with nltk which doesn't allow me to open anymore my previous projects: from nltk.corpus import stopwords from nltk.tokenize import word_tokenize example_sent = "This is a sample sentence, showing off the stop words filtration." stop_words = set(stopwords.words('english')) word_tokens = word_tokenize(example_sent) filtered_sentence = [w for w in word_tokens if not w in stop_words] filtered_sentence = [] for w in word_tokens: if w not in stop_words: filtered_sentence.append(w) print(word_tokens) print(filtered_sentence) and when I run this I get this error File "/Users/nicolas/Desktop/part 1 natural lenguage/stopwords.py", line 1, in <module> from nltk.tokenize import sent_tokenize, word_tokenize File "/Library/Python/2.7/site-packages/nltk/__init__.py", line 114, in <module> from nltk.collocations import * File "/Library/Python/2.7/site-packages/nltk/collocations.py", line 37, in <module> from nltk.probability import FreqDist File "/Library/Python/2.7/site-packages/nltk/probability.py", line 47, in <module> from collections import defaultdict, Counter File "/Library/Python/2.7/site-packages/nltk/collections.py", line 13, in <module> import pydoc File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pydoc.py", line 56, in <module> import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 39, in <module> import tokenize File "/Users/nicolas/Desktop/part 1 natural lenguage/tokenize.py", line 1, in <module> from nltk.corpus import stopwords File "/Library/Python/2.7/site-packages/nltk/corpus/__init__.py", line 64, in <module> from nltk.tokenize import RegexpTokenizer File "/Library/Python/2.7/site-packages/nltk/tokenize/__init__.py", line 67, in <module> from nltk.tokenize.mwe import MWETokenizer File "/Library/Python/2.7/site-packages/nltk/tokenize/mwe.py", line 31, in <module> from nltk.util import Trie File "/Library/Pytho…
has comment: http://stackoverflow.com/comment/84012291
has comment: http://stackoverflow.com/comment/84012997
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84047849
type: Question
has comment: http://stackoverflow.com/comment/84047982

http://stackoverflow.com/comment/83996727
score: 1
type: Comment
type: AnswerComment
has text: You could simply use `colorama.Fore.RESET`, which will work on other platforms as well.
comment on: http://stackoverflow.com/a/48501440

http://stackoverflow.com/a/48604651
accepted answer of: http://stackoverflow.com/q/48505862
answers question: http://stackoverflow.com/q/48505862
type: Answer
downvote count: 0
upvote count: 1
has body: Per ilyas's advice, updated my notebook to 5.4.0 and this issue was resolved.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48590712
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48687491
favorite count: 0
type: Question
upvote count: 4
has body: As the question title states, I am trying to compile my own binaries for the Python3 OpenCV library on Windows 10, with CUDA support and the contrib files. I have been following this guide on installing OpenCV 3 on Windows concurrently with this one for compiling OpenCV with CUDA support. This question is similar to another question, but I am using VS2015, and the solution posted has not solved my issue. The Problem I was able to successfully follow these guides and configure, generate, and build with CMake (with GUI). However, when I ran Python from a fresh terminal after this, I had the same problem mentioned in the other question I linked previously. I have attempted setting path variables as per this solution, but the problem remained. That is when I noticed this line in my CMake output: It appears as though CMake is failing to find Python libraries, despite having set them manually as per step 5.2 of the install guide: I don't understand how CMake works very much, and I am now at a loss as to how to fix this. Other stackoverflow questions about installing OpenCV are all about a different version, a different OS, or non-GPU-supported. The Question How can I get CMake to properly install OpenCV with CUDA support such that my Python3 interpreter will run it? Relevant Information System: Windows 10 Pro (64 bit) CUDA Toolkit Version: 9.1 Python Version: 3.6.1 (Anaconda 4.4.0 64 bit) GPU: NVIDIA GeForce GTX 1080 CMake version: 3.10.2 Visual Studio Version: 14 (VS2015 Win64) Here's the entire output of CMake: Selecting Windows SDK version 10.0.15063.0 to target Windows 10.0.16299. found Intel IPP (ICV version): 2017.0.3 [2017.0.3] at: C:/opencv_3.0/opencv-3.3.1/build/3rdparty/ippicv/ippicv_win found Intel IPP IW sources: 2017.0.3 at: C:/opencv_3.0/opencv-3.3.1/build/3rdparty/ippicv/ippiw_win CUDA detected: 9.1 CUDA NVCC target flags: -gencode;arch=compute_30,code=sm_30;-gencode;arch=compute_35,code=sm_35;-gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,cod…
linked to: http://stackoverflow.com/q/24174394
has title: Build and Compile OpenCV with Python and GPU Support on Windows 10 VS2015
linked to: http://stackoverflow.com/q/33423059
downvote count: 0
score: 4
tagged with: cmake
tagged with: opencv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48687491
tagged with: windows

http://stackoverflow.com/q/48598523
type: Question
accepted answer: http://stackoverflow.com/a/48615796
answer count: 1
tagged with: python
has body: I've been looking around in the PyMel docs but can't I get the inverse of a matrix from pymel.core.datatypes. My code is: inverseM = orientationM*bindRotationM; inverseM = inverseM.asMatrixInverse() I just get the error: Error: line 1: AttributeError: file S:\Maya_2017_DI\build\Release\runTime\Python\Lib\site-packages\maya\OpenMaya.py line 54: asMatrixInverse #
has answer: http://stackoverflow.com/a/48615796
type: AnsweredQuestion
has title: Getting the inverse of a matrix with PyMel in Maya 2017
score: 1
upvote count: 1
downvote count: 0
tagged with: matrix-inverse
tagged with: maya
tagged with: pymel
favorite count: 0

http://stackoverflow.com/comment/84123184
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48562383
type: QuestionComment
has text: your librarries in `/tmp/` folder ?

http://stackoverflow.com/comment/84230338
type: Comment
has text: sure. StackOverflow just doesn't allow me to accept an answer too early so I often accept it some days later. Sorry about the delay.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48575001

http://stackoverflow.com/comment/83993777
type: Comment
type: AnswerComment
has text: glad to have been helpful and thank you for accepting my answer
score: 0
comment on: http://stackoverflow.com/a/48498763

http://stackoverflow.com/a/48583265
answers question: http://stackoverflow.com/q/48582156
score: 0
has body: Write sql query for each name df1=spark.sqlContext("select * from DF_B where name='X'") df2=spark.sqlContext("select * from DF_B where name='Y'") Create one column for each data frame with row id df1_id= df1.withColumn("id", monotonically_increasing_id()) df2_id= df2.withColumn("id", monotonically_increasing_id()) Now we can join the both dataframe df1_id and df2_id. df1_id.join(df2_id,"id").show()
type: Answer

http://stackoverflow.com/q/48595660
favorite count: 0
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has title: Python: What should I use multi-process or multi-thread in DB related tasks?
upvote count: 2
has comment: http://stackoverflow.com/comment/84188860
type: UnansweredQuestion
tagged with: multithreading
has answer: http://stackoverflow.com/a/48758627
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/868568
has body: This thread explains what the CPU bound, IO bound problems. Given that the Python has GIL structure, someone recommended, • Use threads for I/O bound problems • Use processes, networking, or events (discussed in the next section) for CPU-bound problems Honestly, I cannot fully and intuitively understand what these problems really are. Here is the situation I'm faced with: crawl_item_list = [item1, item2, item3 ....] for item in crawl_item_list: crawl_and_save_them_in_db(item) def crawl_and_save_them_in_db(item): # Pseudo code # crawled_items = crawl item from the web // the number of crawled_items is usually 200 # while crawled_items: # save them in PostgreSQL DB # crawled_items = crawl item from the web This is the task that I want to perform with parallel processes or thread. (Each process(or thread) will have their own crawl_and_save_them_in_db and deals with each item) In this case, which one should I choose between multi-processes(something like Pool) and multi-thread? I think that since the main job of this task is storing the DB, which is kind of IO bound task(Hope it is..), so I have to use multi thread? Am I right? Need your advices.
downvote count: 0
answer count: 1

http://stackoverflow.com/q/48585226
tagged with: django
tagged with: python
has title: NOT NULL constraint failed: courses_course.owner_id
score: 0
answer count: 2
has body: I'm creating a school, kinda, and I get NOT NULL constraint failed: courses_course.owner_id whenever I try to create a course via the URL http://127.0.0.1:8000/course/create/. Here are my files: models.py from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from .fields import OrderField class Subject(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('title',) def __str__(self): return self.title class Course(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses_created') subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='courses') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return self.title class Module(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='modules') title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) class Meta: ordering = ['order'] def __str__(self): return '{}. {}'.format(self.order, self.title) class Content(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='contents') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={ 'model__in':('text', 'video', 'image', 'file') }) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') order = OrderField(blank=True, for_fields=['module']) class Meta: ordering = ['order'] class ItemBase(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_related') title = m…
has answer: http://stackoverflow.com/a/61732674
possible better answer: http://stackoverflow.com/a/61732674
type: Question
type: AnsweredQuestion
tagged with: django-2.0
has answer: http://stackoverflow.com/a/48585307
accepted answer: http://stackoverflow.com/a/48585307

http://stackoverflow.com/comment/84180614
comment on: http://stackoverflow.com/q/48590672
type: Comment
type: QuestionComment
has text: I think the issue is when I convert the list I've imported to a pandas data frame. I realize that just loading the .mat files doesn't take long, it's transforming them form list to pd.DataFrame()
score: 0

http://stackoverflow.com/a/48607515
accepted answer of: http://stackoverflow.com/q/48607339
has comment: http://stackoverflow.com/comment/112188181
type: Answer
answers question: http://stackoverflow.com/q/48607339
has comment: http://stackoverflow.com/comment/84211362
upvote count: 18
score: 17
has comment: http://stackoverflow.com/comment/84211420
has comment: http://stackoverflow.com/comment/84211427
has body: you could use pycountry for your task (it also works with python 3): pip install pycountry import pycountry text = "United States (New York), United Kingdom (London)" for country in pycountry.countries: if country.name in text: print(country.name)
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/108493556
has comment: http://stackoverflow.com/comment/84211331

http://stackoverflow.com/comment/83978051
type: Comment
comment on: http://stackoverflow.com/a/48488955
type: AnswerComment
has text: would you please update your answer to include the Case argument: `output_field=models.BooleanField()` and then I will accept your answer. (My edit was rejected)
score: 0

http://stackoverflow.com/comment/84173375
comment on: http://stackoverflow.com/q/48585023
type: QuestionComment
has text: I think you mean the post is different from the linked duplicate now because you edited it, not the other way around. ;-) In such cases best notify the person who closed the question (using the @ notation), otherwise it will not be reopened.
type: Comment
score: 0

http://stackoverflow.com/q/48555454
upvote count: 1
score: 1
favorite count: 0
tagged with: console
tagged with: python
has body: I have a project in pydev / eclipse that has multiple python files in the /src folder. When I run the first program I created, it runs fine and I am able to interact with it in the console pane. When I try to run any of the others no consoles to display at this time flashes up but then the program quickly terminates before I can type anything. I can't reproduce it, but sometimes my first input question will flash by too. If I go back to the first program I wrote, it runs fine even though it failed previously on the other programs. When I run in debug mode, it usually works fine. How do I fix it so I can interact w/ my program in the console when I hit "run"? This is what I have tried: (1) closed eclipse and then restarted it (2) checked that the "allocate console" was selected under run > run configurations > common menu option (3) unchecked the "allocate console" option, ran the program, then selected the "allocate console" option again (4) tried window > show view > console menu option (5) restarted my computer (6) closed eclipse, moved my python files to the desktop, deleted the .metadata folder, deleted the project folder, restarted eclipse, changed the perspective, created a new project, imported my files into the newly created project (7) tried the stuff mentioned on the stack overflow page at No console output in Eclipse Juno. However, I did not understand the server suggestions. Where would I find that? I didn't think I was running one. I have not uninstalled eclipse and python and then reinstalled both, but I am getting desperate so I might. Or I may just try to live with using debug to run the program. I would like to know what is wrong though. I have used other workspaces with multiple python programs in the project with no problem. Thanks in advance for your help.
tagged with: eclipse
linked to: http://stackoverflow.com/q/18504493
type: Question
has title: getting message "no consoles to display at this time" before program terminates in pydev / eclipse
tagged with: pydev
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48738322
answer count: 1
downvote count: 0

http://stackoverflow.com/a/48637882
answers question: http://stackoverflow.com/q/48629103
type: AcceptedAnswer
downvote count: 0
score: 5
upvote count: 5
type: Answer
has body: Eventually @bigreddot 's helped me to find this Bokeh Server callback from tools. Below the code which worked for me: import pandas as pd import numpy as np from bokeh.models import ColumnDataSource from bokeh.plotting import figure from bokeh.layouts import row from bokeh.io import curdoc from random import sample # data for plot 2 df2 = pd.DataFrame({"A" : sample(np.linspace(10, 20, 10),5), "B" : sample(np.linspace(20, 30, 10),5), "C" : sample(np.linspace(30, 40, 10),5), "D" : sample(np.linspace(40, 50, 10),5), "E" : sample(np.linspace(50, 60, 10),5),}) source2 = ColumnDataSource( data=dict( x=list(df2.index.values), y=list(df2.iloc[:,0].values) ) ) # data for plot 1 df1 = np.mean(df2) source1 = ColumnDataSource( data=dict( x=list(range(0,df1.shape[0])), y=list(df1.values), colnames = list(df1.index.values) ) ) # Plot graph one with data from df1 and source 1 as barplot plot1 = figure(plot_height=300, plot_width=400, tools="tap") barglyph = plot1.vbar(x='x',top='y',source=source1, bottom=0,width =0.5) # Plot graph two with data from df2 and source 2 as line plot2 = figure(plot_height=300, plot_width=400, title="myvalues", tools="crosshair,box_zoom,reset,save,wheel_zoom,hover") r1 = plot2.line(x='x',y='y',source =source2, line_alpha = 1, line_width=1) # safe data from plot 2 for later change in subroutine ds1 = r1.data_source def callback(attr, old, new): patch_name = source1.data['colnames'][new['1d']['indices'][0]] ds1.data['y'] = df2[patch_name].values print("TapTool callback executed on Patch {}".format(patch_name)) # add taptool to plot1 barglyph.data_source.on_change('selected',callback) curdoc().add_root(row(plot1,plot2))
accepted answer of: http://stackoverflow.com/q/48629103

discord.py
tags question: http://stackoverflow.com/q/48523580
tags question: http://stackoverflow.com/q/48499144
tags question: http://stackoverflow.com/q/48530423
tags question: http://stackoverflow.com/q/48518300
type: Tag
tags question: http://stackoverflow.com/q/48612603
tag name: discord.py

http://stackoverflow.com/a/48562835
has comment: http://stackoverflow.com/comment/117680208
has comment: http://stackoverflow.com/comment/124224109
has comment: http://stackoverflow.com/comment/87275698
has comment: http://stackoverflow.com/comment/136900393
downvote count: 48
has comment: http://stackoverflow.com/comment/116398010
has comment: http://stackoverflow.com/comment/96633134
type: Answer
score: 145
has comment: http://stackoverflow.com/comment/124233597
has comment: http://stackoverflow.com/comment/134505212
has comment: http://stackoverflow.com/comment/87263664
has comment: http://stackoverflow.com/comment/139021633
has comment: http://stackoverflow.com/comment/124191735
has comment: http://stackoverflow.com/comment/124191655
has body: You don't need to use virtualenv inside a Docker Container. virtualenv is used for dependency isolation. You want to prevent any dependencies or packages installed from leaking between applications. Docker achieves the same thing, it isolates your dependencies within your container and prevent leaks between containers and between applications. Therefore, there is no point in using virtualenv inside a Docker Container unless you are running multiple apps in the same container, if that's the case I'd say that you're doing something wrong and the solution would be to architect your app in a better way and split them up in multiple containers. EDIT 2022: Given this answer get a lot of views, I thought it might make sense to add that now 4 years later, I realized that there actually is valid usages of virtual environments in Docker images, especially when doing multi staged builds: FROM python:3.9-slim as compiler ENV PYTHONUNBUFFERED 1 WORKDIR /app/ RUN python -m venv /opt/venv # Enable venv ENV PATH="/opt/venv/bin:$PATH" COPY ./requirements.txt /app/requirements.txt RUN pip install -Ur requirements.txt FROM python:3.9-slim as runner WORKDIR /app/ COPY --from=compiler /opt/venv /opt/venv # Enable venv ENV PATH="/opt/venv/bin:$PATH" COPY . /app/ CMD ["python", "app.py", ] In the Dockerfile example above, we are creating a virtualenv at /opt/venv and activating it using an ENV statement, we then install all dependencies into this /opt/venv and can simply copy this folder into our runner stage of our build. This can help with minimizing docker image size.
has comment: http://stackoverflow.com/comment/136545313
has comment: http://stackoverflow.com/comment/133638983
has comment: http://stackoverflow.com/comment/104618126
has comment: http://stackoverflow.com/comment/93148194
has comment: http://stackoverflow.com/comment/94982040
has comment: http://stackoverflow.com/comment/120858082
answers question: http://stackoverflow.com/q/48561981
upvote count: 193

http://stackoverflow.com/comment/84057080
has text: you need to provide code sample for both python and c# sides, this question does not make sense in the current state
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48515473

http://stackoverflow.com/a/53184918
type: Answer
has comment: http://stackoverflow.com/comment/107458469
answers question: http://stackoverflow.com/q/48512013
has comment: http://stackoverflow.com/comment/127490012
downvote count: 0
has body: This may happen if your procfile is misspelt, such as "procfile" or "ProcFile" etc. The file name should be "Procfile" (with a capital P). sometimes changing the file name is not anough, because git wouldn't spot the change. I had to delete the Procfile completely, then commit the change, than add it again with the right name, and then commit that again: remove your procfile git commit add a new procfile with the exact name "Procfile" commit again git push heroku master (or main - new heroku projects now uses main) should work!
upvote count: 65
score: 65

odoo
tags question: http://stackoverflow.com/q/48637661
tags question: http://stackoverflow.com/q/48552182
tags question: http://stackoverflow.com/q/48633921
type: Tag
tags question: http://stackoverflow.com/q/48639646
tags question: http://stackoverflow.com/q/48552786
tags question: http://stackoverflow.com/q/48519440
tags question: http://stackoverflow.com/q/48523138
tags question: http://stackoverflow.com/q/48635607
tags question: http://stackoverflow.com/q/48631073
tags question: http://stackoverflow.com/q/48570903
tags question: http://stackoverflow.com/q/48542068
tags question: http://stackoverflow.com/q/48606005
tag name: odoo

http://stackoverflow.com/comment/84224764
has text: try `data.astype('U')` or if you are on python2 `data.astype('S')`
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48613828

http://stackoverflow.com/a/48518454
has comment: http://stackoverflow.com/comment/84045060
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48518155
has comment: http://stackoverflow.com/comment/84045873
type: Answer
has body: To get the missing library run !apt install libnvrtc8.0 After that !find / -name 'libnvrtc.*' returns /usr/lib/x86_64-linux-gnu/libnvrtc.so.8.0 /usr/lib/x86_64-linux-gnu/libnvrtc.so.8.0.61 and mxnet is working with the python 3 runtime.
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/84068965
answers question: http://stackoverflow.com/q/48518155

http://stackoverflow.com/q/48609297
tagged with: django
upvote count: 1
favorite count: 0
type: Question
tagged with: docker
score: 1
tagged with: python
has title: Why does django inside a container needs the "it" flag?
has body: I try to run django on a docker container using sqllite as the db and the django dev server. So far I was able to launch locally the django server: python .\manage.py runserver I can build the docker image using Dockerfile: docker build . -t pythocker But when I run the image with docker run -p 8000:8000 pythocker no output is shown and the machine is not reachable, I have to kill the running container. If I add the -it flag on the docker run command then the server is running and I can go to http://192.168.99.100:8000 and display the django welcome page. Why is this flag mandatory here? Docker logs on the container gives nothing. I also tried to add custom logging inside the manage.py but it's not diplayed in the console or in the docker logs. I am using the Docker Windows toolbox as I have only a windows home computer.
tagged with: docker-toolbox
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/84261163
comment on: http://stackoverflow.com/q/48632016
score: 0
has text: Your ways looks correct to me
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84140482
type: Comment
type: QuestionComment
has text: In your post please. Comments have been known to have been removed
comment on: http://stackoverflow.com/q/48569690
score: 0

http://stackoverflow.com/comment/137990434
comment on: http://stackoverflow.com/a/51239081
type: Comment
type: AnswerComment
score: 0
has text: Thanks for posting this! I am adapting your example into a broader utility. https://github.com/bduhbya/python_named_pipe.git

periodicity
tag name: periodicity
tags question: http://stackoverflow.com/q/48606120
type: Tag

http://stackoverflow.com/q/48644172
has comment: http://stackoverflow.com/comment/84288650
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48644389
tagged with: sublimetext3
has answer: http://stackoverflow.com/a/48644389
answer count: 1
tagged with: sublime-text-plugin
type: Question
has body: I'm trying to build a plugin whose commands are accessible on the command palette. The idea is that each command will ask for text input in the command palette and then present options which are then written to the view. How on Earth do I do this? There is no good documentation anywhere! So far I have: import sublime import sublime_plugin class QueryListInput(sublime_plugin.ListInputHandler): def name(self): return "my_list" But then I get: AttributeError: 'module' object has no attribute 'ListInputHandler' I research and find this answer, which tells me that only dev builds have access to this feature. Really? Does that mean my plugin won't work on regular builds? All I want is: User opens command palette User selects MyCommand User types some text in the command palette User is presented with some options based on that text User selects one and it is written to sublime view This is quite simple but I have found it to be quite difficult to accomplish. Thanks in advance if you can help!
has comment: http://stackoverflow.com/comment/84285832
tagged with: python
has title: Sublime text 3 Custom command palette plugin
has comment: http://stackoverflow.com/comment/84286255
has comment: http://stackoverflow.com/comment/84286989

http://stackoverflow.com/q/48643406
has body: My query is not working according to this post similar post Used the below command with the sql. But im not executing from shell. The sql is created as a string in python and passed to hive using paramiko. In shell it works fine. But when passed as as string from python im getting a bash error. It looks like some character escape issue. Im trying to load csv file with each column value enclosed in double quotes. strsql='''create table temp(col1 INT,col2 string) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde' WITH SERDEPROPERTIES ("quoteChar" = "\"") tblproperties ('skip.header.line.count'='1'); ''' Error ["bash: -c: line 4: unexpected EOF while looking for matching `''\n", 'bash: -c: line 5: syntax error: unexpe cted end of file\n'] The i changed to ("quoteChar" = "\\"") to add extra slash. Then i get a sql error :FAILED: ParseException line 4:38 cannot recognize input near 'quoteChar' '=' ')' i n table properties list On further inspection the hive command is called with some extract properties as below. Could that be an issue? hive -e set hive.cli.print.header=true;hive.support.quoted.identifiers=column;hvesql;
has title: hive data load from double quote enclosed csv file format
accepted answer: http://stackoverflow.com/a/48658018
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/84286705
has comment: http://stackoverflow.com/comment/84286123
tagged with: paramiko
has answer: http://stackoverflow.com/a/48658018
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84291102
upvote count: 0
has comment: http://stackoverflow.com/comment/84291144
answer count: 1
tagged with: shell
downvote count: 1
linked to: http://stackoverflow.com/q/30637536
favorite count: 0
tagged with: hive
type: Question
tagged with: hadoop

http://stackoverflow.com/a/48577656
upvote count: 0
has comment: http://stackoverflow.com/comment/84151725
has body: If I did not overseen it, you do not have the python 3.6.4 directory in your PATH-variable, only (the old one) python 3.6.32. Have a look at this post how to fix this.
has comment: http://stackoverflow.com/comment/84151895
answers question: http://stackoverflow.com/q/48577424
type: Answer
downvote count: 1
score: -1

http://stackoverflow.com/comment/84120691
type: AnswerComment
has text: I have tried a shifted 'close' substitution in the lambda expression, but it generates an 'Ambiguous' exception. At the moment, it looks as if the extra column will have to be the way to go. I shall investigate if creating a temporary copy of 'yclose' could be created so that it is not permanently written to df.
comment on: http://stackoverflow.com/a/48542328
score: 0
type: Comment

pendulum
tag name: pendulum
type: Tag
tags question: http://stackoverflow.com/q/48565353

http://stackoverflow.com/q/48568322
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48568427
has body: I have an array of multiple even and odd numbers, how can i make this array to an arrary of odd elements, for example: odd elements ignored but even elements plus 1; Input_array = [3,67,2,34,55,73,96,21,13,15,16] Output_array = [3,67,3,35,55,73,97,21,13,15,17] this is my code : Output_array = [(x+1) for x in Input_array if x%2 == 0] but this Output_array contains (even elements + 1) not all elements, only [3, 35, 97, 17]
has comment: http://stackoverflow.com/comment/84133119
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/48568412
has comment: http://stackoverflow.com/comment/84132930
tagged with: python
has answer: http://stackoverflow.com/a/48568434
has title: How to make odd all elements of a list in python?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84132886
has comment: http://stackoverflow.com/comment/84133102
accepted answer: http://stackoverflow.com/a/48568500
score: 0
possible better answer: http://stackoverflow.com/a/48568412
has answer: http://stackoverflow.com/a/48568500
answer count: 4

http://stackoverflow.com/comment/84075230
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48539900
has text: `{PATH}` isn't really a valid Bash expression. Perhaps you mean `${PATH}` (where however the braces aren't really useful or necessary)? (Not too familiar with Jupyter though.)
type: Comment

http://stackoverflow.com/a/48555060
has comment: http://stackoverflow.com/comment/84107411
has comment: http://stackoverflow.com/comment/84107529
type: Answer
answers question: http://stackoverflow.com/q/48555034
has body: I didn't get your error but it may be stemming from the variable you created with the same name as the function html_list, perhaps? I tested this code in python2 and python3 and it seems to work. I modified the code so that your function returns the input_list. It prints the output where it calls the function. list_1 = ["hey", "hello", "joe"] def html_list(input_list): new_list = [" "] for item in input_list: new_list.append(" {} ".format(item)) new_list.append(" ") return new_list print(html_list(list_1)) Returns [' ', ' hey ', ' hello ', ' joe ', ' ']
has comment: http://stackoverflow.com/comment/84107472
has comment: http://stackoverflow.com/comment/84107379
has comment: http://stackoverflow.com/comment/84107456
score: 1
accepted answer of: http://stackoverflow.com/q/48555034
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84126278
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48564391
has text: @HassanHaroon The reason you cant catch that exception is because it doesn't exist in 2.7; you want [IOError](https://docs.python.org/2.7/library/exceptions.html#exceptions.IOError) and will have to print out the number or message to determine what happened.
type: Comment

http://stackoverflow.com/comment/84128831
score: 0
type: AnswerComment
has text: Yes, exactly. `dataframe['row'] = dataframe['row'].quantile([.1,.5,.7]).reset_index(drop=True) i get 0 0.009876 1 0.012500 2 0.012125 3 0.013446 4 0.013752 5 NaN ..... 5758 NaN ` - it is expected output and dont use it ;) you need `df = dataframe['row'].quantile([.1,.5,.7]).rename_axis('a').reset_index(name='b')`
comment on: http://stackoverflow.com/a/48563630
type: Comment

http://stackoverflow.com/q/48601526
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84199726
type: Question
tagged with: python-3.x
has body: I want to offer an asynchronous http server to clients, and use asynchronous pub-sub on an internal network of peers to which those clients connect. It looks like the best libraries for this, respectively, are aiohttp and aiozmq: import aiohttp import aiozmq If I do the above, am I already doing it wrong? It is like using different asynchronous frameworks at once...
has answer: http://stackoverflow.com/a/48602481
upvote count: 2
type: UnansweredQuestion
tagged with: zeromq
score: -2
has comment: http://stackoverflow.com/comment/84199785
tagged with: python
has title: Can I use aiozmq with aiohttp?
downvote count: 4
tagged with: python-asyncio

http://stackoverflow.com/comment/83985246
comment on: http://stackoverflow.com/q/48496032
type: Comment
has text: @CIsForCookies Sorry,if you do it like that link,you can just see one green line.
score: 1
type: QuestionComment

http://stackoverflow.com/q/48557705
has body: I have a sort like this: db.getCollection('TEST').aggregate([ {'$sort': {'create_time': 1, 'status': 1}} ]) It has 2 sort fields, mongo will sort the create_time field first, then status.But in python dict is disordered, it sometimes sorts create_time first, sometimes status first, so the question is how can I make sure it always sorts the create_time first?
has comment: http://stackoverflow.com/comment/84111315
answer count: 1
type: Question
tagged with: mongodb
type: UnansweredQuestion
has title: Pymongo $sort parameters order
has comment: http://stackoverflow.com/comment/84111948
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/84146837
has comment: http://stackoverflow.com/comment/84111703
score: 0
has answer: http://stackoverflow.com/a/48627339

http://stackoverflow.com/q/48584208
has comment: http://stackoverflow.com/comment/84165647
has comment: http://stackoverflow.com/comment/84166488
has title: How to run python script at my mac's terminal after being connected to GCP virtual machine?
has comment: http://stackoverflow.com/comment/84166991
has comment: http://stackoverflow.com/comment/84165792
has comment: http://stackoverflow.com/comment/84165722
has comment: http://stackoverflow.com/comment/84165498
tagged with: python
has comment: http://stackoverflow.com/comment/84165365
has comment: http://stackoverflow.com/comment/84165026
has answer: http://stackoverflow.com/a/48584419
has comment: http://stackoverflow.com/comment/84164931
type: AnsweredQuestion
tagged with: terminal
has comment: http://stackoverflow.com/comment/84165980
tagged with: google-cloud-platform
answer count: 1
downvote count: 1
tagged with: ssh
has body: I followed the instructions from this answer (https://datascience.stackexchange.com/questions/27352/how-to-run-a-python-script-on-gcp-compute-engine) to connect to a virtual machine which I created on GCP Compute Engine and run a python script from the terminal of my laptop on GCP Compute Engine. This answer suggests that after I have connected to the virtual machine then I must enter the following at the terminal of my laptop: python your_script.py However, when I point to the exact location of my .py file and enter: python /Users/Paul/PycharmProjects/Eyeglasses_colour/Main.py the response is the following: python: can't open file '/Users/Paul/PycharmProjects/Eyeglasses_colour/Main.py': [Errno 2] No such file or directory What is wrong? Can't I run my python script (while connected at the GCP virtual machine)?
score: -1
has comment: http://stackoverflow.com/comment/84165111
has comment: http://stackoverflow.com/comment/84166571
favorite count: 0
accepted answer: http://stackoverflow.com/a/48584419
type: Question
upvote count: 0

http://stackoverflow.com/a/48542196
has comment: http://stackoverflow.com/comment/84079606
upvote count: 2
has comment: http://stackoverflow.com/comment/84080606
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84081172
has comment: http://stackoverflow.com/comment/84132228
has comment: http://stackoverflow.com/comment/84080017
type: Answer
answers question: http://stackoverflow.com/q/48541968
has body: I think you have a problem with this line: conn.execute("INSERT INTO kundenname VALUES (kundename,auftragstyp,auftragsurl,anzahl)", (kundenname, auftragstyp, auftragsurl, anzahl)) This is not the way to insert, try this: conn.execute("INSERT INTO kundenname ('kundename','auftragstyp','auftragsurl','anzahl') VALUES (" + str(kundename) +"," + str(auftragstyp) + "," + str(auftragsurl) + "," + str(anzahl)+")"

http://stackoverflow.com/comment/84197074
type: QuestionComment
has text: Don't parse HTML with regex. Use an HTML parser. Also do you really mean [tag:pyth], or [tag:python]?
score: 5
comment on: http://stackoverflow.com/q/48600219
type: Comment

http://stackoverflow.com/a/48602360
type: Answer
accepted answer of: http://stackoverflow.com/q/48602330
has comment: http://stackoverflow.com/comment/84201267
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48602330
downvote count: 0
has comment: http://stackoverflow.com/comment/84201305
type: AcceptedAnswer
has body: Just rotate the labels by, say, 45 degrees: ax.set_xticklabels(mov_data,rotation=45).

http://stackoverflow.com/comment/84264397
has text: What do you mean by "avoid"?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48632237

http://stackoverflow.com/comment/84201718
score: 1
type: Comment
type: QuestionComment
has text: Do you have a celery worker running? Eg. from the command line, `celery worker -A <your_module_name>`. Stuff should print in the terminal where you started that.
comment on: http://stackoverflow.com/q/48598870

http://stackoverflow.com/comment/84047717
comment on: http://stackoverflow.com/a/48499056
type: AnswerComment
has text: Another approach to simplify this would be to convert the C string to a Python string in Cython. Since the C string was created via Go, its length is known, to make converting to a Python string faster. After it is made into a python object the C string can be de-allocated immediately as it has been copied and the Python string left up to Python to GC, since you'll need to return Python string from the Python function in any case.
score: 1
type: Comment

http://stackoverflow.com/q/48489530
has comment: http://stackoverflow.com/comment/83971866
type: AnsweredQuestion
has title: Regex ignore word and fixing dble slash
downvote count: 2
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48489883
has comment: http://stackoverflow.com/comment/83972014
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83971992
has comment: http://stackoverflow.com/comment/83972287
accepted answer: http://stackoverflow.com/a/48489883
has body: Trying to get a regex, I need it to ignore a specific word but my regex not working correctly. Ex. Our ignore word will be "timeline" and fixing the last 3 lines. Actually, my regex get timeline but i don't need this. example : https://www.example.com/test/timeline (actually) https://www.example.com/test (Perfect) I have a little bug, i don't know why double slash is not included correctly on the 3 last lines? here's my regex : https://regex101.com/r/gPJZeZ/1 How can I ignore timeline and fixing the double slash?
tagged with: python
score: -1
tagged with: regex

http://stackoverflow.com/comment/84262156
score: 0
type: Comment
type: QuestionComment
has text: what happens when you write `python -c "import mudicom" ` in a terminal?
comment on: http://stackoverflow.com/q/48632439

http://stackoverflow.com/comment/84276201
has text: Thanks for the response Vikas. I edited the code above to better addressed the gap in understanding why it does not work.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48618290

http://stackoverflow.com/q/48518358
answer count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: calendar
has answer: http://stackoverflow.com/a/61393776
has answer: http://stackoverflow.com/a/48523973
score: 3
has body: KivyCalendar has been installed using pip in windows 10. But returns an error:- No module named 'calendar_ui My code is: from kivy.app import App from KivyCalendar import CalendarWidget class MyApp(App): def build(self): return CalendarWidget() MyApp().run() Any help would be much appreciated. Thanks
upvote count: 3
has title: Getting error : No module named 'calendar_ui'. even though KivyCalendar has been installed using pip in windows 10
tagged with: python
tagged with: kivy
favorite count: 0
type: Question

http://stackoverflow.com/a/48554546
has comment: http://stackoverflow.com/comment/84105789
has comment: http://stackoverflow.com/comment/84105616
type: Answer
has body: I think you have a couple of different issues here. First, your selector is wrong -- the selector you have is trying to select an element called wu-value-to (which isn't a valid HTML element) inside something with class wu-value inside a span which is a direct descendent of a div. To select an element with particular classes you need no space between the element name and the class descriptors. So your selector should probably be div &gt; span.wu-value.wu-value-to. If your entire HTML is the part you showed, just 'span' would be enough, but I'm guessing you are being specific by specifying the parent and those classes for a reason. Second, you are selecting the element, not its text content. You need your_node.text to get the text content. Putting it together, you should be able to get what you want with this: w_u_soup.select('div &gt; span.wu-value.wu-value-to').text
answers question: http://stackoverflow.com/q/48554509
score: 0
accepted answer of: http://stackoverflow.com/q/48554509
type: AcceptedAnswer

http://stackoverflow.com/comment/84104135
score: 2
type: Comment
comment on: http://stackoverflow.com/a/48553586
type: AnswerComment
has text: Unfortunately, the commas are still disappearing. Do you have any other suggestions? Thanks.

http://stackoverflow.com/q/48562073
answer count: 1
linked to: http://stackoverflow.com/q/637827
has title: Startup shell script not producing output
tagged with: linux
tagged with: bash
type: Question
has body: I am working with Ubuntu 16.04 on an NVIDIA TX2 system and have a shell script launcher.sh containing the following commands: #!/bin/sh cd /home/nvidia sudo python test.py &gt;&gt; /home/nvidia/test_output.txt, basically implying to store the output of test.py in test_output.txt. The test.pyhas one line: print "Testing startup script!" I want this script (and more complicated scripts later on) to run automatically when the system boots up. To this end, I added it to the Startup Applications with the command /home/nvidia/launcher.sh and rebooted the system. The file test_output.txt is indeed created but there is no output written in it. I tested the script from the terminal and it works fine. How do I make this to work from Startup Applications?
tagged with: shell
has comment: http://stackoverflow.com/comment/84120187
accepted answer: http://stackoverflow.com/a/48562471
has comment: http://stackoverflow.com/comment/84120119
has comment: http://stackoverflow.com/comment/84121727
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48562471
has comment: http://stackoverflow.com/comment/84119890
tagged with: python

highest
tag name: highest
tags question: http://stackoverflow.com/q/48493270
type: Tag

http://stackoverflow.com/comment/84186123
comment on: http://stackoverflow.com/q/48594308
score: 0
type: Comment
has text: okay, I added a solution, please check @DwightD
type: QuestionComment

http://stackoverflow.com/comment/84086048
has text: Just added @VivekKumar
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48544522

http://stackoverflow.com/q/48587595
has answer: http://stackoverflow.com/a/48588929
possible better answer: http://stackoverflow.com/a/48587852
upvote count: 8
tagged with: datetime
has answer: http://stackoverflow.com/a/59097445
tagged with: dataframe
tagged with: python
answer count: 4
score: 8
linked to: http://stackoverflow.com/q/38067348
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/48587852
has body: I have a date column in a pandas DF with Julian dates. How can I convert these Julian dates to mm-dd-yyyy format. Sample data ORG CHAIN_NBR SEQ_NBR INT_STATUS BLOCK_CODE_1 DATA_BLOCK_CODE_1 0 523 1 0 A C 2012183 1 523 2 1 I A 2013025 2 521 3 1 A H 2007067 3 513 4 1 D H 2001046 4 513 5 1 8 I 2006075 I was using jd2gcal function but it's not working. I was also trying to write a code like this but of no use. for i,row in amna.iterrows(): amna['DATE_BLOCK_CODE_1'] = datetime.datetime.strptime(row['DATE_BLOCK_CODE_1'], '%Y%j') desired Output: ORG CHAIN_NBR SEQ_NBR INT_STATUS BLOCK_CODE_1 DATA_BLOCK_CODE_1 0 523 1 0 A C mm-dd-yyyy 1 523 2 1 I A mm-dd-yyyy 2 521 3 1 A H mm-dd-yyyy 3 513 4 1 D H mm-dd-yyyy 4 513 5 1 8 I mm-dd-yyyy Please help me with this.
has title: Convert Julian dates to normal dates in a dataframe?
downvote count: 0
has answer: http://stackoverflow.com/a/71783643
linked to: http://stackoverflow.com/q/13943062
accepted answer: http://stackoverflow.com/a/48588929
favorite count: 0
type: Question

http://stackoverflow.com/comment/84004397
type: AnswerComment
score: 0
has text: Yes, True. Thanks @match. I just saw it myself right now.
type: Comment
comment on: http://stackoverflow.com/a/48505233

http://stackoverflow.com/q/48565965
has answer: http://stackoverflow.com/a/48566179
has body: I'm seeing a few scalability problems with a pyspark script I've written and was wondering if anyone would be able to shed a bit of light. I have a very similar use case to the one presented here: Separate multi line record with start and end delimiter In that I have some multi line data that where there is a logical delimiter between records. E.g. the data looks like: AA123 BB123 CCXYZ AA321 BB321 CCZYX ... Using the example in the previous answer, I've separated this into multiple records using a script like... spark = SparkSession \ .builder \ .appName("TimetableSession") \ #Played around with setting the available memory at runtime .config("spark.executor.memory", "8g") \ .config("spark.driver.memory", "8g") \ .getOrCreate() files = os.path.join("data","*_lots_of_gzipped_files.gz") df=spark.sparkContext.textFile(files).toDF() df=df.withColumn("id", monotonically_increasing_id()) w=Window.partitionBy().orderBy('id') df=df.withColumn('AA_indicator', expr("case when entry like 'AA%' then 1 else 0 end")) #!!!Blowing up with OOM errors here at scale!!! df=df.withColumn('index', sum('AA_indicator').over(w)) df.show() +--------------------+---+------------+-----+ | entry| id|AA_indicator|index| +--------------------+---+------------+-----+ | AA123| 1| 1| 1| | BB123| 2| 0| 1| | CCXYZ| 3| 0| 1| | AA321| 4| 1| 2| | BB321| 5| 0| 2| | CCZYX| 6| 0| 2| +--------------------+---+------------+-----+ This seems to work ok with data which is a reasonable size (e.g. 50MB of data) when I scale this up to > 1GB of data I'm seeing Java OOM errors. I'm seeing the same problem even when attempting to allocate > 20GB memory to spark.driver/executor. I believe the problem is that the window for the data partitioned and everything is being collected into memory at once rather than being parralelised? But I might be way off the mark with this. I'm running this script in a standalone docker container using the jupyter pyspark notebook https://github.com/jupyter/docker-stacks/tree/master/pys…
linked to: http://stackoverflow.com/q/35154267
score: 2
tagged with: apache-spark
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/47406640
favorite count: 0
type: Question
has title: Pyspark Out of Memory window function
linked to: http://stackoverflow.com/q/41313488
upvote count: 2
type: UnansweredQuestion
tagged with: pyspark
tagged with: python

http://stackoverflow.com/comment/84278777
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48640978
has text: Also, are you using the correct `transport` and `protocol` as per http://happybase.readthedocs.io/en/latest/api.html#connection ?
score: 1

http://stackoverflow.com/q/48645391
has answer: http://stackoverflow.com/a/49757155
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48645481
tagged with: python
has body: I have a file *.yaml with contents as below: bugs_tree: bug_1: html_arch: filepath moved_by: user1 moved_date: '2018-01-30' sfx_id: '1' I want to add a new child element to this file under the node [bugs_tree] I have tried to do this as below: if __name__ == "__main__": new_yaml_data_dict = { 'bug_2': { 'sfx_id': '2', 'moved_by': 'user2', 'moved_date': '2018-01-30', 'html_arch': 'filepath' } } with open('bugs.yaml','r') as yamlfile: cur_yaml = yaml.load(yamlfile) cur_yaml.extend(new_yaml_data_dict) print(cur_yaml) Then file should looks that: bugs_tree: bug_1: html_arch: filepath moved_by: username moved_date: '2018-01-30' sfx_id: '1234' bug_2: html_arch: filepath moved_by: user2 moved_date: '2018-01-30' sfx_id: '2' When I'm trying to perform .append() OR .extend() OR .insert() then getting error cur_yaml.extend(new_yaml_data_dict) AttributeError: 'dict' object has no attribute 'extend'
score: 14
has answer: http://stackoverflow.com/a/55884206
answer count: 3
has comment: http://stackoverflow.com/comment/127277337
tagged with: yaml
downvote count: 1
has title: How to append data to YAML file
upvote count: 15
tagged with: pyyaml
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84295745

http://stackoverflow.com/a/48522543
accepted answer of: http://stackoverflow.com/q/48522471
score: 2
type: AcceptedAnswer
has body: Download the pytz requirement. For example download the wheel from PyPi. Then install the wheel before Django pip install pytz-2017.3-py2.py3-none-any.whl pip install django-2.0.1.tar.gz As this answer on the duplicate question suggests, you can download Django and its requirement(s) by running: pip download django
downvote count: 0
answers question: http://stackoverflow.com/q/48522471
upvote count: 2
type: Answer

http://stackoverflow.com/comment/84072555
type: AnswerComment
comment on: http://stackoverflow.com/a/48538043
type: Comment
has text: I already said that i have to give only Demo_list[0] then i should get the square of that. i don't want to give any like ur following answers. I just want to give Demo_list[0], i.e; i want to override internal functions
score: 0

http://stackoverflow.com/a/48601482
upvote count: 1
has comment: http://stackoverflow.com/comment/84199618
has body: Like the documentation states: sklearn.preprocessing.normalize(X, norm='l2', axis=1, copy=True, return_norm=False) Scale input vectors individually to unit norm (vector length). So it takes the norm (by default the L2 norm) and then ensures that the vector is unit. So if we take as input an n×m-matrix, the output is an n×m-matrix. Every m-vector is normalized. For norm='l2' (the default), thus this means that the length is calculated (by the square root of the sum of the square of the components), and every element is divided by that length, such that the result is a vector with length 1.
score: 1
answers question: http://stackoverflow.com/q/48601420
downvote count: 0
type: Answer

http://stackoverflow.com/q/48535847
has comment: http://stackoverflow.com/comment/84066967
score: 1
has comment: http://stackoverflow.com/comment/84066999
downvote count: 1
answer count: 1
tagged with: unit-testing
favorite count: 0
has title: Is it possible to use Karate with pycharm?
tagged with: rest
has comment: http://stackoverflow.com/comment/84074459
type: Question
has answer: http://stackoverflow.com/a/48539339
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84068964
tagged with: pycharm
upvote count: 2
tagged with: karate
has body: Is it possible to use Karate with pycharm? If not, what is the best alternative to Karate for python tornado REST APIs? https://github.com/intuit/karate

http://stackoverflow.com/q/48558085
has comment: http://stackoverflow.com/comment/84112043
has title: Real-time anomaly detection from time series data
has comment: http://stackoverflow.com/comment/84112253
type: AnsweredQuestion
upvote count: 2
answer count: 1
has body: I have some problem when detecting anomaly from time series data. I use LSTM model to predict value of next time as y_pred, true value at next time of data is y_real, so I have er = |y_pred - y_t|, I use er to compare with threshold = alpha * std and get anomaly data point. But sometime, our data is effected by admin or user for example number of player of a game on Sunday will higher than Monday. So, should I use another model to classify anomaly data point or use "If else" to classify it?
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/48558428
tagged with: keras
downvote count: 1
has answer: http://stackoverflow.com/a/48558428
favorite count: 0
type: Question
tagged with: time-series
has comment: http://stackoverflow.com/comment/84111935
score: 1
tagged with: python

aws-cloudformation
tag name: aws-cloudformation
type: Tag
tags question: http://stackoverflow.com/q/48617759
tags question: http://stackoverflow.com/q/48548135

http://stackoverflow.com/comment/84672597
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48613887
has text: Be aware that using just "+" will make you possibly vulnerable to an SQL injection attack - use placeholders!
score: 0

http://stackoverflow.com/q/48532686
tagged with: python
has body: I found and used the following code to do authentication with Python3.6 and Chrome Webdriver. driver.get(url) shell = win32com.client.Dispatch("WScript.Shell") shell.Sendkeys(username) shell.Sendkeys("{TAB}") shell.Sendkeys(password) shell.Sendkeys("{ENTER}") It worked perfectly fine until I had to schedule the script in Windows task scheduler. When the authentication box fires, instead of entering username and password in the field, they are output in cmd or press windows 'Start' icon and pause there. My intuition is I have to fix the object name to Chrome webtab in win32com.client.Dispatch, but after several hours of research, I still have no clue. I also tried other ways to do authentication but this one is by far the only one works. Thank you!
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84062172
downvote count: 0
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/84084182
favorite count: 0
type: Question
has title: Authentication using selenium chrome webdriver and task scheduler
tagged with: win32com
score: 1

http://stackoverflow.com/q/48630109
has title: Curl command succeeded but python requests get 403 Forbidden
tagged with: python
tagged with: request
tagged with: http-status-code-403
has answer: http://stackoverflow.com/a/48638926
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48638926
answer count: 1
downvote count: 0
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/84259237
tagged with: python-requests
favorite count: 0
type: Question
score: 5
upvote count: 5
has body: I try to get a data from this website. I get the cUrl command: curl 'http://mayaapi.tase.co.il/api/report/filter?logo=0' -H 'Origin: http://maya.tase.co.il' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' -H 'X-Maya-With: allow' -H 'Content-Type: application/json;charset=UTF-8' -H 'Referer: http://maya.tase.co.il/reports/fund?q=%7B%22DateFrom%22:%222016-12-31T22:00:00.000Z%22,%22DateTo%22:%222018-02-03T22:00:00.000Z%22,%22QOpt%22:1,%22Page%22:1,%22Q%22:%22%D7%93%D7%95%D7%97%20%D7%97%D7%95%D7%93%D7%A9%D7%99%22,%22events%22:%5B%5D,%22subevents%22:%5B%5D%7D' --data-binary $'{"Page":1,"GroupData":[],"DateFrom":"2016-12-31T22:00:00.000Z","DateTo":"2018-02-03T22:00:00.000Z","IsBreakingAnnouncement":false,"IsForTaseMember":false,"IsSpecificFund":false,"Q":"\u05d3\u05d5\u05d7 \u05d7\u05d5\u05d3\u05e9\u05d9","QOpt":1,"ViewPage":4}' --compressed and when I do it from the command line I get a response. But when I try to do it in python with requests, I get 403 Forbidden. The python code: response = requests.post( "http://mayaapi.tase.co.il/api/report/filter?logo=0", data={ "Page": 1, "GroupData": [], "DateFrom": "2016-12-31T22:00:00.000Z", "DateTo": "2018-02-03T22:00:00.000Z", "IsBreakingAnnouncement": False, "IsForTaseMember": False, "IsSpecificFund": False, "Q": "דוח חודשי", "QOpt": 1, "ViewPage": 4, }, headers={ "Content-Type": "application/json;charset=UTF-8", "Origin": "http://maya.tase.co.il", "Referer": "http://maya.tase.co.il/reports/fund?q=%7B%22DateFrom%22:%222016-12-31T22:00:00.000Z%22,%22DateTo%22:%222018-02-03T22:00:00.000Z%22,%22QOpt%22:1,%22Page%22:1,%22Q%22:%22%D7%93%D7%95%D7%97%20%D7%97%D7%95%D7%93%D7%A9%D7%99%22,%22events%22:%5B%5D,%22subevents%22:%5B%5D%7D", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", "X-Maya-With": "allow", }, cookies={} ) print('req1', response) I tried any…

http://stackoverflow.com/comment/83980330
comment on: http://stackoverflow.com/a/48493572
type: Comment
type: AnswerComment
has text: because you shouldn't encourage such low quality questions by answering them.
score: 0

http://stackoverflow.com/q/48499811
score: 3
type: UnansweredQuestion
tagged with: graphql
has title: How to make multiple queries filters in graphene flask?
has body: I'm a relative newcomer to GraphQL, I'm trying to make a query like this { user(username: "Jon") { name last_lame username posts(in_draft : true) { title text in_draft update_at } } } I want to filter the list of posts that the user has in draft The only way I can do the query is through the relationship of the models, but without being able to filter in the posts in draft. One to many class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Column(String) last_lame = Column(String) username = Column(String) class Post(Base): __tablename__ = 'post' id = Column(Integer, primary_key=True) title = Column(String) text = Column(String) in_draft = Column(Boolean) post_id = Column(Integer, ForeignKey('user.id')) posts = relationship("User", backref='posts') With this relationship, I show the posts node with "backref = 'posts'" My objects: class User(SQLAlchemyObjectType): """User Object.""" class Meta: model = UserModel interfaces = (relay.Node, ) class Post(SQLAlchemyObjectType): """Post Object.""" class Meta: model = PostModel # interfaces = (relay.Node, ) Query: class Query(graphene.ObjectType): user = graphene.Field(lambda: User, username=graphene.String()) def resolve_user(self, info, username): query = User.get_query(info) return query.filter(UserModel.username == username).first() I want to make the query of the posts belong to the user posts = graphene.List(lambda: Post, in_draft=graphene.Boolean()) def resolve_posts(self, info, in_draft): query = Post.get_query(info) return query.filter(PostModel.in_draft == in_draft).all() schema = graphene.Schema( query=Query, types=[User, Post]) Any idea or suggestion?
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/49830535
answer count: 1
downvote count: 0
tagged with: flask
tagged with: flask-sqlalchemy
tagged with: graphene-python
favorite count: 0
type: Question

http://stackoverflow.com/comment/83991442
score: 0
type: AnswerComment
has text: Basically I have a master list c (dataframe) with customer ID and another subset list b (float64) also containing the customer ID. I want to create a new column or a separate table where if customer is in both list a and b then it updates with a 1 otherwise 0.
type: Comment
comment on: http://stackoverflow.com/a/48497712

codec
tags question: http://stackoverflow.com/q/48532538
tag name: codec
type: Tag

http://stackoverflow.com/a/48577194
has comment: http://stackoverflow.com/comment/84150806
type: Answer
score: 0
has body: The basic python data structure you are looking for is a dictionary, not a list. Dictionaries allow key-value pairing in a native way. Example. d={akey:aval} d['mykey']=myval then you can retrieve you values print(d['mykey'])
answers question: http://stackoverflow.com/q/48577136

http://stackoverflow.com/a/48571357
upvote count: 0
has body: You could load the file do the replacement, e.g. string_containing_modified_data = data_as_string.replace('\\&gt;', '/&gt;') use etree.fromstring(string_containing_modified_data) to parse the xml. If possible, you should try to fix the writer, but I understand if you don't have the opportunity to do so.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84172865
downvote count: 1
has comment: http://stackoverflow.com/comment/84173384
accepted answer of: http://stackoverflow.com/q/48571060
answers question: http://stackoverflow.com/q/48571060
type: Answer
score: -1

http://stackoverflow.com/comment/84131111
type: Comment
comment on: http://stackoverflow.com/q/48567471
has text: what did you try already?
score: 0
type: QuestionComment

http://stackoverflow.com/q/48561981
score: 131
has answer: http://stackoverflow.com/a/78768036
linked to: http://stackoverflow.com/q/29146792
type: Question
has body: I have a Dockerfile where I tried to activate python virtualenv so that, it should install all dependencies within this env. However, everything still gets installed globally. I used different approaches and none of them worked. I am also not getting any errors. Where is the problem? 1. ENV PATH $PATH:env/bin 2. ENV PATH $PATH:env/bin/activate 3. RUN . env/bin/activate I also followed an example of a Dockerfile config for the python-runtime image on Google Cloud, which is basically the same stuff as above. Setting these environment variables are the same as running source /env/bin/activate. ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH Additionally, what does ENV VIRTUAL_ENV /env mean and how it is used?
has answer: http://stackoverflow.com/a/59200322
has answer: http://stackoverflow.com/a/56286534
tagged with: python
has comment: http://stackoverflow.com/comment/128586560
tagged with: virtualenv
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51919568
has answer: http://stackoverflow.com/a/48562835
has answer: http://stackoverflow.com/a/53008740
tagged with: docker
upvote count: 131
has comment: http://stackoverflow.com/comment/84120948
has comment: http://stackoverflow.com/comment/84119713
has comment: http://stackoverflow.com/comment/86007418
has title: Activate python virtualenv in Dockerfile
answer count: 9
has answer: http://stackoverflow.com/a/78851316
downvote count: 0
has answer: http://stackoverflow.com/a/76274293
tagged with: dockerfile
has answer: http://stackoverflow.com/a/48565216
favorite count: 0
tagged with: python-venv

http://stackoverflow.com/q/48495433
type: Question
tagged with: model
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83984509
tagged with: django
tagged with: python
score: 3
tagged with: metaclass
upvote count: 3
downvote count: 0
answer count: 1
has title: Find model instance from table name in Django
has comment: http://stackoverflow.com/comment/83984454
has body: I've the following table. class TempTable(models.Model): name = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) ... ... class Meta: db_table = 'temp_table' Now suppose I know the table name temp_table. Currently I'm using the following script to get the model instance from table name. from django.db.models import get_app, get_models all_models = get_models() for item in all_models: if item._meta.db_table == 'temp_table': return item Are there any better ways of achieving this..??
has answer: http://stackoverflow.com/a/48496056
favorite count: 0

http://stackoverflow.com/a/63316299
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48527785
has comment: http://stackoverflow.com/comment/111968181
type: Answer
has body: Renaming the bokeh.py file and deleting bokeh.pyc file solved it for me.
score: 1

http://stackoverflow.com/comment/84184136
has text: The answer is fine, and thanks for acknowledging that it is best not to enable lazy OPs like this. Homework is not the issue here. Asking for free code with zero demonstrated effort is.
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48593390

http://stackoverflow.com/a/48791576
downvote count: 0
answers question: http://stackoverflow.com/q/48608501
has comment: http://stackoverflow.com/comment/84742431
score: 3
type: Answer
has body: If you want to perform an individual 1D convolution over the 40 feature channels you should add a dimension to your input: (1500,40,1) if you perform 1D convolution on a input with shape (1500,40) the filters are applied on the time dimension and the pictures you posted indicate that this is not what you want to do.
has comment: http://stackoverflow.com/comment/84743244
upvote count: 3

http://stackoverflow.com/comment/84132930
type: Comment
type: QuestionComment
score: 8
comment on: http://stackoverflow.com/q/48568322
has text: `[x +1 if x % 2 == 0 else x for x in Input_array]`

http://stackoverflow.com/q/48630035
type: Question
linked to: http://stackoverflow.com/q/5824881
has comment: http://stackoverflow.com/comment/84257318
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have just started with Python and have been studying the code of a particular library. The library contains an Html class whose initialization looks like this page = Html()( # add tags inside the one you created calling the parent Head()( # add multiple tags in one call Meta(charset='utf-8'), # add tag attributes using kwargs in tag initialization Link(href="my.css", typ="text/css", rel="stylesheet") ), body=Body()( # give them a name so you can navigate the DOM with those names Div(klass='linkBox')( A(href='www.foo.com') ), (P()(text) for text in my_text_list), # tag insertion accepts generators another_list # add text from a list, str.join is used in rendering ) ) and the class definition looks like this class Html(Tag): """Html tag have a custom render method for it needs to output the Doctype tag outside the main page tree. Every Html object is associated with a Doctype object (default doctype code: 'html'). """ __tag = 'html' def __init__(self, *args, **kwargs): # Setting a default doctype: 'html' doctype = kwargs.pop('doctype', 'html') super().__init__(**kwargs) self.doctype = Doctype(doctype) My question is why is the second set of parentheses needed in the Html object initialization? The init does not return a function here. The full code can be found here https://github.com/Hrabal/TemPy/tree/master/tempy https://github.com/Hrabal/TemPy/blob/master/tempy/tempy.py
has title: Python Object initialization with two sets of parentheses
answer count: 1
accepted answer: http://stackoverflow.com/a/48630206
has answer: http://stackoverflow.com/a/48630206

http://stackoverflow.com/comment/84019821
type: QuestionComment
comment on: http://stackoverflow.com/q/48512393
has text: You're very close. I'll give you some hints: you want the opposite of `startswith()` and maybe checking the length could be helpful.
type: Comment
score: 1

http://stackoverflow.com/comment/84007645
type: AnswerComment
comment on: http://stackoverflow.com/a/48505664
has text: Thanks, this seems to be exactly what I want to do. The problem is that I get the error: AttributeError: "Worksheet has no attribute cell" or also AttributeError: "Worksheet has no attribute append". I'm also using the newest version of openpyxl. What's wrong?
score: 0
type: Comment

http://stackoverflow.com/comment/84202029
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48602601
has text: @MTG: initialized dictionary? You can not calculate the power of a dictionary. I tested it with some values (see edited answer).
type: AnswerComment

http://stackoverflow.com/comment/84105757
type: QuestionComment
comment on: http://stackoverflow.com/q/48554577
has text: Thanks for the quick response, just what I'm looking for! If you want to move this to an answer I'll happily vote it once I test it :)
type: Comment
score: 0

http://stackoverflow.com/comment/84139766
type: Comment
type: QuestionComment
has text: Re. your second question - https://stackoverflow.com/q/4396974/2877364
comment on: http://stackoverflow.com/q/48571463
score: 1

http://stackoverflow.com/comment/84238337
has text: When you do `for element in jsonresponse[u'available_projects']:` you're iterating over the _keys_ of the dict (i.e. `element` is a string). You want to iterate over the dict's _values_ instead.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48620892

http://stackoverflow.com/comment/84107073
type: QuestionComment
comment on: http://stackoverflow.com/q/48533983
score: 0
has text: @DanilaGanchar Thanks for the tips. For my use case a monolithic code base is a lot easier to deploy. I'll use uwsgi and nginx for deployment when it's production ready though.
type: Comment

http://stackoverflow.com/comment/84017783
type: AnswerComment
has text: The OP is already using numpy. This round is a part of numpy. Also, anything wrong with importing math? I guess in case you want the least amount of modules possible it would be ok.
comment on: http://stackoverflow.com/a/48511307
type: Comment
score: 0

http://stackoverflow.com/comment/84147937
has text: But what value does current_name contain?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48575624
type: Comment

http://stackoverflow.com/q/48621559
score: 1
tagged with: classification
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48643652
has answer: http://stackoverflow.com/a/48643652
has body: I am new to keras and have read blog posts about deep learning classification using keras but, even after reading a lot of them, I am unable to figure out how each of them have calculated the parameter value of first dense layer just after flatten layer in their code. for example: from keras.models import Sequential from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten def createModel(): model = Sequential() model.add(Conv2D(32, (3, 3), padding='same', activation='relu',input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3), padding='same', activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3), padding='same', activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(nClasses, activation='softmax')) My doubts: How did the programmer decide on the value '512' for this dense layer? Is it totally random? because I know that in this example, flatten has 256 parameters so logic says they are multiplying it by 2 to get the value of 512. But, this logic does not follow in any other case I have read. How did this dense layer affect the training? If I put too large a value, like in my code below, going by the logic I multiplied my flatten parameter 86400 by 2 i.e. 172800, I get the following error: model = Sequential() model.add(Conv2D(32, (3, 3),input_shape=input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3) )) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(96, (3, 3))) model.add(Activation('relu')) model.add…
tagged with: python
type: AnsweredQuestion
tagged with: keras-layer
has title: How to calculate dense layer output parameter value
tagged with: deep-learning

http://stackoverflow.com/comment/84053736
score: 0
has text: I believe the problem lies within the way pycharm handles packages.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48529159

docker
tags question: http://stackoverflow.com/q/48550191
tags question: http://stackoverflow.com/q/48568918
tag name: docker
tags question: http://stackoverflow.com/q/48579428
tags question: http://stackoverflow.com/q/48591664
type: Tag
tags question: http://stackoverflow.com/q/48643360
tags question: http://stackoverflow.com/q/48507340
tags question: http://stackoverflow.com/q/48598273
tags question: http://stackoverflow.com/q/48522640
tags question: http://stackoverflow.com/q/48637148
tags question: http://stackoverflow.com/q/48493028
tags question: http://stackoverflow.com/q/48527958
tags question: http://stackoverflow.com/q/48613669
tags question: http://stackoverflow.com/q/48554539
tags question: http://stackoverflow.com/q/48521983
tags question: http://stackoverflow.com/q/48514589
tags question: http://stackoverflow.com/q/48609297
tags question: http://stackoverflow.com/q/48607096
tags question: http://stackoverflow.com/q/48624632
tags question: http://stackoverflow.com/q/48588449
tags question: http://stackoverflow.com/q/48520750
tags question: http://stackoverflow.com/q/48543834
tags question: http://stackoverflow.com/q/48591394
tags question: http://stackoverflow.com/q/48595858
tags question: http://stackoverflow.com/q/48630545
tags question: http://stackoverflow.com/q/48561981
tags question: http://stackoverflow.com/q/48511058

http://stackoverflow.com/comment/103448075
has text: @pdoherty926 I just tested it again and it still works for me, now under Python 3.7.3. You have to import `patch` from `unittest.mock` in case that's unclear.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48552812
type: Comment

http://stackoverflow.com/q/48520393
tagged with: shapefile
has body: I am searching way to fill polygons of a shapefile based on a value. So far from basemap tutorial (http://basemaptutorial.readthedocs.io/en/latest/shapefile.html) i 've found how to fill the polygons with a specific color. import matplotlib.pyplot as plt import pypyodbc from mpl_toolkits.basemap import Basemap from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection from matplotlib.patches import PathPatch import numpy as np fig= plt.figure() ax= fig.add_subplot(111) m=Basemap(projection='cyl',llcrnrlat=34.5,llcrnrlon=19,urcrnrlat=42,urcrnrlon=28.5,resolution='h') m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='#ddaa66',lake_color='aqua') m.drawcoastlines() m.readshapefile('nomoi','nomoi') patches = [] for info, shape in zip(m.nomoi_info, m.nomoi): if info['ID_2'] == 14426: patches.append( Polygon(np.array(shape), True) ) ax.add_collection(PatchCollection(patches, facecolor='m', edgecolor='k', linewidths=1., zorder=2)) plt.show() What I would like to do is taking values from a dictionary such as this: dict1={14464: 1.16, 14465: 1.35, 14466: 1.28, 14467: 1.69, 14468: 1.81, 14418: 1.38} in which the keys are the info['ID_2'] column from the shapefile as in the code presented above and the values are the variable that i want to represent to color. Meaning to have a colormap varying from 1.16 to 1.81 and each polygon (ID_2) to have a color related to it's value from dict1. Thanks in advance
has title: Filling shapefile polygons with a color in matplotlib
type: Question
upvote count: 5
score: 5
downvote count: 0
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/84035773
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84037528
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/48522450
tagged with: matplotlib-basemap
favorite count: 0
has answer: http://stackoverflow.com/a/48522450

http://stackoverflow.com/q/48524014
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/84043813
tagged with: whatsapp
answer count: 1
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48553684
linked to: http://stackoverflow.com/q/16896685
has title: How to send a pdf file with Whatsapp Web using Selenium and Python in Windows 10
score: 2
upvote count: 2
has body: I am trying to send some payment receipts via Whastapp Web, as I have done via e-mail, but I can not specify the name of the file to send and press 'Enter' in the Windows common control dialog. I know that it is not possible to do it directly with Selenium and I've tried with win32gui, without success. This is the code I've been using to test: import win32gui from selenium import webdriver from selenium.webdriver.common.keys import Keys send_to = 'John Smith' attach_name = "GyG Recibo_00741.pdf" # Lets use Chrome as web browser web_driver = webdriver.Chrome('ChromeDriver') # Open WhatsApp Web web_driver.get('http://web.whatsapp.com') web_driver.implicitly_wait(100) # seconds # Find destinatary new_chat = web_driver.find_element_by_id('input-chatlist-search') new_chat.send_keys(send_to, Keys.ENTER) # Press Attach button button = web_driver.find_elements_by_xpath('//*[@id=\"main\"]/header/div[3]/div/div[2]/div/span') button[0].click() # Press Document button inp_xpath = '//*[@id=\"main\"]/header/div[3]/div/div[2]/span/div/div/ul/li[3]/button' button = web_driver.find_elements_by_xpath(inp_xpath) button[0].click() # Loop until Open dialog is displayed (my Windows version is in Spanish) hdlg = 0 while hdlg == 0: hdlg = win32gui.FindWindow(None, "Abrir") # Set filename and press Enter hwnd = 0x000047C # ControlID (as reported by Spy++) filename = attach_name ent = "{ENTER}" win32gui.SetDlgItemText(hdlg, hwnd, filename) win32gui.SetDlgItemText(hdlg, hwnd, ent)
type: UnansweredQuestion

http://stackoverflow.com/q/48578235
type: Question
has body: I have been doing some experiments with the sklearn RandomForestClassifier. I am training multiple trees on multiple batches and merging them using: def combine_rfs(rfList): rf1 = rfList[0] for i in range(1,len(rfList)): rf1.estimators_ += rfList[i].estimators_ rf1.n_estimators = len(rf1.estimators_) return rf1 I noticed that if I give an equal number of samples in category A and category B, the classification of the final tree tends to be 40-60% category A, and 40-60% category B, despite that I would have expected it to be much more in A, and less in B. Basically what I am seeing is that the proportion of samples in A/B will dictate the proportion of classifications for these categories, no matter what the actual proportion of these categories in the test data. How can I mitigate this effect?
score: 3
tagged with: random-forest
type: UnansweredQuestion
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/48580015
has title: Random Forest: Effect of Number of Samples in Each Class
has comment: http://stackoverflow.com/comment/84154789
answer count: 1
downvote count: 0
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/comment/84275286
type: Comment
comment on: http://stackoverflow.com/q/48628394
type: QuestionComment
score: 0
has text: Thanks will definitely have a look :)

http://stackoverflow.com/comment/84204986
type: AnswerComment
comment on: http://stackoverflow.com/a/48604036
type: Comment
has text: @StefanPochmann, see the edit just now for a doc reference. It's explicitly pointing out what can go _wrong_, but you can also infer from it the behavior I already described.
score: 0

http://stackoverflow.com/a/48589059
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48588932
has body: I don't know of a way to do this directly in numpy, but you could always iterate through the array and write your comments and the line to a file. a = np.array([[10,5,2],[7,2,6],[8,3,1]]) print(" " + " ".join([str(x+1)+"C" for x in range(a.shape[1])])) for i, row in enumerate(a): print("%dL %s" % (i+1, "; ".join(map(str, row)))) # 1C 2C 3C #1L 10; 5; 2 #2L 7; 2; 6 #3L 8; 3; 1 To write to a file: with(open('path/to/file', 'w') as f): header = " " + " ".join([str(x+1)+"C" for x in range(a.shape[1])]) f.write(header + "\n") for i, row in enumerate(a): line = "%dL %s" % (i+1, "; ".join(map(str, row))) f.write(line + "\n")
has comment: http://stackoverflow.com/comment/84175581
type: Answer
answers question: http://stackoverflow.com/q/48588932
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/84003694
type: Comment
comment on: http://stackoverflow.com/q/48504867
score: 2
type: QuestionComment
has text: Try https://stackoverflow.com/a/40366276/1283083

http://stackoverflow.com/comment/104121053
type: AnswerComment
comment on: http://stackoverflow.com/a/48568366
has text: yes it works, but when there is an object with value 'null' like: { "value": null } the output is: { "value": None } And None is a JS error
score: 0
type: Comment

http://stackoverflow.com/q/48638004
type: Question
has comment: http://stackoverflow.com/comment/84272941
has title: Adjust all nested lists to the same length
has comment: http://stackoverflow.com/comment/84273870
score: 8
upvote count: 9
tagged with: python-3.x
tagged with: python
linked to: http://stackoverflow.com/q/12550929
accepted answer: http://stackoverflow.com/a/48638541
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48638238
tagged with: list
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/48638541
has answer: http://stackoverflow.com/a/48638238
has comment: http://stackoverflow.com/comment/84272395
has comment: http://stackoverflow.com/comment/84272957
has body: I am referring to this this specific answer Making nested lists same length. Since I don't have the permissions to comment yet and answering with a question to that topic would violate the rules, I am asking a new question. I don't fully understand the answer. In my understanding the iterator row in the for-loop is usually an integer value which iterates over each element in myList. So how is it possible to use len(row) as part of the condition since it is just an integer? Is there something I am missing? I have tried to apply this solution to my code but as expected I receive an error saying TypeError: object of type 'int' has no len() args = ("object of type 'int' has no len()",) with_traceback = &lt;built-in method with_traceback of TypeError object&gt; referring to this line row.extend(['null'*(len(maxSS7) - len(row))]) Further I don't understand the use of .extend with row which is the iterator and not a list. Here is the relevant part from the answer. maxLen = max(map(len, myList)) for row in myList: if len(row) &lt; maxLen: row.extend(...) A brief walkthrough would be greatly appreciated. Or maybe there is a better way to adjust the lengths of all nested list to same length.
downvote count: 1
has comment: http://stackoverflow.com/comment/84272330
favorite count: 0

canvas
tags question: http://stackoverflow.com/q/48544583
tag name: canvas
type: Tag
tags question: http://stackoverflow.com/q/48526531
tags question: http://stackoverflow.com/q/48505575

opencv3.0
tags question: http://stackoverflow.com/q/48611517
type: Tag
tags question: http://stackoverflow.com/q/48589151
tags question: http://stackoverflow.com/q/48509138
tags question: http://stackoverflow.com/q/48583135
tag name: opencv3.0

http://stackoverflow.com/q/48608389
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84233246
possible better answer: http://stackoverflow.com/a/48618530
has answer: http://stackoverflow.com/a/48631693
tagged with: database-migration
has answer: http://stackoverflow.com/a/48618530
tagged with: django
tagged with: python
has body: I have several apps in my Django 2.0.2 project. One of the apps (app_one) has a migration that depends on migrations from the other app (app_two) being installed. It is initial migration of app_one and it looks like this: def import_data(apps, schema_editor): schema_model = apps.get_model('app_two', 'Model') # do import def drop_data(apps, schema_editor): schema_model = apps.get_model('app_two', 'Model') # undo import class Migration(migrations.Migration): dependencies = [ ('app_two', '0005_auto_20180127_2155') ] operations = [ migrations.RunPython( import_data, reverse_code=drop_data ) ] Currently in order to install the database I need to manage.py migrate app_two and only after that do manage.py migrate, because otherwise I get an error on this migration that relation Model from app_two does not exist. Also I'm unable to run tests manage.py test normally due to the same error. It seems that Django ignores dependency in this migration for some reason. How do I fix that?
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48610919
accepted answer: http://stackoverflow.com/a/48631693
answer count: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84218043
tagged with: migration
has title: How to fix order of Django migrations?
downvote count: 0
has comment: http://stackoverflow.com/comment/84248560
favorite count: 0
type: Question

http://stackoverflow.com/comment/84017579
comment on: http://stackoverflow.com/q/48511319
score: 0
has text: You have to design your own algorithm to judge the simlimar word, it does have some libs like [difflib](https://docs.python.org/2/library/difflib.html#difflib.get_close_matches) already implement it, but may not meet your requirements.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84003538
has text: Replace each item in the list with the *new* string or make a new list with the new strings.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48504813

firefox
type: Tag
tags question: http://stackoverflow.com/q/48520690
tags question: http://stackoverflow.com/q/48551161
tag name: firefox
tags question: http://stackoverflow.com/q/48639399
tags question: http://stackoverflow.com/q/48641884
tags question: http://stackoverflow.com/q/48509816

http://stackoverflow.com/q/48567772
has comment: http://stackoverflow.com/comment/84131861
type: Question
score: 0
tagged with: google-text-to-speech
tagged with: python
linked to: http://stackoverflow.com/q/352478
has body: So I am trying to write a python program to speak out a sentence . For this purpose I am trying to use the "gTTS" Python library . It works fine in my Laptop (windows 10) and the sound plays well . However , when I run the same code in Raspberry Pi 2 , the audio file is not played . I have used omxplayer as well as mplayer , but the result remains the same . I have tried using other mp3 files , directly downloaded from the internet , and they work fine . But the files saved through the python program (see below) , do not work . from gtts import gTTS import os print("Converting your text to sound . . .") tts = gTTS(text="hello world I am doing fine", lang='en') tts.save("voice.mp3") print("Starting audio. . .") os.system("omxplayer voice.mp3") print("Thank You !!") The omxplayer just shows the following message and exits . omxplayer Output Please help .
has answer: http://stackoverflow.com/a/48568696
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/84131816
type: UnansweredQuestion
tagged with: text-to-speech
answer count: 1
tagged with: omxplayer
has title: How to save a text to audio in Raspberry Pi/Python?

http://stackoverflow.com/q/48521203
has body: I am attempting to use python's getopt to parse some input arguments, but my options are not recognised. Why does the following happen? What am I doing wrong? &gt;&gt; $ ipython Python 2.7.6 (default, Nov 23 2017, 15:49:48) Type "copyright", "credits" or "license" for more information. IPython 1.2.1 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object', use 'object??' for extra details. In [1]: import getopt In [2]: opts, args = getopt.getopt(['arg1', '-f', '-l'], "filo:t:", ["help", "output="]) In [3]: opts Out[3]: [] In [4]: args Out[4]: ['arg1', '-f', '-l']
answer count: 1
has title: Why is python getopt not parsing my options and instead think they are arguments?
has comment: http://stackoverflow.com/comment/84037373
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48521515
accepted answer: http://stackoverflow.com/a/48521515
upvote count: 2
has comment: http://stackoverflow.com/comment/84037537
downvote count: 0
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/48580096
type: Question
linked to: http://stackoverflow.com/q/12169839
has body: I am hoping to create a system for my game where the user is able to save some of their information into a file; however, I am unsure if I would be able to name the file after the name they input. ("james" becoming "james.txt" would be an example of what I would like to happen) import pygame def playerSave(playerName): player = open("player1.txt", "w") player.write("test") player.close() playerLoad() def playerLoad(): player = open("player1.txt", "r") message = player.read() print (message) player.close() playerName = "james" playerSave(playerName) I am unsure how to do this but the above code shows what I have so far. Any help is much appreciated :)
score: -2
tagged with: python
possible better answer: http://stackoverflow.com/a/48580216
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48580216
has title: Custom File Names
has comment: http://stackoverflow.com/comment/84156488
upvote count: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/48580196
tagged with: file
has answer: http://stackoverflow.com/a/48580196
favorite count: 0

http://stackoverflow.com/comment/84083357
type: Comment
comment on: http://stackoverflow.com/q/48516165
type: QuestionComment
has text: @Philippe Skip worktree is definitely something new i came across but it still isnt useful to me. I want the files to change when I switch branch.
score: 0

http://stackoverflow.com/q/48594862
has answer: http://stackoverflow.com/a/48610596
has body: I want to create a nested layout in bokeh with 2 columns. The left column has 2 plots, one above the other. The right column has a number of widgets, all stacked ontop of each other. I also want everything to autofit within the browser window: I currently have something like this: from bokeh.io import curdoc from bokeh.layouts import row, column, widgetbox, layout from bokeh.models import ColumnDataSource from bokeh.models.widgets import Slider, TextInput, Button, CheckboxGroup, RadioButtonGroup from bokeh.plotting import figure # Set up data source = ColumnDataSource(data=dict(time=[1,2,3], acc=[1,2,3])) source_raw = ColumnDataSource(data=dict(time=[1,2,3], acc=[1,2,3])) ## Top plot_orig = figure(tools="crosshair,pan,reset,save,wheel_zoom") line_orig = plot_orig.line('time', 'acc', source=source, line_width=1, line_alpha=1) ## Bottom plot_new = figure(tools="crosshair,pan,reset,save,wheel_zoom") line_new = plot_new.line('time', 'acc', source=source, line_width=1, line_alpha=1) # Set up widgets sub = TextInput(value="1", title="Option #:") trial = TextInput(value="1", title="Option #:") signal_type = RadioButtonGroup(labels=["Raw", "Filtered", "Both"], active=1) flip_signal_active = [] flip_signal_btn = CheckboxGroup(labels=["Flip signal"], active=flip_signal_active) filter_order = Slider(title="Filter order", value=2, start=2, end=20, step=1) filter_threshold = Slider(title="Filter threshold (Hz)", value=10, start=1, end=20, step=1) reset_options_btn = Button(label="Set Default Options", button_type="danger") value = Slider(title="Minimum value", value=0.6, start=0, end=1, step=0.01) distance = Slider(title="Minimum distance", value=30, start=0, end=100, step=0.01) deletions = TextInput(value="", title="Peaks to delete (comma separated):") reset_params_btn = Button(label="Set Default Parameters", button_type="danger") save_params_btn = Button(label="Save Parameters", button_type="success") # Set up layouts and add to document sub_trial = widgetbox(sub, trial) optio…
answer count: 1
downvote count: 0
tagged with: bokeh
favorite count: 0
type: Question
tagged with: graph
upvote count: 2
type: UnansweredQuestion
tagged with: data-visualization
tagged with: python
has title: Bokeh nested column layout
has comment: http://stackoverflow.com/comment/84200374
has comment: http://stackoverflow.com/comment/84204581
score: 2

http://stackoverflow.com/q/48619162
type: Question
has comment: http://stackoverflow.com/comment/84305358
tagged with: ruby
has title: Loading and reading Ruby Marshal dump files in Python
has answer: http://stackoverflow.com/a/66365620
has comment: http://stackoverflow.com/comment/84236731
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84266155
score: 0
has comment: http://stackoverflow.com/comment/84254693
answer count: 1
has body: Simply put, I would like to (if possible) load a Ruby Marshal dump (.dat) file into Python and parse it back into something readable. I've looked into the Pickle, Marshal and RubyMarshal modules but ended up getting errors each time. The following errors had occured: Pickle: Traceback (most recent call last): File "C:\Users\User\Saved Games\unmarshal\unmarsh.py", line 2, in &lt;module&gt; ma = pickle.load(open('file.dat','rb')) _pickle.UnpicklingError: invalid load key, '\x04'. Marshal: Traceback (most recent call last): File "C:\Users\User\Saved Games\unmarshal\unmarsh.py", line 2, in &lt;module&gt; ma = marshal.load(open('file.dat','rb')) ValueError: bad marshal data (unknown type code) RubyMarshal (using their base example) doesn't error but it doesn't accomplish what I am after, meaning it remains the same. Any insight on these would be extremely useful.

http://stackoverflow.com/comment/84241584
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48619710
has text: @MaciejGol - fixed the import line - thanks. the `str` might not be needed here, but it's good practice since `join` will die if it ever isn't a string.
score: 0

http://stackoverflow.com/a/48537640
answers question: http://stackoverflow.com/q/48535962
has comment: http://stackoverflow.com/comment/84080965
accepted answer of: http://stackoverflow.com/q/48535962
has body: Let me rewrite it in this block. Levels in train data: (-1, 0) Levels in test data: (-1, 0, 1, 2, 3) I think that the best way will be: create 2 columns for train data (1st column will have 1 where value == -1 and 0 otherwise; 2nd column will have 1 where value == 0 and 0 otherwise) group (1, 2, 3) in test data do the same encoding as in the first bullet but for group you will have 0 in the first column and 0 in the second column So you will have 2 levels in general (for value == -1 and value == 0) and 3rd level where all values in one-hot-encoded vector will be equal to zero.
type: Answer
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84082473

http://stackoverflow.com/comment/103609127
type: AnswerComment
comment on: http://stackoverflow.com/a/48640292
score: 2
type: Comment
has text: Hold on, depending on how you are using the deque, the "front" of the deque might be at the beginning! (i.e. `d[0]`)

http://stackoverflow.com/comment/84120692
type: QuestionComment
has text: is your goal to modify the dataframe (adding many columns for specific dates), or just create function which will interpolate for you for a specific row and date?
score: 0
comment on: http://stackoverflow.com/q/48562123
type: Comment

http://stackoverflow.com/a/48627947
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48627444
type: Answer
has body: Just use pip with Pyhton 3: sudo python3 -m pip install flask It will do the job for the rightful version of Python. And always invoke your script with python3 to be sure you are using the proper version. You can also check with which command to understand what binary will be executed when invoking in shell: jlandercy@themis:~$ which python /usr/bin/python jlandercy@themis:~$ which python3 /usr/bin/python3 Or create an alias to python3 if you find it easier, then which will respond accordingly.
score: 2

http://stackoverflow.com/comment/84139442
comment on: http://stackoverflow.com/q/48571331
type: Comment
has text: Please add some data along with your desired outcome.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84172851
has text: @Uraforclain I know what you're looking for, but I'm telling you that your regex is not correct at the moment. It's including characters between `$` and `_`, which happens to be `$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`. Right now your regex will match `http://;`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48587537

http://stackoverflow.com/comment/84320636
type: QuestionComment
comment on: http://stackoverflow.com/q/48560452
has text: Yeah, I am sure raw elimination like that should probably boil it down for any problem in a few hours. However, didn't work for the import statement removals I tried and then it was easier to use a # UnusedImport exception in pydev after that.
score: 0
type: Comment

http://stackoverflow.com/q/48618586
tagged with: excel
has comment: http://stackoverflow.com/comment/84240993
has comment: http://stackoverflow.com/comment/84233750
type: Question
tagged with: pandas
has title: Add an Excel column from lookup using Python
has comment: http://stackoverflow.com/comment/84265243
has comment: http://stackoverflow.com/comment/84233835
has body: As shown in the picture, I have an Excel file showing some products prices in local currency, and a file showing exchange rates. An extra column is wanted to show their USD values. Here’s how I do: import xlwt, xlrd from xlutils.copy import copy exchange_rate = {"China": 0.16, "Sweden": 0.13, "Russia": 0.015} workbook = xlrd.open_workbook("C:\\Price.xlsx") old_sheet = workbook.sheet_by_index(0) wb = copy(workbook) sheet = wb.get_sheet(0) for row_index in range(1, old_sheet.nrows): Column_B = old_sheet.cell(row_index, 1).value Column_C = old_sheet.cell(row_index, 2).value sheet.write(row_index, 3, Column_C * exchange_rate[Column_B]) sheet.write(0, 3, "Price (USD)") wb.save("C:\\result.xls") It works ok. But I am wondering what would be a better way to do? More importantly, how can I use Pandas to perform the same?
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/84233964
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/48547677
tagged with: python
type: AnsweredQuestion
tagged with: api
score: 1
accepted answer: http://stackoverflow.com/a/48547949
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48547949
favorite count: 0
type: Question
has body: I would like to find all the titles in my shopify store. I found this piece of code which give me the product id. xxx = shopify.Product.find(limit=50, page=1) What I am looking for is the title......... I tried xxx = shopify.Product.title(limit=50, page=1) xxx = shopify.Product.title(limit=50, page=1).title() xxx = shopify.title(limit=50, page=1) xxx = title(limit=50, page=1) What I want to see on the output window. 'This is the title of the product' &lt;- this is what I want to extract What I get now is product(322940174383) &lt;- bad I want the title not product id
tagged with: shopify
downvote count: 0
has title: shopify Title instead of product id. API Python

http://stackoverflow.com/a/61410421
answers question: http://stackoverflow.com/q/48537039
score: 0
has body: Maybe in your case, just running apt-get update before apt-get install python3-tk may be enough. I had this problem while running it inside a Dockerfile. I had in my Dockerfile: RUN apt-get update -y RUN apt-get install python3-tk -y And it was failing with the same message as yours. I realised that if I ran both lines outside of Docker, they worked fine, and that the apt-get update was using cache while running the docker-compose build. When I run docker-compose build --no-cache, it worked.
type: Answer

http://stackoverflow.com/comment/84101765
type: QuestionComment
score: 0
has text: Would not this post be more useful at [SciPy issue tracker](https://github.com/scipy/scipy/issues)? Maybe there is no reason, and your approach should be used instead. Or there is, and some SciPy dev thought about it.
comment on: http://stackoverflow.com/q/48552133
type: Comment

http://stackoverflow.com/comment/83998819
type: Comment
type: AnswerComment
has text: Not directly. If you want to get data after some time after running script without calling it directly, you need to store this state somewhere. Lets say, in file on disk.
comment on: http://stackoverflow.com/a/48502459
score: 0

http://stackoverflow.com/comment/84033866
comment on: http://stackoverflow.com/a/48519221
type: AnswerComment
has text: In my solution, I edited my tree object and finally wrote that updated tree to the file.
score: 0
type: Comment

http://stackoverflow.com/comment/83999956
comment on: http://stackoverflow.com/a/48501318
has text: Thanks. That works, but can I get it to run as a normal run (rather than a unit test) by default when i click the green arrow?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84145036
has text: Got it, thanks. I am slowly, painfully moving into python from years of doing data analysis in Stata, and almost every day I discover a bad habit that programming in the latter has formed in me. For example, in Stata you always work within what amounts to a single data frame, so I hadn't thought about how subsetting would be more efficient.
comment on: http://stackoverflow.com/a/48574059
score: 1
type: Comment
type: AnswerComment

vmware
tags question: http://stackoverflow.com/q/48582628
tag name: vmware
type: Tag

http://stackoverflow.com/a/48600414
has body: I think this may be an instance of the same error you posted about (a similar question). Try this patch: https://github.com/coleifer/peewee/commit/cd07f4e01a1262166d8944736e11d0681fb76214 Also, Peewee model instances are not subscriptable. You should access the element using oldRow.price -- not oldRow[0]. The object returned by a query are model instances unless you explicitly tell peewee to return tuples/dicts/namedtuples. http://docs.peewee-orm.com/en/latest/peewee/api.html#BaseQuery.tuples
type: Answer
accepted answer of: http://stackoverflow.com/q/48598522
answers question: http://stackoverflow.com/q/48598522
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48535282
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84066570
type: Question
tagged with: numpy
tagged with: array-merge
accepted answer: http://stackoverflow.com/a/48535465
tagged with: transpose
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48535465
type: AnsweredQuestion
score: 0
has title: Transpose and merge a tab-separated file by column using Python Pandas
tagged with: pandas
has body: I am new to coding and am currently learning python. Your expertise is greatly appreciated. I have a tab separated data file, tsv.tab, that has 30,000 comma-separated entries in columns two and three but only 1 entry in column one. Each column is separated by a tab. The file looks like so: 57 A,C,G,C ID1,ID2,ID3,ID4 2079 G,C,A,T ID1,ID2,ID3,ID4 5270 C,T,T,G ID1,ID2,ID3,ID4 Please, can you suggest a python method to read in the data, transpose,merge (column 3, i.e. ID1,..) and save the data as a tab or comma-separated file? I will gladly accept pure python, pandas, or numpy suggestions. The output should look like so: 57 2079 5270 ID A G C ID1 C C T ID2 G A T ID3 C T G ID4 or 57,2079,5270,ID A,G,C,ID1 C,C,T,ID2 G,A,T,ID3 C,T,G,ID4 So far, I have tried to use pandas as follows. import pandas as pd df = pd.read_csv('tsv.tab', delimiter= '\t', header=None) df.transpose().to_csv('tsv.csv', header = False, index=False)
answer count: 1

http://stackoverflow.com/a/48551091
score: 1
has body: It looks like you've forgotten to register your ProductAdmin. Change this: admin.site.register(Product) To this: admin.site.register(Product, ProductAdmin)
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48549883
accepted answer of: http://stackoverflow.com/q/48549883

http://stackoverflow.com/a/48562513
accepted answer of: http://stackoverflow.com/q/48562457
has comment: http://stackoverflow.com/comment/84408261
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48562457
score: 0
has body: First create a function that checks if there are any digits in the string: def hasDigits(inputString): return any(char.isdigit() for char in inputString) Then use a loop to keep asking for input until it contains no digits. A sample loop would look like the following: firstname=input("Please enter your first name: ") while hasDigits(firstname): firstname=input("Please re-enter your first name (Without any digits): ") Live Example

http://stackoverflow.com/a/48652855
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: No, you cannot log from both Python and C# at the same time to the same file. The reason for this is that Python's logging (and likely the C# logging too) is not equipped for concurrent logging - even if the log file is not 'locked' by one of them, there is a chance of getting different logs mixed together due to multiple writers. If you do not own the C# dll you're probably out of luck - unless it would allow you to configure the log file/level from a C# program, there is no magic that Python can do to fix it. However, if you control the source and can build a new dll, consider changing the C# class to allow you to pass in a delegate/lambda (assuming this is implemented in PythonNet), which will simply call back into Python's logger function. Example: c# code: public class CoolImportedFeature { private readonly Action&lt;string&gt; LogCallback; public CoolImportedFeature(string inputA, int inputB, Action&lt;string, string&gt; logCallback) { LogCallback = logCallback; // do other constructor stuff } public void SomeMethod() { // do something LogCallback("critical", "An error occurred"); } } python code: def log_callback(log_level, message): getattr(logger, log_level)(message) import CoolImportedFeature feat = CoolImportedFeature("hello", 1, log_callback) feat.SomeMethod() Something like that - there is no magic translation between Python's log levels and C#'s, so you will need to do some translation there (or the getattr reflection I used above).
type: Answer
answers question: http://stackoverflow.com/q/48515473
accepted answer of: http://stackoverflow.com/q/48515473

http://stackoverflow.com/comment/84231590
comment on: http://stackoverflow.com/q/48617163
type: QuestionComment
has text: Are you using virtual environment?
type: Comment
score: 0

http://stackoverflow.com/a/48550644
has body: Another option to get the columns with the given value is value = 791103 l = (df.values==value).any(axis=0) cols = [df.columns[idx] for idx in np.where(l==True)[0]] On my machine this takes 15.9 µs ± 645 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) while Evans's answer takes 628 µs ± 2.01 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48549844
has comment: http://stackoverflow.com/comment/84098430
has comment: http://stackoverflow.com/comment/84097916
has comment: http://stackoverflow.com/comment/84097830
has comment: http://stackoverflow.com/comment/84098145
type: Answer
answers question: http://stackoverflow.com/q/48549844

http://stackoverflow.com/comment/84186227
type: Comment
type: AnswerComment
has text: It is not like **JVM** but once you start using it, you will get to know the importance of it.
score: 0
comment on: http://stackoverflow.com/a/48594464

http://stackoverflow.com/q/48502077
has body: data = ['10', '0', '1915', '387', '1933', '402'] That is the kind of data i have. what i want is to compare data[2] with data[4] and data[3] with data[5] and put inside data[2] the value of the bigger data[2] or data[4] same with data[3] and data[5] so the end result for this example would be : ['10', '0', '1933', '402', '1915', '382']
tagged with: python
has answer: http://stackoverflow.com/a/48502920
has answer: http://stackoverflow.com/a/48502566
has answer: http://stackoverflow.com/a/48502657
accepted answer: http://stackoverflow.com/a/48502566
has answer: http://stackoverflow.com/a/48502449
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/83998720
downvote count: 3
possible better answer: http://stackoverflow.com/a/48502920
has title: How can i manipulate my list?
has answer: http://stackoverflow.com/a/48502596
favorite count: 0
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/83998010
answer count: 5
score: -3

http://stackoverflow.com/comment/84186079
type: QuestionComment
comment on: http://stackoverflow.com/q/48594405
has text: like this {'No club and school cricket in Cape Town as drought worsens ': 'http://www.cricbuzz.com/cricket-news/100135/no-club-school-cricket-cape-town-drought-south-africa', 'Du Plessis ruled out of India ODIs, T20Is with finger injury': 'http://www.cricbuzz.com/cricket-news/100134/south-africa-faf-du-plessis-ruled-out-india-cricket-team-odi-t20i-finger-injury-farhaan-behardien-heinrich-klaasen',}
score: 0
type: Comment

http://stackoverflow.com/comment/84190703
has text: since the display values are not stored in db and get_<field>_display() is an instance function, the only option i can think is annotate a label and assign the choice display value in a for loop.
comment on: http://stackoverflow.com/q/48596370
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48596429
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/1218933
has comment: http://stackoverflow.com/comment/84201830
type: Question
has comment: http://stackoverflow.com/comment/84201955
has title: Badly aligned output when printing an rpy2 stem and leaf plot
has body: I am attempting to plot a stem and leaf plot in python with rpy2, the plot shows in my output but it is not arranged well, as you can see the output has unnecessary breaks in it when some of the output should all be on the same line (see below). How can a remedy this? import pandas as pd import numpy as np from rpy2.robjects import r, pandas2ri, numpy2ri pandas2ri.activate() # Lets me convert pandas data frame to r numpy2ri.activate() # Lets me use numpy arrays in r functions s df = pd.DataFrame(r['iris']) # Convert r's iris data set to a pandas # Set column names attributes = ["sepal_length", "sepal_width", "petal_length", "petal_width", "class"] df.columns = attributes # Get list of sepal widths of versicolor df_versicolor = df.loc[df['class'] == "versicolor"] versicolor_sepal_width = df_versicolor["sepal_width"].tolist() versicolor_sepal_width = np.array(versicolor_sepal_width) # Stem and leaf plot r_stem_and_leaf = r['stem'] stem = r_stem_and_leaf(example) And the output, which is not aligned well The decimal point is 1 digit(s) to the left of the | 20 | 0 22 | 0 0 0 0 0 24 | 0 0 0 0 0 0 0 26 | 0 0 0 0 0 0 0 0 28 | 0 0 0 0 0 0 0 0 0 0 0 0 0 30 | 0 0 0 0 0 0 0 0 0 0 0 32 | 0 0 0 0 34 | 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48603335
tagged with: rpy2
tagged with: python
has answer: http://stackoverflow.com/a/48603335

http://stackoverflow.com/q/48556601
downvote count: 0
tagged with: ssl
tagged with: python
tagged with: python-requests
has title: Python requests throwing SSLEOFError
score: 2
tagged with: tls1.2
favorite count: 0
type: Question
has body: I am trying to connect a Python Requests POC to this tool. I am specifically looking at the test cases for FIA-X509 Ext 1.1. However, the Python POC is throwing the following error: Traceback (most recent call last): File "/home/hussain/Desktop/pythonVenv/python36Venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen chunked=chunked) File "/home/hussain/Desktop/pythonVenv/python36Venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 346, in _make_request self._validate_conn(conn) File "/home/hussain/Desktop/pythonVenv/python36Venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 850, in _validate_conn conn.connect() File "/home/hussain/Desktop/pythonVenv/python36Venv/lib/python3.6/site-packages/urllib3/connection.py", line 326, in connect ssl_context=context) File "/home/hussain/Desktop/pythonVenv/python36Venv/lib/python3.6/site-packages/urllib3/util/ssl_.py", line 329, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "/usr/lib/python3.6/ssl.py", line 407, in wrap_socket _context=self, _session=session) File "/usr/lib/python3.6/ssl.py", line 814, in __init__ self.do_handshake() File "/usr/lib/python3.6/ssl.py", line 1068, in do_handshake self._sslobj.do_handshake() File "/usr/lib/python3.6/ssl.py", line 689, in do_handshake self._sslobj.do_handshake() ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:777) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/hussain/Desktop/pythonVenv/python36Venv/lib/python3.6/site-packages/requests/adapters.py", line 440, in send timeout=timeout File "/home/hussain/Desktop/pythonVenv/python36Venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "/home/hussain/Desktop/pythonVenv/python36Venv/lib/python3.6/site-packages/urllib3/util/retry.py", line 388, in increment raise MaxRetryError(_pool, url, error or …
answer count: 0
upvote count: 2
type: UnansweredQuestion

pca
tag name: pca
tags question: http://stackoverflow.com/q/48502667
type: Tag
tags question: http://stackoverflow.com/q/48620858

http://stackoverflow.com/q/48522952
has body: I have a DataFrame whose columns are MultiIndex. I want to groupby one level of the columns and use apply to perform a transformations. Goal: I want that the DataFrame passed to the function using apply does not have the keys of groupby in the index. From the docs it looks like this is what group_keys is doing, but it seems to have no effect: import numpy as np import pandas as pd data = {'A': pd.DataFrame(np.random.randn(100, 5)), 'B': pd.DataFrame(np.random.randn(100, 5)), 'C': pd.DataFrame(np.random.randn(100, 5))} data = pd.concat(data, axis=1, names=['feat_1', 'feat_2']) def foo(df): print(df.columns) return df.sum(1) My attempt: result = data.groupby(level=['feat_1'], axis=1, group_keys=False).apply(foo) This is what is printed on screen: MultiIndex(levels=[['A', 'B', 'C'], [0, 1, 2, 3, 4]], labels=[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4]], names=['feat_1', 'feat_2']) MultiIndex(levels=[['A', 'B', 'C'], [0, 1, 2, 3, 4]], labels=[[1, 1, 1, 1, 1], [0, 1, 2, 3, 4]], names=['feat_1', 'feat_2']) MultiIndex(levels=[['A', 'B', 'C'], [0, 1, 2, 3, 4]], labels=[[2, 2, 2, 2, 2], [0, 1, 2, 3, 4]], names=['feat_1', 'feat_2']) Desired output of print: I would like the function footo receive a dataframe with only feat_2 as columns, given I am using group_keys=False [0, 1, 2, 3, 4] [0, 1, 2, 3, 4] [0, 1, 2, 3, 4] Am I missing something from the documentation? Or how can I achieve what I want (possibly without modifying the function foo)? Note: I am using pandas 0.20.3 on Python 3
has comment: http://stackoverflow.com/comment/84042129
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48525736
tagged with: python
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/84043922
has comment: http://stackoverflow.com/comment/84042788
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas
answer count: 1
has title: pandas groupby on multiindex levels: group_keys
favorite count: 0
type: Question

http://stackoverflow.com/a/48554503
type: AcceptedAnswer
upvote count: 1
has body: Here is a solution that autodetects the required output size: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; # create ragged list &gt;&gt;&gt; n = 4 &gt;&gt;&gt; ragged = list(map(np.full, np.random.randint(1, 6, (n, 2)), 10**np.arange(n))) &gt;&gt;&gt; &gt;&gt;&gt; ragged [array([[1, 1, 1]]), array([[10, 10], [10, 10], [10, 10]]), array([[100], [100], [100]]), array([[1000, 1000, 1000, 1000], [1000, 1000, 1000, 1000]])] &gt;&gt;&gt; # find maximum size in each dimension &gt;&gt;&gt; maxsh = *map(max, zip(*map(np.shape, ragged))), # allocate result &gt;&gt;&gt; result = np.zeros(maxsh, dtype=ragged[0].dtype) # and add &gt;&gt;&gt; for r in ragged: ... result[(*map(slice, r.shape),)] += r ... &gt;&gt;&gt; result array([[1111, 1011, 1001, 1000], [1110, 1010, 1000, 1000], [ 110, 10, 0, 0]])
answers question: http://stackoverflow.com/q/48552101
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48552101
score: 1

http://stackoverflow.com/q/48553991
downvote count: 2
tagged with: formatting
has body: I am reading a csv dataset and returning the X and Y coordinates to separate lists. I'm removing the XY Coordinates were the X-Coordinate is less than 5. The csv is structured like this: Frame Time Player 1_X Player 1_Y Player 2_X Player 2_Y Player 3_X Player 3_Y 2920 15:31.0 67.30126517 23.99694962 3.753634891 -2.13857999 69.90505068 -2.504794226 2921 15:31.1 67.28604137 24.20629904 4.122542578 -1.939556384 69.83347832 -2.377951675 2922 15:31.2 67.27140091 24.41644649 4.500764877 -1.724636234 69.7662355 -2.257606667 2923 15:31.3 67.26373215 24.61751047 4.887649337 -1.501664655 69.72997973 -2.135141953 2924 15:31.4 67.28158751 24.80200421 5.294844117 -1.275928937 69.72595034 -2.013856015 2925 15:31.5 67.32005993 24.97498635 5.721823825 -1.042487504 69.73204207 -1.907299936 2926 15:31.6 67.36659395 25.14388582 6.155413991 -0.789898029 69.72947318 -1.811930399 2927 15:31.7 67.40717007 25.31477304 6.58302186 -0.513340546 69.71798806 -1.71190236 2928 15:31.8 67.42824027 25.48791173 7.001268674 -0.212791949 69.69067463 -1.61337704 2929 15:31.9 67.44179872 25.65540719 7.437058638 0.112079642 69.64537185 -1.526329851 2930 15:32.0 67.46336705 25.82181033 7.90386401 0.447834398 69.6061351 -1.441474747 I use the code below to remove all player's XY values were the X value is less than 5. So, using this code the XY data for Player 2 would be removed up to frame 2923. with open('Wide_Single_timestamp2.csv') as csvfile : readCSV = csv.reader(csvfile, delimiter=',') n=0 for row in readCSV : if n == 0 : n+=1 continue x_data = [] y_data = [] for (x,y) in [(2,3),(4,5),(6,7)]: xcoord = float(row[x]) if xcoord &gt;= 5: x_data.append(xcoord) y_data.append(float(row[y])) visuals[1].append(x_data) visuals[0].append(y_data) This works in the fact that the resulting data is removed from the X-Cordinates that are less than 5. However, I get a strange formatting result. Columns of empty data (those that were &lt;5) are now filled with data from the right. Ex. Player 2 should be empty but it …
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48558944
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/48554105
tagged with: http://stackoverflow.com/tag/csv
has title: Formatting error when removing values from a csv file and returning to a list
tagged with: python
has answer: http://stackoverflow.com/a/48554230
tagged with: list
answer count: 3
upvote count: 0

http://stackoverflow.com/q/48562582
favorite count: 0
has comment: http://stackoverflow.com/comment/84120657
type: Question
upvote count: 2
tagged with: testing
answer count: 0
has comment: http://stackoverflow.com/comment/84121019
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84120768
score: 2
has comment: http://stackoverflow.com/comment/84121066
has comment: http://stackoverflow.com/comment/84120664
downvote count: 0
has comment: http://stackoverflow.com/comment/84121241
has comment: http://stackoverflow.com/comment/84121212
has title: Django test - models.DoesNotExist: matching query does not exist
has comment: http://stackoverflow.com/comment/84120810
has comment: http://stackoverflow.com/comment/84120874
has comment: http://stackoverflow.com/comment/84121000
has body: I have two test files, test1.py and test2.py. Individually they run fine, but when I try to run them using 'django manage.py test' I get the following error: post.models.DoesNotExist: Post matching query does not exist. One more thing I notice is that, whichever file runs first will work well while the other throws this error (tested this by renaming files). I am using django.test.TestCase. This is the relevant code - test1.py: def setUpTestData(cls): Post.objects.create(...) Post.objects.get(id=1) #Works fine since this file runs first test2.py: def setUpTestData(cls): Post.objects.create(...) Post.objects.get(id=1) #Throws above error I am new to testing in django so I think I'm missing something basic here.

http://stackoverflow.com/q/48551297
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/48551355
has title: combining multiple columns pandas groupby
has answer: http://stackoverflow.com/a/48551355
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
has body: suppose I have a stock, and I have a minute-by-minte dataframe of prices and volumes: close high low open symbol timestamp tradingDay volume 0 116.02 116.02 116.02 116.02 AAPL 2017-01-03 04:03:00-05:00 2017-01-03 200 1 116.14 116.14 116.14 116.14 AAPL 2017-01-03 04:06:00-05:00 2017-01-03 100 2 116.15 116.24 116.12 116.14 AAPL 2017-01-03 04:07:00-05:00 2017-01-03 1370 3 116.13 116.15 116.13 116.15 AAPL 2017-01-03 04:08:00-05:00 2017-01-03 1100 4 116.15 116.15 116.15 116.15 AAPL 2017-01-03 04:09:00-05:00 2017-01-03 100 (sorry about the formatting) I want to combine these into "vwap" (volume weighed average price), and this seems easy: zoo= foo.groupby('tradingDay').agg( lambda x: x['close'].dot(x['volume'])/np.sum(x.volume)) But the resulting object has as many columns as the original dataframe (each column being the same and equal to the desired vwap price). Of course, one can then select a random column, but that seems morally impure and memory-wasteful. I am presumably missing something very obvious, but what?
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/a/48626575
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84258483
answers question: http://stackoverflow.com/q/48623544
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/84265864
has body: An answer to your first question is simply no if you are doing in normal way, but yes if you want it to be. No because the target function cannot communicate back to spawning thread using a return. One way to do it is to use a queue and wrapper functions as following: from threading import Thread from Queue import Queue def p_get_reading(newport,N,interval,return_dict): reading = newport.get_reading(N,interval,return_dict) return_dict.update({'power_meter': reading}) return return_dict def p_capture(camera,N,return_dict): img = camera.capture(N) return_dict.update({'image': img}) return return_dict def wrapper1(func, arg1, arg2, queue): queue.put(func(arg1, arg2)) def wrapper2(func, arg1, arg2, arg3, queue): queue.put(func(arg1, arg2, arg3)) q = Queue() Thread(target=wrapper1, args=(p_capture, camera, 10 , q)).start() Thread(target=wrapper2, args=(p_get_reading, newport, 100, 1, q)).start() Now q holds the updated and returned dict from p_capture() and p_get_reading().

http://stackoverflow.com/comment/84006629
comment on: http://stackoverflow.com/q/48506031
has text: Could you please detail about declaring relation explicitly with above example, that would be help me understand better
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/48539823
has body: Use replace or mask, which by default change value to NaNs by condition: df = df.replace('NULL', np.nan) For compare mixed data use values or cast to string: df = df.mask(df.values == 'NULL') df = df.mask(df.astype(str) == 'NULL')
accepted answer of: http://stackoverflow.com/q/48539785
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48539785
has comment: http://stackoverflow.com/comment/84074745
score: 3
has comment: http://stackoverflow.com/comment/84074807
has comment: http://stackoverflow.com/comment/84074806
type: Answer
has comment: http://stackoverflow.com/comment/84074781

http://stackoverflow.com/comment/84023247
has text: KK I'm running it through PythonAnywhere
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48513404

http://stackoverflow.com/comment/84126719
type: QuestionComment
score: 3
has text: `for cell in grid` -- you are using the name `cell` for something else. (This is partly the reason you should capitalise class names, e.g. `Cell`)
comment on: http://stackoverflow.com/q/48565426
type: Comment

http://stackoverflow.com/comment/109016870
type: QuestionComment
comment on: http://stackoverflow.com/q/48511484
has text: This smells like a bug. astype('int16') or any explicit type always crashes so I always use astype('object'). NaN support should be out of the box. filling it with "some value" is the wrong answer as nulls are a fact.
score: 7
type: Comment

http://stackoverflow.com/q/48568858
tagged with: http://stackoverflow.com/tag/xml
score: 0
has answer: http://stackoverflow.com/a/48569151
type: UnansweredQuestion
has body: I have an xml file that has multiple layers of data in. <?xml version="1.0" encoding="UTF-8"?> <DevLog State="PowerOn"/> <ComponentPrivateDataLog> 1 1 0301 </ComponentPrivateDataLog> <ComponentPrivateDataLog> 1 1 0401 </ComponentPrivateDataLog> <DevLog State="StandByIn"/> <EndOfFileLog /> In this, each Log tag is a separate entity having its own time attribute and a child node. I am using minidom to parse the data. The following is the code: from xml.dom import minidom xmldoc=minidom.parse("testxml.xml") dl=xmldoc.getElementsByTagName("DeviceLog") for d in dl: dId=d.attributes["DevID"] dId=dId.value dod=d.attributes["DocDate"] dod=dod.value bsld=d.attributes["BSLogDate"] bsld=bsld.value log=xmldoc.getElementsByTagName("Log") for l in log: logtime = l.attributes["LogTime"] logtime = logtime.value devLog = l.getElementsByTagName("DevLog") for dl in devLog: devEvnt = dl.attributes["State"] devEvnt = devEvnt.value print dId,dod,bsld,logtime, devEvnt The above code prints the time and state of the StandBy (last entry) and not the first PowerOn state. I tried indexing log=xmldoc.getElementsByTagName("Log")[0] and similarly for logtime. But didn't work. How can i parse the logs so that I get each log with time in a separate line?
answer count: 1
type: Question
has title: Python parse nested xml
tagged with: python

http://stackoverflow.com/a/48589099
accepted answer of: http://stackoverflow.com/q/48573631
has body: The API recently deprecated TLS 1.0 support which is causing the issue. I am now working on upgrading python to use TLS1.2 which is also very challenging as Mac default install of Python only supports TLS 1.0.
answers question: http://stackoverflow.com/q/48573631
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/q/48593891
has comment: http://stackoverflow.com/comment/84184981
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84185025
tagged with: python
linked to: http://stackoverflow.com/q/4915361
has answer: http://stackoverflow.com/a/48593914
score: 0
has title: "Not Equal" != into Python 3 not working
answer count: 2
duplicate of: http://stackoverflow.com/q/4915361
has comment: http://stackoverflow.com/comment/84185007
has body: I'm trying to switch a code from Python 2.7.10 to Python 3, and some things aren't working. I just recently was introduced to Python. choice = 2 while choice != 1 and choice != 0: choice = input("Hello, no.") if choice != 1 and choice != 0: print("Not a good code.") How do I change the "!=" into something Python 3 will understand? When I type in 1 or 0, it gives me my "hello, no" invalid print.
linked to: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/84185370
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48593921

http://stackoverflow.com/comment/84237613
type: QuestionComment
has text: None instead of 'none" does not change the colormap problem.
score: 0
comment on: http://stackoverflow.com/q/48620370
type: Comment

http://stackoverflow.com/comment/84292829
score: 0
type: Comment
type: AnswerComment
has text: It'd be a link-only answer, and I don't have the time at the moment to flesh it out. It's also not clear how to get the Gmail-ID and change it to a link; they're different encodings.
comment on: http://stackoverflow.com/a/48629145

http://stackoverflow.com/comment/84271392
comment on: http://stackoverflow.com/a/48637222
type: Comment
type: AnswerComment
has text: @sam So why don’t you [upvote](https://stackoverflow.com/help/privileges/vote-up) it?
score: 0

http://stackoverflow.com/comment/84017734
type: AnswerComment
comment on: http://stackoverflow.com/a/48511427
type: Comment
has text: On my Windows machine this fails in the debug statement `print "A {}".format(X.shape)`
score: 0

http://stackoverflow.com/comment/84059137
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48530970
has text: They are not points, they are **lines**. That is what you aren't understanding. Anyway, it seems like what you really want is 11 box blots or violin plots or something. 176501 lines is just not going to be efficient in matplotlib
type: Comment

http://stackoverflow.com/comment/84044999
score: 0
comment on: http://stackoverflow.com/a/48523779
type: Comment
has text: @YepramYeransian Fixed.
type: AnswerComment

business-logic-layer
tags question: http://stackoverflow.com/q/48516893
tag name: business-logic-layer
type: Tag

http://stackoverflow.com/comment/129572520
type: AnswerComment
score: 0
type: Comment
has text: Ok, but this : "[...]make more requests even you reached that limit because you didn't reached total_time and total_cputime limit yet." it's not always true then
comment on: http://stackoverflow.com/a/70696998

http://stackoverflow.com/comment/83985606
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48496335
has text: Question says: *move1 contains images named as frame1.jpg , frame2.jpg , frame3.jpg...* !

http://stackoverflow.com/q/48542084
has body: I have wrriten a simple application using flask. Its main objective is to implement CLD2 (language detector) using post and get methods. It is working well for English but for any other language such Urdu, Arabic. It gives invalid results Following is the corresponding script # http://127.0.0.1:5000/cld2?text="Your input text string" # OUTPUT ( It gives output as we done in CC) #"585&amp;URDU-99-1155" from flask import Flask,abort,jsonify,request from flask_restful import Resource, Api, reqparse import cld2 from bs4 import BeautiflSoup import sys import urllib2, urllib import re reload(sys) sys.setdefaultencoding('utf8') app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def cld2_states(self, txt): txt = txt.encode("utf8") isReliable, textBytesFound, details = cld2.detect(txt) outstr = str(textBytesFound) for item in details: # Iterate 3 languages if item[0] != "Unknown": outstr += '&amp;' + item[0] + '-' + str(item[2]) + '-' + str(int(item[3])) return outstr def get(self): parser = reqparse.RequestParser() parser.add_argument('text', type=str) parser.add_argument('url', type=str) _dict = dict(parser.parse_args()) if _dict["text"] is not None: value = _dict["text"] print type(value) return self.cld2_states(value) return None def post(self): data = request.get_json(force=True) # print data predict_request = [data['content']][1] out = self.cld2_states(predict_request) return jsonify(score=out) api.add_resource(HelloWorld, '/cld2') if __name__ == '__main__': app.run(debug=True, port=6161, host='0.0.0.0') If I give a query via get method, it give correct results but for same query in post method, it return just a number. But if text is in English then post also give correct result. My client is a simple Java application then iterate over files and find their language one by one.
tagged with: python
score: -1
tagged with: flask
has title: Flask server could not handle non ascii characters
has answer: http://stackoverflow.com/a/48542981
linked to: http://stackoverflow.com/q/9942594
answer count: 1
tagged with: flask-restful
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84195133
comment on: http://stackoverflow.com/q/48599299
score: 1
type: QuestionComment
has text: The assignment operator `=` will not change existing objects. It only binds a name (on the left) to an object (on the right). The names `a` and `lst` just end up pointing to different objects instead of the same object
type: Comment

http://stackoverflow.com/comment/84064760
type: AnswerComment
comment on: http://stackoverflow.com/a/48534631
has text: Sorry, I made an edit to this. I am just wanting it to completely reject the potential identifier. Right now it is matching parts of it.
type: Comment
score: 0

http://stackoverflow.com/a/48504881
answers question: http://stackoverflow.com/q/48503761
has comment: http://stackoverflow.com/comment/84004894
type: Answer
has comment: http://stackoverflow.com/comment/84004410
has comment: http://stackoverflow.com/comment/84004673
has comment: http://stackoverflow.com/comment/84004633
has comment: http://stackoverflow.com/comment/84004829
has comment: http://stackoverflow.com/comment/84006299
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84003914
has comment: http://stackoverflow.com/comment/84006152
has comment: http://stackoverflow.com/comment/84004602
has body: What you could've done to find this error: print(type(Energy[j]), type(num_a), type(E_a)) Right before you set Energy[j]. You'll find it out isn't going to work: &lt;class 'numpy.float64'&gt; &lt;class 'float'&gt; &lt;class 'numpy.ndarray'&gt; E_a is a numpy array. You can't assign an array to a value that has to resolve to a float. I'm not familiar with the algorithm, but perhaps you wanted to use the following instead? Energy[j]= num_a * E_a[i][j] You'll find the same thing goes wrong for setting Magnetization[j] a little later on. Same problem, same fix. This solves the problem on my machine, running Python 3.5.2. The code still has issues though. For example, num_b is referenced twice but never created. EDIT: renaming num_2 to num_b and M1 to M_a, there are a couple more errors. Basically your function could be looking like this: for i in range(len(Temp)): E_a=M_a=0 E_b=M_b=0 Q=startspin(num) init_Temp_a=1/Temp[i] init_Temp_b=init_Temp_a**2 for j in range(steps_monte): montestep(Q,init_Temp_a) Energy_calc=Energy[Q] Mag_calc=Magnetization[Q] E_a=E_a+(Energy_calc) M_a=M_a+(Mag_calc) M_b=M_b+(Mag_calc**2) E_b=E_b+(Energy_calc**2) print(E_a[i][j]) Energy[j]= num_a * E_a[i][j] Magnetization[j]=num_a*M_a[i][j] SpecificHeat[j]=(num_a*E_b[i][j]*(E_a[i][j]**2))*init_Temp_b Susceptibility[j]=(num_a*M_b[i][j]*(M_a[i][j]**2))*init_Temp_a for _ in range(steps_equil): montestep(Q,init_Temp_a) But that shows something much more problematic. Take a look at the following: for i in range(len(Temp)): for j in range(steps_monte): steps_monte is set to 1024, the length of Temps appears to be non-constant (but above 250). So this will be iterating over a lot of values, right? Well, not really. Because the arrays it's iterating over aren't that big. So the iteration will go out of bounds. The array stops earlier than the iteration. Which makes me wonder whether the algorithm implementation isn't flawed in a much bigger way. Note: your code uses j before i. I switched that around, whic…
has comment: http://stackoverflow.com/comment/84004506
has comment: http://stackoverflow.com/comment/84005253

http://stackoverflow.com/a/48539441
upvote count: 2
type: Answer
score: 2
downvote count: 0
has body: As per numpy.zeros documentation, the first argument is a sequence or int representing the shape of the array. If you look closely the nested square brackets differ in line with the shapes you've built. This example might make it clearer: np.zeros((2, 3, 4)) array([[[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], [[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]])
answers question: http://stackoverflow.com/q/48539344

http://stackoverflow.com/a/74345583
type: Answer
score: 0
has body: You could also use im = tf.expand_dims(input, axis=0) to insert a dimension of 1 into the tensor's shape. im will be a rank 4 tensor. This way you do not have to specify the dimensions of the image.
answers question: http://stackoverflow.com/q/48509419

http://stackoverflow.com/a/48523617
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48522128
has body: When selecting the QModelIndex with the method selectionModel().selectedRows() this returns the indexes with respect to the model that was established to the view, in your case the SortedModel, but if you want to obtain an item you must have a QModelIndex that belong to AssetModel, that is, to the source model, for this you must use mapToSource of the proxy model: def import_assets(self): selection = self.ui_asset_list.selectionModel().selectedRows() selection_x = [self.ui_asset_list.model().mapToSource(index) for index in selection] assets = self.ui_asset_list.model().sourceModel().getSelectedItems(selection_x) for x in assets: print(x.name)
answers question: http://stackoverflow.com/q/48522128
type: Answer

http://stackoverflow.com/a/48563539
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48562123
has body: First convert columns to datetimes by to_datetime, then reindex for NaNs for missing days and last interpolate: df.columns = pd.to_datetime(df.columns, format='%Y%m') #by first and last values of columns rng = pd.date_range(df.columns[0], df.columns[-1]) #alternatively min and max of columns #rng = pd.date_range(df.columns.min(), df.columns.max()) df = df.reindex(rng, axis=1).interpolate(axis=1) Verify solution: a = (0.793101-0.747711)/31 print (0.747711 + a) print (0.747711 + a*2) print (0.747711 + a*3) 0.7491751935483871 0.7506393870967742 0.7521035806451613 print (df) 2013-01-01 2013-01-02 2013-01-03 2013-01-04 2013-01-05 2013-01-06 \ a 0.747711 0.749175 0.750639 0.752104 0.753568 0.755032 b 0.776537 0.775995 0.775454 0.774912 0.774370 0.773829 c 0.801699 0.803181 0.804664 0.806146 0.807629 0.809111 d 0.797942 0.794392 0.790842 0.787293 0.783743 0.780193 e 0.777472 0.778188 0.778905 0.779621 0.780337 0.781053 f 0.780933 0.779960 0.778987 0.778014 0.777042 0.776069 g 2.071699 2.077829 2.083960 2.090090 2.096220 2.102351 2013-01-07 2013-01-08 2013-01-09 2013-01-10 ... 2017-09-22 \ a 0.756496 0.757960 0.759425 0.760889 ... 0.814214 b 0.773287 0.772745 0.772204 0.771662 ... 0.762876 c 0.810594 0.812076 0.813559 0.815041 ... 0.769847 d 0.776643 0.773094 0.769544 0.765994 ... 0.786643 e 0.781770 0.782486 0.783202 0.783918 ... 0.795591 f 0.775096 0.774123 0.773150 0.772177 ... 0.778847 g 2.108481 2.114611 2.120742 2.126872 ... 2.036774 2017-09-23 2017-09-24 2017-09-25 2017-09-26 2017-09-27 2017-09-28 \ a 0.814026 0.813838 0.813650 0.813462 0.813274 0.813086 b 0.763132 0.763388 0.763644 0.763900 0.764156 0.764413 c 0.769147 0.768448 0.767748 0.767049 0.766349 0.765650 d 0.785060 0.783476 0.781893 0.780310 0.778727 0.777144 e 0.795165 0.794740 0.794314 0.793888 0.793462 0.793036 f 0.778276 0.777705 0.777133 0.776562 0.775990 0.775419 g 2.043678 2.050583 2.057487 2.064392 2.071296 2.078201 2017-09-29 2017-09-30 2017-10-01 a 0.812898 0.812710 0.812522 b 0.764669 0.764925 0.…
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/48562123

http://stackoverflow.com/comment/84188819
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48595074
type: Comment
has text: I posted part of the trace. I did not modify the code, as it is the same. This works without the .toDF() lines = sqlContext.read.parquet("hdfs:////data/lad_01/") lines.registerTempTable("test_data") resultsDF = sqlContext.sql("select * from test_data") resultsDF.take(10)

http://stackoverflow.com/q/48572764
type: Question
has answer: http://stackoverflow.com/a/48573068
tagged with: python
has comment: http://stackoverflow.com/comment/84142411
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84142364
linked to: http://stackoverflow.com/q/978061
answer count: 1
tagged with: python-requests
has body: We have a web service(GET) that takes a complex JSON with lists, How do I set it up so that requests sends the generated data as json and not through query string? Here's the simplified version of the current code and I keep on getting error 403: def build_get_request_params(table_name): data = {'table_data': table_name} return data def get_table_data_prefixed(table_name): built = build_get_request_params(table_name) response = requests.get("https://www.endpoint", data=json.dump(built)) print(response.json())
has title: Sending a JSON data through HTTP Get using requests
accepted answer: http://stackoverflow.com/a/48573068
has comment: http://stackoverflow.com/comment/84142436

http://stackoverflow.com/q/48612092
tagged with: orm
tagged with: sqlalchemy
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48617497
accepted answer: http://stackoverflow.com/a/48617497
tagged with: python
has body: I have two objects, User and Room both of which inherit from a Base Object. class BaseModel: __metaclass__ = Serializable created = Column(DateTime, default=func.now()) modified = Column(DateTime, default=func.now(), onupdate=func.now()) @declared_attr def __tablename__(self): return self.__name__.lower() Base = declarative_base(cls=BaseModel) This is my User model with the many-to-many association with Room declared on top. association_table = Table('users_rooms', Base.metadata, Column('user_id', Integer, ForeignKey('user.id')), Column('room_id', Integer, ForeignKey('room.id')) ) class User(Base): __table_args__ = {'extend_existing': True} id = Column(Integer, primary_key=True) mobile = Column(String(20), index=True, unique=True) rooms = relationship("Room", secondary=association_table, back_populates="users") And this is the Room model. association_table = Table('users_rooms', Base.metadata, Column('user_id', Integer, ForeignKey('user.id')), Column('room_id', Integer, ForeignKey('room.id')) ) class Room(Base): __table_args__ = {'extend_existing': True} id = Column(Integer, primary_key=True) room_type = Column(String(50), default=RoomType.PRIVATE) hex_code = Column(String(100), unique=True) users = relationship("User", secondary=association_table, back_populates="rooms") When I try to compile this, I get the following error. sqlalchemy.exc.InvalidRequestError: Table 'users_rooms' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
has title: Can't map Many-to-Many relationship in SQLAlchemy
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/90760212
score: 0
comment on: http://stackoverflow.com/q/48560171
has text: did you ever found a solution?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84067965
has text: What do you want to do? If you just want to read and write to another file, read it with "rb" `with open('h.docx', 'rb') as f:` and write it with `wb`
comment on: http://stackoverflow.com/q/48536461
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84314316
has text: @ShengbaoShuiMSFT Thank you very much! Now it works!
comment on: http://stackoverflow.com/a/48634744
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48584254
has comment: http://stackoverflow.com/comment/84166240
type: Question
has comment: http://stackoverflow.com/comment/84166682
type: UnansweredQuestion
tagged with: python
tagged with: concurrency
has body: I have an ExtendedUser model like this, that just points to Django's User model: class ExtendedUser(models.Model): user = models.OneToOneField(User) When a request comes in, I want to get or create an User and its related ExtendedUser if the user that I'm looking for doesn't exist. I have this code : def get_or_create_user(username): with transaction.atomic(): user, created = User.objects.get_or_create( username=username, defaults={ 'first_name': "BLABLA", }, ) if created: extended_user = ExtendedUser() extended_user.user = user extended_user.save() return user I wrap it inside a transaction, to be sure I don't create an User but not its associated ExtendedUser. But, when two requests come in simultaneously that will create the same user, this fails from time to time with an IntegrityError, for both requests. So I end up with no user being created.. IntegrityError: (1062, "Duplicate entry 'BLABLABLA' for key 'username'") Note that I use MySQL, but I force READ COMMITTED isolation level. What do I do wrong ? How should I handle this ? The models need to stay as they are.
has comment: http://stackoverflow.com/comment/84167522
has answer: http://stackoverflow.com/a/48584741
has comment: http://stackoverflow.com/comment/84167579
has title: Django get_or_create race condition when creating related objects
has comment: http://stackoverflow.com/comment/84165902
has comment: http://stackoverflow.com/comment/84166543
downvote count: 0
tagged with: mysql
upvote count: 1
tagged with: django
score: 1
has comment: http://stackoverflow.com/comment/84165731
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48596350
score: 0
type: Answer
has body: l = [] for row in dataframe.itertuples(): for col in dataframe.columns: l.append((row.Index,col, dataframe.loc[row.Index,col])) you can iterate over each row and then each column to append the resulting tuple to a list. On my test this was faster than the previous answer, probably depending on the number of rows and columns you have. %%timeit l = [] for row in dataframe.itertuples(): for col in dataframe.columns: l.append((row.Index,col, dataframe.loc[row.Index,col])) 594 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) L = dataframe.stack().to_frame('a').set_index('a', append=True).index.tolist() L = [tuple(x) for x in dataframe.stack().reset_index().values] 2.25 ms ± 12.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) as requested, here the timings for 1000 rows: matrix = scipy.sparse.rand(1000, 3, density=0.2, format='lil') array = numpy.array(matrix.toarray()) index = list(range(1000)) dataframe= pd.DataFrame(data=array, index=index) %%timeit l = [] for row in dataframe.itertuples(): for col in dataframe.columns: l.append((row.Index,col, dataframe.loc[row.Index,col])) 17 ms ± 38 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %%timeit -n 100 L = dataframe.stack().to_frame('a').set_index('a', append=True).index.tolist() L = [tuple(x) for x in dataframe.stack().reset_index().values] 5.08 ms ± 16.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
answers question: http://stackoverflow.com/q/48596061
has comment: http://stackoverflow.com/comment/84189900
has comment: http://stackoverflow.com/comment/84189624

http://stackoverflow.com/q/48547734
accepted answer: http://stackoverflow.com/a/48548634
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48548634
has title: Python: Modifying class variables outside module has no effect
tagged with: python
has comment: http://stackoverflow.com/comment/84091435
tagged with: module
has comment: http://stackoverflow.com/comment/84092349
tagged with: reference
type: Question
has comment: http://stackoverflow.com/comment/84091965
score: 0
tagged with: types
answer count: 1
has comment: http://stackoverflow.com/comment/84092549
has body: I am trying to create a system where I can mutate the values of A as easily as possible. When I import A into various other modules and modify the fields of A they seem to remain changed in the foreign module but are unchanged in A's native module. # module name a.py import b class A: x = 0 @classmethod def call_mutate_A_from_B(cls): b_object = b.B() b_object.mutate_A() # change does not seem to stay in effect upon # return print(cls.x) # prints 0 def main(): A.call_mutate_A_from_B() if __name__ == '__main__': main() # module name b.py from a import A class B: # in a different module def mutate_A(): A.x = 2 Is this the expected behaviour? I don't think it is. Should I create an object representation of A not treat is as a static class?
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: class

http://stackoverflow.com/q/48489893
has body: I have a dataframe in which one column is all hyperlinks (eg, http://example.com). I have managed to make these links render as html inside Jupyter Notebook: from IPython.display import HTML df["URL"] = df["URL"].apply(lambda x: '&lt;a href="{}"&gt;{}&lt;/a&gt;'.format(x,x)) df = HTML(df.to_html(escape=False)) df But I cannot get these links written to an Excel (or ODS) spreadsheet as html rather than text. In the above, df become a IPython.core.display.HTML object, without pandas's to_excel(). When I convert the individual cells to IPython.core.display.HTML with lambda x: HTML('&lt;a href="{}"&gt;{}&lt;/a&gt;'.format(x,x)) and then call to_excel on the DataFrame, I get the Exception: Unexpected data type &lt;class 'IPython.core.display.HTML'&gt;
downvote count: 0
has title: Ouputting (clickable) hyperlinks to a spreadsheet with Python pandas.to_excel()
upvote count: 1
tagged with: python
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/48489931
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/48593644
tagged with: vba
tagged with: excel
type: Question
has body: I have a python script that uses Openpyxl to load worbook.xlsm for data entry and print chart by using Matplotlib. I convert the script to exe using Py2exe. It's weird when I double-click the program, it runs perfectly. Call that program on VBA raise the directory of workbook.xlsm is not found. Both program file and workbook are in the same directory. Can anyone explain to me how I can figure it out? Update: Please see my code as attached.myscript.py
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has title: Double Click Python EXE run properly but Call from VBA raise Error No.2 No such directory file
has comment: http://stackoverflow.com/comment/84186229
score: 0
has comment: http://stackoverflow.com/comment/84184586
has comment: http://stackoverflow.com/comment/84186767
answer count: 0
has comment: http://stackoverflow.com/comment/84185270

http://stackoverflow.com/comment/84043044
type: QuestionComment
has text: you may not need an extension, see https://stackoverflow.com/questions/31684024/burp-extension-add-header-to-response
score: 0
comment on: http://stackoverflow.com/q/48523890
type: Comment

http://stackoverflow.com/comment/87898576
type: QuestionComment
comment on: http://stackoverflow.com/q/48578906
score: 0
has text: @Quba, still haven't figured out this issue. Can you give me some guidance on how to accomplish this?
type: Comment

http://stackoverflow.com/comment/84191010
score: 0
type: AnswerComment
has text: also, user commented earlier that `itertools.groupby` was not permitted! i have submitted an edit to include `countArray`.
type: Comment
comment on: http://stackoverflow.com/a/48597015

http://stackoverflow.com/q/48612184
has body: It was working fine until I messed up my PATH enviroment variable. I did the following thing: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" echo 'export PATH="/usr/local/bin:$PATH"' &gt;&gt; ~/.bashrc source ~/.bashrc echo 'export PATH="/usr/local/opt/python/libexec/bin:$PATH"' &gt;&gt; ~/.bashrc source ~/.bashrc This pretty much installed homebrew python 3 and created entire havoc ... then now celery only listens to these. I just completely uninstalled python 3. Now I'm currently facing the following error: -bash: /usr/local/bin/celery: /usr/local/opt/python3/bin/python3.6: bad interpreter: No such file or directory When I do which python it gives me this directory: /usr/bin/python When I run python it's running 2.7 as expected. However celery command seems to be throwing me that error. How do I revert back to my default state?
has title: Use celery with python 2.7
tagged with: python
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50830809
tagged with: celery
score: 0
has answer: http://stackoverflow.com/a/48633901
tagged with: path

http://stackoverflow.com/comment/84083198
comment on: http://stackoverflow.com/a/48541016
type: AnswerComment
score: 0
has text: Would just like to point out one thing regarding template - at least in my case, it did not work with 3 {} for variable placeholder, 2 {} did the trick.
type: Comment

http://stackoverflow.com/a/48513087
answers question: http://stackoverflow.com/q/48513073
has body: Here's the code: import numpy as np import pandas as pd import matplotlib.pyplot as plt earnings = pd.read_csv('earnings.csv', sep=';') tips = pd.read_csv('tips.csv', sep=';') print(earnings) print(tips) earnings['index'] = earnings.index height, width = earnings.shape cols = list(earnings.columns.values) colors = ['r', 'g', 'b'] # Thanks for # https://stackoverflow.com/questions/43812911/adding-second-legend-to-scatter-plot plt.rcParams["figure.subplot.right"] = 0.8 plt.figure(figsize=(8,4)) # get axis ax = plt.gca() # plot each column, each row will be in a different X coordinate, creating a category for x in range(1, width-1): earnings.plot.scatter(x='index', y=cols[x], label=None, xticks=earnings.index, c=colors[x-1], s=tips[cols[x]].multiply(10), linewidth=0, ax=ax) # This second 'dummy' plot is to create the legend. If we use the one above, # [enter image description here][1]the circles in the legend might have different sizes for x in range(1,width-1): earnings.loc[:1].plot.scatter([], [], label=cols[x], c=colors[x-1], s=30, linewidth=0, ax=ax) # Label the X ticks with the categories' names ax.set_xticklabels(earnings.loc[:,'DayOfWeek']) ax.set_ylabel("Total Earnings") ax.set_xlabel("Day of Week") leg = plt.legend(title="Location", loc=(1.03,0)) ax.add_artist(leg) # Create a second legent for the points' scale. h = [plt.plot([],[], color="gray", marker="o", ms=i, ls="")[0] for i in range(1,10, 2)] plt.legend(handles=h, labels=range(1,10, 2), loc=(1.03,0.5), title="Avg. Tip") plt.show() # See also: # https://jakevdp.github.io/PythonDataScienceHandbook/04.06-customizing-legends.html Resulting figure
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84021955
downvote count: 0
has comment: http://stackoverflow.com/comment/84020996
type: Answer
accepted answer of: http://stackoverflow.com/q/48513073
has comment: http://stackoverflow.com/comment/84020957
score: 2

http://stackoverflow.com/q/48547983
answer count: 1
has comment: http://stackoverflow.com/comment/84091875
has title: How to get kNN in python (visual studio)? I thought it was part of sklearn?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48548046
score: -2
has comment: http://stackoverflow.com/comment/84091883
tagged with: python
has body: I tried to import it from numpy import * import kNN from matplotlib import * from matplotlib.pyplot import * from os import * but kNN is highlighted with an error: ImportError: No module named kNN
tagged with: visual-studio
tagged with: knn
upvote count: 0
downvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/84124658
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48564368
has text: Without a clear use-case *why* you want to use NumPy arrays, instead of the Dataframe and Series/columns, I find this an unclear question. If you want to learn about NumPy arrays themselves, start there instead, not with a Dataframe.
type: Comment

http://stackoverflow.com/q/48636748
has comment: http://stackoverflow.com/comment/84271573
has comment: http://stackoverflow.com/comment/84269968
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 5
score: 5
has answer: http://stackoverflow.com/a/48637928
has body: I have one simple pytest problem,: import pytest @pytest.fixture def config(): return "abc" def mytest(config): print(config) The message mentioned that "Shadows name 'config' from out scope" in the line of def mytest(config):. Any suggestion to handle this PEP8 message?
tagged with: python
has title: PEP8 mark the variable reference @pytest.fixture as "shadows name from outer scope"
tagged with: pytest
tagged with: pep8
downvote count: 0
answer count: 1

http://stackoverflow.com/a/48517213
answers question: http://stackoverflow.com/q/48516215
has comment: http://stackoverflow.com/comment/84038314
has comment: http://stackoverflow.com/comment/84105471
type: Answer
has comment: http://stackoverflow.com/comment/84055719
score: 2
upvote count: 2
downvote count: 0
has body: Give your objects a self._layer attribute and set it to the self.rect.bottom coord. Sprites with a higher layer number appear above the sprites with lower numbers. When the player moves, you can call the change_layer method of the LayeredUpdates group to set the layer of the sprite in the group to the current rect.bottom position. Here's a complete example: import random import pygame as pg PLAYER_IMG = pg.Surface((30, 50)) PLAYER_IMG.fill(pg.Color('dodgerblue1')) TRIANGLE_IMG = pg.Surface((50, 50), pg.SRCALPHA) pg.draw.polygon(TRIANGLE_IMG, (240, 120, 0), [(0, 50), (25, 0), (50, 50)]) class Player(pg.sprite.Sprite): def __init__(self, pos): super().__init__() self.image = PLAYER_IMG self.rect = self.image.get_rect(center=pos) # The sprite will be added to this layer in the LayeredUpdates group. self._layer = self.rect.bottom class Triangle(pg.sprite.Sprite): def __init__(self, pos): super().__init__() self.image = TRIANGLE_IMG self.rect = self.image.get_rect(center=pos) # The sprite will be added to this layer in the LayeredUpdates group. self._layer = self.rect.bottom def main(): screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() all_sprites = pg.sprite.LayeredUpdates() player = Player((50, 80)) all_sprites.add(player) for _ in range(20): all_sprites.add(Triangle((random.randrange(600), random.randrange(440)))) done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True keys = pg.key.get_pressed() if keys[pg.K_d]: player.rect.x += 5 if keys[pg.K_a]: player.rect.x -= 5 if keys[pg.K_w]: player.rect.y -= 5 if keys[pg.K_s]: player.rect.y += 5 # If any of the wasd keys are pressed, change the layer. if any((keys[pg.K_w], keys[pg.K_a], keys[pg.K_s], keys[pg.K_d])): # Set the layer of the player sprite to its rect.bottom position. all_sprites.change_layer(player, player.rect.bottom) all_sprites.update() screen.fill((30, 30, 30)) all_sprites.draw(screen) pg.display.flip() clock.tick(30) if __name__ == '__main__': pg.init()…

http://stackoverflow.com/a/48556595
has comment: http://stackoverflow.com/comment/84131054
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48555747
type: Answer
has comment: http://stackoverflow.com/comment/84126427
has body: Assuming that all your instances of Spectrum have the same ydata-length, I would go with a simple list comprehension: array = np.array([spec[i+1].ydata for i in range(len(spec))]) print(array) output: [[1 2 3] [4 5 6]] EDIT: I took another look at the desired output, in that case it would be array = np.array([spec[i+1].ydata for i in range(len(spec))]).T and [[1 4] [2 5] [3 6]] EDIT: I wrote a small test program to compare the performances of np.array().T and np.column_stack() against each other: import numpy as np from timeit import Timer class Spectrum(object): def __init__(self, ydata): self.ydata = ydata def create_by_array(): return np.array([spec[i+1].ydata for i in range(len(spec))]).T def create_by_column_stack(): return np.column_stack([spec[i+1].ydata for i in range(len(spec))]) I = 1000 spec = {i: Spectrum([j for j in range(3*i,3*(i+1))]) for i in range(1,I+1)} t1 = Timer( """create_by_array()""", setup="""from __main__ import create_by_array""" ) res1 = t1.repeat(10,1000) t2 = Timer( """create_by_column_stack()""", setup="""from __main__ import create_by_column_stack""" ) res2 = t2.repeat(10,1000) print( 'Results of the two tests: ', '{:5}, {:5}, {:5}'.format('min','mean','max') ) print( 'With np.array and transpose:', '{:5.3}, {:5.3}, {:5.3}'.format(np.min(res1), np.mean(res1),np.max(res1)) ) print( 'With np.column_stack(): ', '{:5.4}, {:5.4}, {:5.4}'.format(np.min(res2), np.mean(res2),np.max(res2)) ) The program first produces a dict of 1000 Spectrum instances and then times the two methods 10 x 1000 times. Here are the results: ('Results of the two tests: ', 'min , mean , max ') ('With np.array and transpose:', '0.687, 0.709, 0.742') ('With np.column_stack(): ', '3.982, 4.367, 5.263') As you can see, np.array().T method is about 5 times faster than the np.column_stack(). I'm not entirely sure why that is, but according to the numpy column_stack documentation page, Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D …
accepted answer of: http://stackoverflow.com/q/48555747
has comment: http://stackoverflow.com/comment/84138987
score: 0

http://stackoverflow.com/comment/84202878
type: Comment
type: QuestionComment
has text: @3novak missed your comment - you should post as answer!
comment on: http://stackoverflow.com/q/48602903
score: 0

http://stackoverflow.com/a/48654725
accepted answer of: http://stackoverflow.com/q/48617771
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48617771
has body: There was a thread discussing this in the original caffe implementation and one of the repositories I was working on here. Author of the SSD paper says: You can think of it as approximating a gaussian distribution for adjusting the prior box. Or you can think of it as scaling the localization gradient. Variance is also used in original MultiBox and Fast(er) R-CNN. Author of the repo that I was working on says: Probably, the naming comes from the idea, that the ground truth bounding boxes are not always precise, in other words, they vary from image to image probably for the same object in the same position just because human labellers cannot ideally repeat themselves. Thus, the encoded values are some random values, and we want them to have unit variance that is why we divide by some value. Why they are initialized to the values used in the code - I've no idea, probably some empirical estimation by the authors.
type: Answer

http://stackoverflow.com/comment/131133497
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/63933172
has text: Thanks, it works but it gives me two different objects for every User
score: 0

http://stackoverflow.com/q/48500047
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48500222
has comment: http://stackoverflow.com/comment/83993467
has comment: http://stackoverflow.com/comment/83993810
answer count: 1
has comment: http://stackoverflow.com/comment/83993382
has body: I'm learning Python and for some reason I have a strange problem with negative indexes. Instead of getting the last character I get an empty string. And instead of getting all character but last I get the whole string back. Here is the code I'm using: print('Starting loop') for line in sys.stdin: last = line[-1] print 'last = ' + last allButLast = line[:-1] print 'AllButLast = ' + allButLast The result: Starting loop 123 123 last = AllButLast = 123 last = AllButLast = 123
has title: Last character when parsing from sys.stdin not printing properly
accepted answer: http://stackoverflow.com/a/48500222
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/83994128
downvote count: 1

http://stackoverflow.com/q/48525155
has answer: http://stackoverflow.com/a/48525300
tagged with: python
score: 0
tagged with: google-cloud-platform
linked to: http://stackoverflow.com/q/18564745
answer count: 1
tagged with: pip
upvote count: 1
has comment: http://stackoverflow.com/comment/84048868
downvote count: 1
has body: I am get some errors while trying to install google-cloud by using pip. I tried the following commands to install google-cloud: sudo pip install --upgrade google-cloud sudo pip3 install --upgrade google-cloud sudo pip3.6 install --upgrade google-cloud But I am getting the following error by all these commands: Requirement already satisfied: google-cloud in /usr/lib/python3.6/si te-packages/google_cloud-0.32.1.dev1-py3.6.egg Requirement already satisfied: google-api-core&lt;0.2.0dev,&gt;=0.1.2 in / usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-bigquery&lt;0.29dev,&gt;=0.28. 0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-bigquery-datatransfer&lt;0. 2dev,&gt;=0.1.0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-bigtable&lt;0.29dev,&gt;=0.28. 1 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-container&lt;0.2dev,&gt;=0.1.0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-core&lt;0.29dev,&gt;=0.28.0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-datastore&lt;1.5dev,&gt;=1.4.0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-dns&lt;0.29dev,&gt;=0.28.0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-error-reporting&lt;0.29dev, &gt;=0.28.0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-firestore&lt;0.29dev,&gt;=0.28 .0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-language&lt;1.1dev,&gt;=1.0.0 in /usr/lib/python3.6/site-packages (from google-cloud) Requirement already satisfied: google-cloud-logging&lt;1.5dev,&gt;=1.4.0 i n /usr/lib/python3.6/site-packages (fro…
favorite count: 0
type: Question
has title: Error in installing google-cloud
type: UnansweredQuestion

http://stackoverflow.com/q/48516113
tagged with: lmdb
has answer: http://stackoverflow.com/a/48516748
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84027275
has comment: http://stackoverflow.com/comment/84027318
linked to: http://stackoverflow.com/q/33117607
type: Question
tagged with: deep-learning
has body: I have two LMDB files, with the first one my network trains fine while with the other one doesn't really work (loss starts and stays at 0). So I figured that maybe there's something wrong with the second LMDB. I tried writing some python code (mostly taken from here) to fetch the data from my LMDBs and inspect it but so far no luck with any of the 2 databases. The LMDBs contain images as data and bounding box information as labels. Doing this: for key, value in lmdb_cursor: datum.ParseFromString(value) label = datum.label data = caffe.io.datum_to_array(datum) on either one of the LMDBs gives me a key which is correctly the name of the image, but that datum.ParseFromString function is not able to retrieve anything from value. label is always 0, while data is an empty ndarray. Nonetheless, the data is there, value is a binary string of around 140 KB which correctly accounts for the size of the image plus the bounding box information I guess. I tried browsing several answers and discussions dealing with reading data from LMDBs in python, but I couldn't find any clue on how to read structured information such as bounding box labels. My guess is that the parsing function expects a digit label and interprets the first bytes as such, with the remaining data being then lost due to the binary string not making any sense anymore? I know for a fact that at least the first LMDB is correct since my network performs correctly in both training and testing using it. Any inputs will be greatly appreciated!
has comment: http://stackoverflow.com/comment/84026912
has comment: http://stackoverflow.com/comment/84027379
has title: Caffe & python, reading LMDB with complex label structure
score: 4
upvote count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: neural-network
accepted answer: http://stackoverflow.com/a/48516748
tagged with: caffe
tagged with: python

http://stackoverflow.com/comment/84123035
has text: Can you also post snippet where you execute the query?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48563303
score: 1

http://stackoverflow.com/comment/106408313
type: Comment
comment on: http://stackoverflow.com/q/48581540
type: QuestionComment
score: 0
has text: FYI: My answer here explains how weighting works: https://stats.stackexchange.com/a/448904/216706

http://stackoverflow.com/q/48571820
answer count: 4
type: AnsweredQuestion
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48572030
has title: Creating dataframe from dict inside dict with new column names
has answer: http://stackoverflow.com/a/48572030
upvote count: 1
has comment: http://stackoverflow.com/comment/84140434
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48572389
has body: I have a dictionary which looks something like: dictionary = {'A' : {'a': 2, 'b': 3, 'c': 4}, 'B' : {'a': 4, 'd': 3, 'e': 3}} I want to create a dataframe that looks like, P1 P2 P3 0 A a 2 1 A b 3 2 A c 4 3 B a 4 4 B d 3 5 B e 3 I want to have the keys of first dictionary as one column and keys and values of the inner dictionary as second and third column respectively with new column names.
possible better answer: http://stackoverflow.com/a/48571878
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48571878
has answer: http://stackoverflow.com/a/48572236

http://stackoverflow.com/comment/84077043
has text: There are no headers in FTP nor SFTP. Headers are HTTP-only thing. - This might be [XY problem](https://meta.stackexchange.com/q/66377/218578). What do you want to achieve? What do headers have to do with your player being slow or fail? Actually is it slow or does it fail? You cannot get both.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48539829
type: QuestionComment

http://stackoverflow.com/comment/84140336
has text: You're making things harder by treating two series from the same (grouped) df as two different objects. Instead do `df.groupby(['ID', 'yy'])` and save that grouped df (or use it with a context manager). See my answer
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48551370

http://stackoverflow.com/comment/84044400
type: Comment
type: QuestionComment
has text: Are all the times in Dataframe A going to have ten-minute intervals as shown here or could they be more granular?
comment on: http://stackoverflow.com/q/48524552
score: 0

http://stackoverflow.com/comment/84183075
score: 0
type: Comment
type: AnswerComment
has text: you just decide that it's illegal when you find the first match of it, but that still requires that you know what it is in advance.
comment on: http://stackoverflow.com/a/48591930

http://stackoverflow.com/comment/84174232
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48588490
has text: Regex isn't practical for this kind of thing.
score: 10

http://stackoverflow.com/q/48615935
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48616589
tagged with: opencv
tagged with: image-stitching
has answer: http://stackoverflow.com/a/48616589
score: 7
has answer: http://stackoverflow.com/a/48629229
tagged with: python
has comment: http://stackoverflow.com/comment/84234640
has comment: http://stackoverflow.com/comment/84229349
has comment: http://stackoverflow.com/comment/84396204
has title: Merging regions in MSER for identifying text lines in OCR
has body: I am using MSER to identify text regions in MSER. I am using the following code to extract the regions and save them as an image. Currently, each identified region is saved as a separate image. But, I want to merge regions belonging to a line of text merged as a single image. import cv2 img = cv2.imread('newF.png') mser = cv2.MSER_create() img = cv2.resize(img, (img.shape[1]*2, img.shape[0]*2)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) vis = img.copy() regions = mser.detectRegions(gray) hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions[0]] cv2.polylines(vis, hulls, 1, (0,255,0)) How can I stitch the images that belong to a single line together? I get the logic to do will mostly be based on some heuristic for identifying areas with nearby y-coordinates. But how exactly the regions can be merged in OpenCV. I am missing out on this as I am new to openCV. Any help would be appreciated. Attaching a sample image The desired output(s) is as follows Another line Another Line
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84229151
answer count: 2
linked to: http://stackoverflow.com/q/34981144
possible better answer: http://stackoverflow.com/a/48629229
has comment: http://stackoverflow.com/comment/84365199
tagged with: mser
downvote count: 0
tagged with: bounding-box
upvote count: 7
has comment: http://stackoverflow.com/comment/84229470

http://stackoverflow.com/a/48584644
answers question: http://stackoverflow.com/q/48584422
score: 5
has body: It's quite simple with a logic function import numpy as np aa = np.array([-4.793, -1.299, 0.453, np.nan, np.nan, 1.131, 0.684, 1.037]) mask = np.logical_or(-4 &lt; aa, np.isnan(aa)) print mask # [False True True True True True True True]
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48584422
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48612634
possible better answer: http://stackoverflow.com/a/48612975
has answer: http://stackoverflow.com/a/48613703
tagged with: python
tagged with: numpy
type: AnsweredQuestion
has title: How to set zdir in Axes3D of matplotlib to get better waterfall
answer count: 2
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48612975
favorite count: 0
has body: I am planning to plot waterfall like figures from multi-text data files, x is the wavelength, y are the responses, z is the frame number. x and y have the same dimensions(e.x. 5000 data). Basically, simplified my code is something like the following, I find I can not get the right view. What I want is the z-axis and y-axis be exchanged, from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from numpy import arange, sin, pi x = arange(0.0, 10, 0.04) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for z in range(0,8): y = sin(2*x*pi*z) ax.plot(x, y, z ) plt.xlabel(' x', fontsize = 12, color = 'black') plt.ylabel(' y', fontsize = 12, color = 'black') plt.show() with the "zdir='y'" Without zdir='y' What I want is Z-axis and y-axis be exchanged in Fig2. Thanks a lot!
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48613703
tagged with: matplotlib

http://stackoverflow.com/q/48491764
tagged with: apply
has comment: http://stackoverflow.com/comment/83977003
has title: Pandas Apply and Loc - efficiency and indexing
has answer: http://stackoverflow.com/a/48512606
accepted answer: http://stackoverflow.com/a/48491963
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48512606
has comment: http://stackoverflow.com/comment/83976873
has body: I want to find the first value after each row that meets a certain criteria. So for example I want to find the first rate/value (not necessarily the first row after) after the current row that increased 5%. The added column would be the last 'first5percentIncrease' and would be the index (and/or value) of the first row (after current row) that had a 5% increase. Notice how each could not be lower than the current row's index. amount date rate total type first5percentIncreaseValue first5percentIncreaseIndex 9248 0.05745868 2018-01-22 06:11:36 10 0.00099984 buy 10.5 9341 9249 1.14869147 2018-01-22 06:08:38 20 0.01998989 buy 21 9421 9250 0.16498080 2018-01-22 06:02:59 15 0.00286241 sell 15.75 9266 9251 0.02881844 2018-01-22 06:01:54 2 0.00049999 sell 2.1 10911 I tried using loc to apply() this to each row. The output takes at least 10 seconds for only about 9k rows. This does the job (I get a list of all values 5% higher than the given row) but is there a more efficient way to do this? Also I'd like to get only the first value but when I take do this I think it's starting from the first row. Is there a way to start .locs search from the current row so then I could just take the first value? coin_trade_history_df['rate'].apply( lambda y: coin_trade_history_df['rate'].loc[coin_trade_history_df['rate'].apply( lambda x: y &gt;= x + (x*.005))]) 0 [0.01387146, 0.01387146, 0.01387148, 0.0138714... 1 [0.01387146, 0.01387146, 0.01387148, 0.0138714... 2 [0.01387146, 0.01387146, 0.01387148, 0.0138714... 3 [0.01387146, 0.01387146, 0.01387148, 0.0138714... 4 [0.01387146, 0.01387146, 0.01387148, 0.0138714... Name: rate, dtype: object Further clarification Peter Leimbigler said it better than me: Oh, I think I get it now! "For each row, scan downward and get the first row you encounter that shows an increase of at least 5%," right? I'll edit my answer :) – Peter Leimbigler
tagged with: pandas-loc
type: Question
has comment: http://stackoverflow.com/comment/83976770
tagged with: pandas
has answer: http://stackoverflow.com/a/48491963
tagged with: python

http://stackoverflow.com/q/48501803
has comment: http://stackoverflow.com/comment/84001398
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54966624
upvote count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84000465
has body: @app.route('/result/&lt;case_id&gt;') def result(case_id): USER_FOLDER = os.path.join(UPLOAD_FOLDER + '/' + Case_ID) Analysis_code.main(USER_FOLDER, Case_ID, Case_ID + '_mRNA_file.txt', Case_ID + '_lncRNA_file.txt', Case_ID + '_miRNA_file.txt') return render_template('test.html',case_id=Case_ID) In my this result route, I call a function that are from another file.But when flask executed Analysis_code.main(), it didn't have enough time to run through the code. In my Analysis_code.main(), the correlation def seemed like doesn't finish the save file job, and server return gateway timeout error back. def main(): correlation(PATH, CASE_ID, mRNA_file_name, lncRNA_file_name, miRNA_file_name) bipartite_network(PATH, CASE_ID) Is there any way to solve this problem? I've searched about subprocess, but it seems like it's not suitable for me. I am trying to figure out how to return the render_template and the def call from another python code can still finish in the background. Now, render_template has to wait for the function call finish so that it can return the webpage.
has comment: http://stackoverflow.com/comment/84000242
type: UnansweredQuestion
has title: How to run another python code in background with flask
answer count: 1
tagged with: flask
has comment: http://stackoverflow.com/comment/84008178
has comment: http://stackoverflow.com/comment/83997169
has comment: http://stackoverflow.com/comment/84003614
score: 1
downvote count: 1

protractor
type: Tag
tag name: protractor
tags question: http://stackoverflow.com/q/48551528

http://stackoverflow.com/comment/84102095
type: Comment
has text: Thanks, it is such a short and complex code, and very beautiful! I gonna split it into several steps for better understanding!
comment on: http://stackoverflow.com/a/48552719
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84021271
type: Comment
comment on: http://stackoverflow.com/a/48513132
type: AnswerComment
has text: @schilcote, if you've already serialize the result into files, then I will suggest you do calculate a sha hash from your file and use that sha hash value as the name of the file. Assuming the same test result will produce the same file (byte to byte comparison ).
score: 0

http://stackoverflow.com/q/48547697
tagged with: pandas
tagged with: matplotlib
tagged with: python
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/48548188
has body: I have a data frame with weekdays. I need to highlight weekends ('Saturday' &amp; 'Sunday') with a different color on my bar chart. I found some solutions where I can set a different color by index.get_indexer. But how can I do it more efficiently by setting a condition? Will appreciate your help! # create an example of my df dates = pd.DataFrame({'dates': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], 'stats':[10,20,30,40,50,60,70,10,20,30,40,50,60,70], 'other':[44,55,66,88,33,22,11,44,55,66,88,33,22,11]}) # And plot it... ax = dates.plot(x='dates', y='stats', kind='bar', color='b') ax.patches[dates.index.get_indexer([5])[0]].set_facecolor('orange') ax.patches[dates.index.get_indexer([6])[0]].set_facecolor('orange') # etc... ax.legend() plt.show()
has answer: http://stackoverflow.com/a/48548188
answer count: 1
tagged with: bar-chart
has title: Change colour of bars based on string value
type: AnsweredQuestion

http://stackoverflow.com/q/48574997
tagged with: hdfs
has answer: http://stackoverflow.com/a/48666604
has title: Connection timeout error while reading a file from HDFS using Python
has body: I have created a single node HDFS in a VM (hadoop.master, IP: 192.168.12.52). The file etc/hadoop/core-site.xml has the following configuration for the namenode: fs.defaultFS hdfs://master.hadoop:9000/ I want to read a file from the HDFS on my local, physical desktop. For that, this is my code, which I've saved in a file named hdfs_read.py: from hdfs import InsecureClient client = InsecureClient('http://192.168.12.52:9000') with client.read('/opt/hadoop/LICENSE.txt') as reader: features = reader.read() print(features) Now when I run it, I get the following timeout error: $ python3 hdfs_read.py Traceback (most recent call last): File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 137, in _new_conn (self.host, self.port), self.timeout, **extra_kw) File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 91, in create_connection raise err File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 81, in create_connection sock.connect(sa) OSError: [Errno 113] No route to host During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 560, in urlopen body=body, headers=headers) File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 354, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/usr/lib/python3.6/http/client.py", line 964, in send self.connect() File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 162, in con…
favorite count: 0
has comment: http://stackoverflow.com/comment/84149379
has comment: http://stackoverflow.com/comment/84149016
has answer: http://stackoverflow.com/a/48577497
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/48666294
has comment: http://stackoverflow.com/comment/84149337
answer count: 4
has answer: http://stackoverflow.com/a/57856749
type: Question
has comment: http://stackoverflow.com/comment/84149532
tagged with: hadoop
has comment: http://stackoverflow.com/comment/84151284
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84148971
has comment: http://stackoverflow.com/comment/84150912
downvote count: 0

http://stackoverflow.com/comment/84044284
has text: I recommend using Willian Fuks solution and, also, just to make things clear, `gsutil` is used for GCS and for BigQuery `bq` is used ([docs](https://cloud.google.com/bigquery/bq-command-line-tool)).
comment on: http://stackoverflow.com/q/48508954
type: QuestionComment
type: Comment
score: 0

aws-lambda
tags question: http://stackoverflow.com/q/48636108
tags question: http://stackoverflow.com/q/48619163
type: Tag
tags question: http://stackoverflow.com/q/48641292
tags question: http://stackoverflow.com/q/48551038
tags question: http://stackoverflow.com/q/48613604
tags question: http://stackoverflow.com/q/48632576
tags question: http://stackoverflow.com/q/48492495
tags question: http://stackoverflow.com/q/48554902
tags question: http://stackoverflow.com/q/48580673
tag name: aws-lambda
tags question: http://stackoverflow.com/q/48541074

http://stackoverflow.com/q/48639069
type: Question
upvote count: 9
has body: My python version is 3.6.3 and spark version is 2.2.1. Here is my code: from pyspark.ml.linalg import Vectors from pyspark.ml.feature import VectorAssembler from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession sc = SparkContext() spark = SparkSession.builder.appName("Data Preprocessor") \ .config("spark.some.config.option", "1") \ .getOrCreate() dataset = spark.createDataFrame([(0, 59.0, 0.0, Vectors.dense([2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9.0, 9.0, 9.0]), 1.0)], ["id", "hour", "mobile", "userFeatures", "clicked"]) assembler = VectorAssembler(inputCols=["hour", "mobile", "userFeatures"], outputCol="features") output = assembler.transform(dataset) output.select("features").show(truncate=False) Instead of getting a single vector, I am getting following output: (12,[0,2,9,10,11],[59.0,2.0,9.0,9.0,9.0])
tagged with: pyspark
has answer: http://stackoverflow.com/a/48639576
tagged with: python
duplicate of: http://stackoverflow.com/q/40505805
tagged with: apache-spark-mllib
has title: Vector assembler in Pyspark is creating tuple of multiple vectors instead of a single vector, how to solve the issue?
score: 9
type: AnsweredQuestion
downvote count: 0
tagged with: apache-spark
linked to: http://stackoverflow.com/q/40505805
answer count: 1
accepted answer: http://stackoverflow.com/a/48639576
favorite count: 0

http://stackoverflow.com/comment/84243437
type: Comment
score: 0
has text: What do you mean by „repeat for each year“? You wanted to count the number of events between given dates, right? That‘s what my suggested code does...
type: AnswerComment
comment on: http://stackoverflow.com/a/48620936

http://stackoverflow.com/comment/84078648
comment on: http://stackoverflow.com/q/48536835
score: 0
type: Comment
type: QuestionComment
has text: @three_pineapples Thank you. I really tried a lot and exhausted couldn't find the solution. If you could run the above code you can see the problem.

http://stackoverflow.com/a/48569214
has comment: http://stackoverflow.com/comment/84137147
has comment: http://stackoverflow.com/comment/84151904
has body: I'm sure you can and should use --site-packages. It doesn't do what you seem to think it does — it doesn't make pip install all packages globally. It makes python in the virtual env access global site-packages but pip still install packages in the virtual env (after you activate it with . env/bin/activate).
score: 0
has comment: http://stackoverflow.com/comment/84151516
has comment: http://stackoverflow.com/comment/84138418
has comment: http://stackoverflow.com/comment/84151575
answers question: http://stackoverflow.com/q/48563680
type: Answer
has comment: http://stackoverflow.com/comment/84152581

http://stackoverflow.com/comment/84087616
type: Comment
comment on: http://stackoverflow.com/q/48545890
score: 0
has text: what sizes are you simulating, with what? lists or numpy? Optimization is normally a thing for http://codereview.stackexchange.com. and for anything that is not using a crystal ball, enhanced clairvoyance and the lookFutureAI.dll this piece of code is not really helpfull. Read up on codereview posting rules and post it according to theire rules there. moving this questions probably not needed as it is not complete enough.
type: QuestionComment

http://stackoverflow.com/a/48513612
accepted answer of: http://stackoverflow.com/q/48513591
type: Answer
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84021978
has comment: http://stackoverflow.com/comment/84022047
has body: You have to set the directory in the pythonpath so python knows where to look at: export PYTHONPATH=$PYTHONPATH:/your/path/to/your/module
answers question: http://stackoverflow.com/q/48513591
score: 3

http://stackoverflow.com/a/48599398
has body: The error is because there is no name Login defined in the available scopes where you are using it. Instead you must use the qualified name login_page.Login as in your login() function. However, more importantly, you cannot call with_() or login_succesfull_() on the class name. Instead, you need an instance of the Login class. There are several pieces missing that are needed to fix this. First of all, Selenium is often used within the context of a testing framework. This isn't strictly required but is the most common use case. PyCharm defaults to running tests with unittest. To use unittest, you must create a class which inherits from the TestCase class: import unittest.TestCase class TestLogin(TestCase): pass Most such classes will have a setUp() method which initializes the fixture for each test in the class. For example, this is where you can perform the login: import unittest.TestCase class TestLogin(TestCase): def setUp(self): self.page = self.login() Next, your login() function takes a request parameter which it never uses. You can just remove it: def login(self): ... Now in your test, use the page member variable which we created in setUp(): def test_login(self): self.page.with_("username", "password") assert self.page.login_succesfull_() I suggest that you read more about unittest before continuing with Selenium. You also need to learn more about Object Oriented Programming in Python, especially the syntax required to create and use objects.
answers question: http://stackoverflow.com/q/48599095
type: AcceptedAnswer
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48599095
score: 1
has comment: http://stackoverflow.com/comment/84199600
downvote count: 0

http://stackoverflow.com/comment/84238933
type: QuestionComment
has text: Why don't you try using set operations like union and intersection? I am not able to understand your question very well.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48620997

http://stackoverflow.com/a/48593008
type: Answer
has comment: http://stackoverflow.com/comment/84183298
has comment: http://stackoverflow.com/comment/84183355
score: 0
has comment: http://stackoverflow.com/comment/84183545
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84183433
accepted answer of: http://stackoverflow.com/q/48592965
answers question: http://stackoverflow.com/q/48592965
has comment: http://stackoverflow.com/comment/84183576
has body: Since you do import peakutils, you don't need this line: from peakutils import * Remove that extra line and it should work.

http://stackoverflow.com/comment/84270253
type: QuestionComment
has text: Possible duplicate of [How to get scroll bar real width in Qt?](https://stackoverflow.com/questions/16515646/how-to-get-scroll-bar-real-width-in-qt)
comment on: http://stackoverflow.com/q/48636467
score: 1
type: Comment

http://stackoverflow.com/comment/84047204
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48521754
has text: Thanks, I'll try there.
score: 0

http://stackoverflow.com/comment/84064241
comment on: http://stackoverflow.com/a/48532869
type: AnswerComment
score: 0
has text: I am using eclipse, not Pycharm.
type: Comment

http://stackoverflow.com/q/48534360
type: Question
has body: I am trying to send an array as postData = {'WIFI_CLONE', 'keyword#2'} to python post request as follows and running into exception as too many values to unpack ?how to fix this? def AddKeywordToProblem(self, problemID=None, keyword = ""): if self._checklogin(): problemID = '37040553' postData = ['WIFI_CLONE', 'keyword#2'] logger.info(postData) r = requests.post(self._baseurl + 'problems/' + problemID + '/keywords', headers=self._headers,data=postData,timeout=DEFAULT_REQUESTS_TIMEOUT) if r.status_code != 201: logger.warning('Error: Unable to get data. Server came back with:') logger.warning(r.text) return False return r.json() Exception too many values to unpack
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48534437
has title: how to send an array in python post data
has comment: http://stackoverflow.com/comment/84065118
score: 2
favorite count: 0

http://stackoverflow.com/a/75123667
answers question: http://stackoverflow.com/q/48621360
type: Answer
has body: I thought I would post my solution for others that may be coming in from the search engine. When I was learning async networking programming in Python I couldn't find an async API for UDP. I searched Google for why that was and eventually came across an old mailing list posting about the issue and how Python's creator thought it was a bad idea. I don't agree with this. Yes, it's true UDP packets are unordered and may not arrive but there's no technical reason why it shouldn't be possible to have awaitable APIs for send/recv/open/close in UDP. So I built a library and added it. Here's what it looks like to do async UDP. First, start the Python REPR with await support: python3 -m asyncio from p2pd import * # Load internal interface details. netifaces = await init_p2pd() # Load the default interface. i = await Interface(netifaces=netifaces) # Open a UDP echo client. route = await i.route().bind() dest = await Address("p2pd.net", 7, route) pipe = await pipe_open(UDP, dest, route) # Queue all responses. pipe.subscribe() # Send / recv. await pipe.send(b"echo back this data", dest.tup) out = await pipe.recv() print(out) # Cleanup. await pipe.close() There's many more problems my library solves. It properly handles interface management, address lookup, and NAT enumeration. It makes IPv6 as easy to use as IPv4. It provides the same API for UDP / TCP / Server / Client. It supports peer-to-peer connections. And there's a REST API that can be used from other languages. You can read more about the problems Python async networking has at https://roberts.pm/p2pd and the docs from my library are at https://p2pd.readthedocs.io/en/latest/.
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/84009292
comment on: http://stackoverflow.com/q/48507133
type: QuestionComment
type: Comment
has text: Do you also want the files in subdirectories, if any, included in the list?
score: 0

session-cookies
tags question: http://stackoverflow.com/q/48561819
type: Tag
tag name: session-cookies

http://stackoverflow.com/comment/84163798
score: 0
has text: If [reading the yes/no from stdin in the Python script](https://stackoverflow.com/q/1450393/6505250) does not work, you can wrap the command in an Ant or shell/bash script.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48544209

http://stackoverflow.com/comment/84285064
type: AnswerComment
has text: WOW! I can't believe I didn't see that. Thanks.
comment on: http://stackoverflow.com/a/48644123
score: 0
type: Comment

http://stackoverflow.com/q/48499398
answer count: 1
downvote count: 0
tagged with: process
tagged with: x11
upvote count: 1
has answer: http://stackoverflow.com/a/48502825
linked to: http://stackoverflow.com/q/11063458
favorite count: 0
has body: I have asked a question how to run a clipboard clearing command from python, and I got a good answer for that: subprocess.run("xclip",stdin=subprocess.DEVNULL) subprocess.run(["xclip","-selection","clipboard"],input="") This seem to work in python, but there is a problem, it leaves the process open. Actually it opens 2 processes, one xclip and one with xclip -selection clipboard parameters. And it seems like they are zombie processes, they remain there indefinitely, until you copy-paste something again. After that both of them dissapear. So I have run the script from an USB drive's directory, and it doesn't let you remove the USB drive, it says "USB drive busy", until the processes don't close. So either I copy something new into the clipboard, otherwise the process remains there indefinitely, like a zombie. Is it possible to just close the process after the python script ends? Since there is no reason for that process to remain open after the python script has ran.
has title: How to run a process and quit after the script is over?
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84012464
has comment: http://stackoverflow.com/comment/83992741
type: Question
linked to: http://stackoverflow.com/q/48490382
tagged with: python-3.x
tagged with: subprocess
type: UnansweredQuestion

http://stackoverflow.com/comment/84189985
comment on: http://stackoverflow.com/a/48595935
has text: Last one: The solution you mention creates a list. I need a string?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48544112
answers question: http://stackoverflow.com/q/48543979
type: Answer
score: 4
has body: Use floor for remove times, then create date_range and get difference: d = df['dti'].dt.floor('d') print (d) 0 2016-07-27 1 2016-07-29 2 2016-07-29 3 2016-07-30 4 2016-08-01 5 2016-08-02 Name: dti, dtype: datetime64[ns] a = pd.date_range(d.min(), d.max(), freq='d') print (a) DatetimeIndex(['2016-07-27', '2016-07-28', '2016-07-29', '2016-07-30', '2016-07-31', '2016-08-01', '2016-08-02'], dtype='datetime64[ns]', freq='D') b = a.difference(d) print (b) DatetimeIndex(['2016-07-28', '2016-07-31'], dtype='datetime64[ns]', freq=None) df1 = pd.DataFrame({'missing':a.difference(d)}) print (df1) missing 0 2016-07-28 1 2016-07-31 Another solution is downsample by mean and get indices of NaNs values: a = df.resample('d', on='dti').mean() print (a) id_n dti 2016-07-27 1.0 2016-07-28 NaN 2016-07-29 1.0 2016-07-30 2.0 2016-07-31 NaN 2016-08-01 3.0 2016-08-02 3.0 b = a.index[a['id_n'].isnull()] print (b) DatetimeIndex(['2016-07-28', '2016-07-31'], dtype='datetime64[ns]', name='dti', freq=None)
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48543979
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48512416
upvote count: 1
has comment: http://stackoverflow.com/comment/84055219
has body: I would send the already prepared data from the view to the template to avoid additional logic in the front-end. You could do something like this in the view: products = Product.objects.all() all_products_by_cat ={} for product in products: if all_products_by_cat.get(product.category): all_products_by_cat[product.category].append(product) else: all_products_by_cat[product.category] = [product] And in the template you would just do: {% for product in all_products_by_cat['some_category'] %} &lt;!-- do something with the product--&gt; {% endfor %}
answers question: http://stackoverflow.com/q/48512048
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/48640791
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: passing arguments between multiple decorators
accepted answer: http://stackoverflow.com/a/48767446
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/48767446
favorite count: 0
type: Question
has body: I am using two decorators to decorate a function "add_user", the first one @auth_user authenticates the logged in user via json web token request headers and returns the user's information as an argument "user_info" back to the decorated function add_user. The second decorator @has_permission is supposed to check whether or not the user has permissions on the requested resource. I wanted to pass the user's information returned as user_info by @auth_user to @has_permission but don't know how to do that, here is the code so far: @has_permission @auth_user def add_user(user_info): """ do something """ return None The decorators: def auth_user(f): @wraps(f) def wrapper(*args, **kwargs): data = jwt.decode(request.headers['some-access-token'], some_secret_key) try: user_info = User.query.filter(User.id==data['user_id']).first() except: return jsonify({"message" : "error"}), 401 return f(user_info, *args, **kwargs) return wrapper and the second decorator where I want to access the user_info: def has_permission(f): wraps(f) def wrapper(*args, **kwargs): # This is where I want to access the user information instead of processing the key again # # return some new_args ... # return f(*args, **kwargs) return wrapper What is the best way to achieve this?
tagged with: python-3.x
downvote count: 0

http://stackoverflow.com/a/48503388
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48503250
has comment: http://stackoverflow.com/comment/84000897
has comment: http://stackoverflow.com/comment/84000372
has comment: http://stackoverflow.com/comment/84000771
score: 3
has comment: http://stackoverflow.com/comment/84000653
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84001052
accepted answer of: http://stackoverflow.com/q/48503250
has body: You want to update your Product after each save of Review. So the best and fastest way would be using post save method. For example, after each saved product you can get all reviews and calculate overall rating and then save it to the Product. @receiver(post_save, sender=Review, dispatch_uid="update_overall_rating") def update_rating(sender, instance, **kwargs): parent = instance.product all_reviews = Review.objects.filter(product=parent) parent.overall_rating = get_overall_rating(all_reviews)

http://stackoverflow.com/comment/84097162
type: AnswerComment
comment on: http://stackoverflow.com/a/48550450
has text: How are you running your docker?
score: 0
type: Comment

http://stackoverflow.com/a/48579158
score: 0
type: Answer
has body: I found the solution to this issue. It's because I wrote my terminal output to a text file. So it took much more time when the delay increases time to time.
answers question: http://stackoverflow.com/q/48556297
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48556297

http://stackoverflow.com/a/48502735
answers question: http://stackoverflow.com/q/48492618
score: 2
downvote count: 0
upvote count: 2
type: Answer
has body: Your Item file "SoapguildItem" does not contain url named member variable, please define url. from scrapy.item import Item, Field class SoapguildItem(Item): url = Field()

http://stackoverflow.com/q/48598304
tagged with: curses
has body: I would like to format strings to show them with curses. For that, I would like to add spaces if the line is too short, and cut it and add continuation characters if it is too long. My problem is to compute the real width of the string in my terminal. In my string, I can have characters that won't be shown and others that will be of length two (and printed as square). Consequently, the function len is not a right candidate. To solve that, I tried to use unicodedate.category to filter characters: removed_category = ('Mn', 'So') string = ''.join(char for char in string \ if unicodedata.category(char) not in removed_category) But it does not work for all cases. For instance, 'Ｓ' is detected as a uppercase letter but in terminal its width is not one. Moreover, it is slow and not very elegant. I also tried string.printable to it removes also characters than can be shown in my terminal. EDIT (since the question is closed) Solutions based on unicodedata.east_asian_width do not work with zero-width characters. If we combine that with unicodedata.category, it seems to work: def stringWidth(string): width = 0 for c in string: # For zero-width characters if unicodedata.category(c)[0] in ('M', 'C'): continue w = unicodedata.east_asian_width(c) if w in ('N', 'Na', 'H', 'A'): width += 1 else: width += 2 return width Depending on your text, you may need to add other categores for zero-width characters.
tagged with: string
has comment: http://stackoverflow.com/comment/84193090
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84193127
linked to: http://stackoverflow.com/q/2455255
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84193112
duplicate of: http://stackoverflow.com/q/34655347
tagged with: python
has comment: http://stackoverflow.com/comment/84193699
has comment: http://stackoverflow.com/comment/84193785
score: 2
has comment: http://stackoverflow.com/comment/84193552
has comment: http://stackoverflow.com/comment/84193098
answer count: 0
duplicate of: http://stackoverflow.com/q/7086856
has title: Width of a string with zero-width and two-width characters, in Python 3 in a terminal (not in a GUI)
has comment: http://stackoverflow.com/comment/84193547
downvote count: 0

http://stackoverflow.com/a/48637265
downvote count: 0
answers question: http://stackoverflow.com/q/48616410
score: 3
type: Answer
has body: Since the pyquery doesn't support the pseudo classes like :hidden, I have added my own custom class ('myhide') to use that as a selector. So I have used the following code to remove the hidden elements from pyquery import PyQuery html_data = ''' This is a hidden div. This is another paragraph. This is a span This is a div. ''' pq = PyQuery(html_data) pq('.myhide').remove() pq.html() So the output comes like this This is another paragraph This is a div
upvote count: 3

http://stackoverflow.com/comment/84084672
type: QuestionComment
has text: @Piinthesky i've done the part of the code where it takes care of that.
comment on: http://stackoverflow.com/q/48543554
score: 0
type: Comment

http://stackoverflow.com/comment/84209663
comment on: http://stackoverflow.com/q/48606567
type: QuestionComment
type: Comment
score: 0
has text: In that case, to rebuild the document is trivial - since your document is not complex, all you have to do is the inverse operation of `split` which is `join`: i.e. `""".""".join(doc1)`.

http://stackoverflow.com/q/48638325
tagged with: python-3.x
type: Question
answer count: 2
has title: Using BeautifulSoup to Match string in a html document and highlight it where ever it appears
has comment: http://stackoverflow.com/comment/84273167
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50327040
score: 6
upvote count: 6
has answer: http://stackoverflow.com/a/59988682
has body: I am trying to match a string in a HTML document and highlight it particularly. I have used BeautifulSoup along with html.parser. What i have tried so far is using find_all() and passing the string to be matched but it doesnt help as it returns the whole text present in the element. I want you to guide me how to target the particular string in the document and highlight it. For Eg: Markup: Lorem is simply dummy text of the printing and typesetting industry. Lorem has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it After Highlighting: Markup: Lorem is simply dummy text of the printing and typesetting industry. Lorem has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it Expected Output: Lorem is simply dummy text of the printing and typesetting industry. Lorem has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it If i could get a array of the strings i can replace it with the mark tag . GOT SO FAR with beautifulsoup : import urllib.request import re from bs4 import BeautifulSoup sauce = urllib.request.urlopen('http://courseweb.stthomas.edu/mjodonnell/cojo258/resume/simple_code.html').read() soup = BeautifulSoup(sauce, 'html.parser') body = soup.find('body') results = body.find_all(text=re.compile(r'bastyr', re.I)) print(results)
downvote count: 0
has comment: http://stackoverflow.com/comment/84275603
tagged with: html-parsing
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/comment/84160359
type: Comment
comment on: http://stackoverflow.com/a/48582050
type: AnswerComment
has text: I think it should be dictionary["owner"]["name"]
score: 1

http://stackoverflow.com/comment/84166488
score: 0
type: QuestionComment
has text: Ok so, if I understand right, you mean that I must install anew python on GCP Compute Engine to even run my python script from my laptop even though it is already installed on my laptop?
comment on: http://stackoverflow.com/q/48584208
type: Comment

http://stackoverflow.com/q/48569690
has comment: http://stackoverflow.com/comment/84140536
answer count: 1
has comment: http://stackoverflow.com/comment/84140482
has body: I need to scrape links with text from table. There are two identical tables on page, but I need to select second table. Then data are only on 3rd column of this table. In each cell there are 4 different links a href="link"&gt;link&lt;/a&gt; and I need only 2nd link it each cell. I was able to extract 3rd column with this: table = soup.find_all(class_='bordercolor')[1] rows = table.find_all('tr') first_columns = [] third_columns = [] for row in rows[1:]: third_columns.append(row.find_all('td')[2]) for third in third_columns: print(third.text) EDIT: example page where i try to extract: https://www.simplemachines.org/community/index.php?board=9.0 need to extract subject with link
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/48572122
has title: Scrape certain data from a column
has answer: http://stackoverflow.com/a/48572122
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84135651
score: 0

http://stackoverflow.com/a/48626176
score: 0
type: Answer
has body: There was nothing wrong with your code other than it was a bit more convoluted than it had to. The following looks more on-the-money to me: import time temp_y.ValueConverted = 1 # initial value while temp_x != 0: # until it becomes 0 we... time.sleep(20) # ...wait temp_y.ValueConverted = 3 # and then we update the original temp_y print('Done') Finally, note that we are blocking execution with our while block so the initial temp_y.ValueConverted value does not have any effect. We could skip initialization and define it after our check is fulfilled.
has comment: http://stackoverflow.com/comment/84250459
answers question: http://stackoverflow.com/q/48626066
has comment: http://stackoverflow.com/comment/84249219

http://stackoverflow.com/comment/84239819
type: QuestionComment
has text: Can you post your JSON data?
score: 0
comment on: http://stackoverflow.com/q/48621750
type: Comment

http://stackoverflow.com/comment/84494537
comment on: http://stackoverflow.com/a/48672858
score: 0
type: AnswerComment
type: Comment
has text: Unfortunately, I had to revert the code back to the previous state (covering only the tests), because I could not generate an XML report for codecov. I did get the same table showing coverage results for the different .`pxi` files, though. https://github.com/SCIP-Interfaces/PySCIPOpt/pull/128

http://stackoverflow.com/comment/84085472
comment on: http://stackoverflow.com/a/48544937
score: 0
type: Comment
type: AnswerComment
has text: Are you using my code for generating `datelist` variable?

http://stackoverflow.com/a/48631202
type: Answer
has comment: http://stackoverflow.com/comment/84260120
accepted answer of: http://stackoverflow.com/q/48631155
score: 2
has body: On your machine (Unix), os.listdir was defined in the posix module. It's that simple. &gt;&gt;&gt; os.listdir is posix.listdir True
answers question: http://stackoverflow.com/q/48631155
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/48643114
downvote count: 1
upvote count: 0
has comment: http://stackoverflow.com/comment/84282740
answers question: http://stackoverflow.com/q/48642703
type: Answer
score: -1
has body: def revisedRussianRoulette(doors): counter = 0 for i in range(0, len(doors), 2): i = int(i) condition_one = doors[i] == 1 &amp; counter == 0 condition_two = doors[i] == 1 &amp; counter == 1 condition_three = doors[i] == 0 &amp; counter == 1 if condition_one: counter += 1 elif condition_two: doors[i] = 0 doors[i-2] = 0 doors[i+2] = 0 elif condition_three: doors[i-2] = 0 return doors n = int(input().strip()) doors = list(map(int, input().strip().split())) result = revisedRussianRoulette(doors) print (" ".join(map(str, result)))

http://stackoverflow.com/comment/84002252
type: Comment
has text: Yes. In theory, though, you should prepare for the occasion that your server has for example received only "exi" from the socket when it calls recv. If there does not appear to be something that makes sense, you need to read again and sum everything up before parsing. And if your delimiter char is \n and you have commands "show", "version" and "exit", you might have "version\nshow\nexit\n" when you read, and if you only use "endswith", you will have ignored two commands that should be processed first.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48503368

http://stackoverflow.com/q/48506842
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84008331
duplicate of: http://stackoverflow.com/q/3777861
tagged with: python
tagged with: kivy
type: Question
tagged with: python-3.x
tagged with: kivy-language
has body: Im trying to limit my bar chart at 100 and i tried putting ylim(100) but it wont show and it wont work import matplotlib matplotlib.use('module://kivy.garden.matplotlib.backend_kivy') from matplotlib.figure import Figure from numpy import arange, sin, pi from kivy.app import App import numpy as np from kivy.garden.matplotlib.backend_kivyagg import FigureCanvas,\ NavigationToolbar2Kivy from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from matplotlib.transforms import Bbox from kivy.uix.button import Button from kivy.graphics import Color, Line, Rectangle import matplotlib.pyplot as plt N = 5 menMeans = (20, 35, 30, 35, 27) menStd = (2, 3, 4, 1, 2) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars plt.ylim(100) fig, ax = plt.ylim(1000) fig, ax = plt.subplots() rects1 = ax.bar(ind, menMeans, width, color='b', yerr=menStd) womenMeans = (25, 32, 34, 20, 25) womenStd = (3, 5, 2, 3, 3) rects2 = ax.bar(ind + width, womenMeans, width, color='r', yerr=womenStd) # add some text for labels, title and axes ticks ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(ind + width) ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) canvas = fig.canvas class MatplotlibTest(App): title = 'Matplotlib Test' def build(self): fl = BoxLayout(orientation="vertical") nav1 = NavigationToolbar2Kivy(canvas) fl.add_widget(nav1.actionbar) fl.add_widget(canvas) return fl if __name__ == '__main__': MatplotlibTest().run() As you can see in the code i tried putting ylim but its not showing.
has comment: http://stackoverflow.com/comment/84008940
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84011292
has title: How to put a limit to my graph matplotlib
has comment: http://stackoverflow.com/comment/84015486
has comment: http://stackoverflow.com/comment/84008394
linked to: http://stackoverflow.com/q/3777861
score: 0

http://stackoverflow.com/q/48505891
tagged with: parsing
type: Question
has title: Extract function names in python code using javascript regex
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48506189
tagged with: javascript
has comment: http://stackoverflow.com/comment/84005998
score: 0
has comment: http://stackoverflow.com/comment/84007097
answer count: 1
tagged with: python
has body: I am using prism.js to highlight python code but for some reasons it is not highlighting function names which are called for example deep_flatten() or flatten([1,2,3]) or flatten(list(map(lambda x: x*2,[1,2,3]))). So made the following code to overcome this problem [...document.getElementsByClassName('code')].forEach(x =&gt; { x.innerText = x.innerText.replace(/(\w+)\([^\(\)]*\)/gi,match=&gt;{ if(match.match(/^\d/)){ return match } else { return `&lt;span class="called-function"&gt;${match}&lt;/span&gt;` } } }) It works fine for the first two ones but fails for the other two ones. On doing google search I found that this is called something recursive and can be done only with parsers. On searching for python parsers in javscript I found a lot of them but they are very big and for parsing whole code. How can I make a parser/regex which extracts all function names and encloses them within span tags. I don't want the specific code just some psuedo-code or algorithm as to how to proceed.
tagged with: regex
has comment: http://stackoverflow.com/comment/84007230

http://stackoverflow.com/comment/84055075
type: QuestionComment
has text: You could gain a lot of readability if you use str.format(). Read up on it, it's worth it :)
comment on: http://stackoverflow.com/q/48529862
score: 2
type: Comment

http://stackoverflow.com/comment/84210337
type: AnswerComment
score: 0
has text: @MaximilianPeters. thanks, i haven't tested this code - just a proof of concept. but i have updated nonetheless.
comment on: http://stackoverflow.com/a/48606964
type: Comment

http://stackoverflow.com/comment/84114689
score: 0
comment on: http://stackoverflow.com/q/48559251
type: Comment
type: QuestionComment
has text: Did you print out `df[0]`? Is it one string like shown in your example? Then you should first separate the header with `split(':')` and then the list elements with `.split()`.

http://stackoverflow.com/q/48534380
tagged with: for-loop
tagged with: turtle-graphics
possible better answer: http://stackoverflow.com/a/48534490
has comment: http://stackoverflow.com/comment/84064214
has answer: http://stackoverflow.com/a/48534490
type: Question
has title: Use a for loop to create a set of turtles from a list in Python
accepted answer: http://stackoverflow.com/a/48534476
has answer: http://stackoverflow.com/a/48534476
tagged with: python
has body: I'm attempting to create a list of turtles in Python. I can achieve this manually by the following: import turtle wn = turtle.Screen() one = turtle.Turtle() two = turtle.Turtle() I'm hoping to iterate through a list of turtle names using the following for loop, but the syntax is throwing me: import turtle wn = turtle.Screen() for turtleName in ["one","two"]: turtleName = turtle.Turtle() one.left(60) one.forward(160) NameError: name 'one' is not defined
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2

http://stackoverflow.com/a/48604757
score: 0
type: Answer
has body: The problem is that you are pulling the model number from the page and it looks like "P128080PP" but in the image src the P's are lowercase (-p128080pp-) so it's not matching in the line below if mpn in image.get_attribute('src'): There's a much easier way to do this. You are pulling all IMG tags, then matching on the model number, then matching on 145.jpg. You can do all of this in a single locator to avoid scraping the page multiple times and looping. You are also cutting your list in half at the end. I'm assuming this is because you are finding all the images on the page which includes things like Frequently Bought Together, More In This Collection, etc. I'm assuming you really only want the images from the product area. These are all in the &lt;div id="thumbnails" ...&gt; container. You can also add this to the locator so that you only get the images you want in one locator. def get_image_links(url): driver = webdriver.Chrome(r"C:\Users\Tut10\Desktop\PSTool-Python\chromedriver.exe") driver.get(url) model_no = driver.find_elements_by_css_selector("h2.modelNo").text.split(' ')[2].lower() image_list = driver.find_elements_by_css_selector("#thumbnails img[src$='145.jpg'][src*='" + model_no + "']") return image_list The first line gets the model number. I changed the locator to be shorter and less fragile. I did the same split() but changed it to lowercase so that it will match with the src in the images. The next line grabs all the images under the &lt;div id="thumbnails" ...&gt; where the src ends with 145.jpg and contains the model number.
answers question: http://stackoverflow.com/q/48603932

http://stackoverflow.com/comment/84029850
type: QuestionComment
score: 1
has text: You do not have Rabbit settings. You did not set up your broker.
comment on: http://stackoverflow.com/q/48517318
type: Comment

http://stackoverflow.com/comment/84253344
type: AnswerComment
has text: @hmaxx You might want to remove whitespaces, if any: `df['COL2'].str.strip().eq('SOME_NAME')`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48628097

http://stackoverflow.com/q/48588412
has answer: http://stackoverflow.com/a/48588623
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84174238
answer count: 1
tagged with: multi-index
type: Question
has comment: http://stackoverflow.com/comment/84174282
has title: Python pandas - Possible issue with multi indexing column names of different types
type: UnansweredQuestion
tagged with: python
has body: The following code leads to the exception: KeyError: u'the label [37,5 cl ] is not in the [columns]'. df = pd.read_csv('https://raw.githubusercontent.com/AntoineGautier/Data/master/new.txt') df.rename({'1': 1, '3': 3, '0':0}, axis=1, inplace=True) df.set_index(list(df.columns[:3]), inplace=True) df.sort_index(inplace=True) for idx in df.index: tmp = df.loc[idx] No exception if all column names are strings.

http://stackoverflow.com/a/48615106
answers question: http://stackoverflow.com/q/48615015
has comment: http://stackoverflow.com/comment/84227740
has comment: http://stackoverflow.com/comment/84227504
downvote count: 1
has body: Your entry_kg is not known anywhere outside the scope of initUI method. That is why. You could convert it from a method variable to instance attribute to be within reach for class methods by replacing: entry_kg = Entry(frame_kg) entry_kg.pack(fill=X, padx=(5, 30), expand=True) with: self.entry_kg = Entry(frame_kg) self.entry_kg.pack(fill=X, padx=(5, 30), expand=True) Only then: You can mention it in a class method like: ... kg = self.entry_kg.get() That way you if you make your convert a method under Example again: def initUI(self): ... def convert(self): # is defined under the same scope as initUI print("clicked") kg = self.entry_kg.get() # notice that it now refers to self.e... print(kg) also don't forget to replace command option as well: btn_convert=Button(..., command=self.convert) Or only then: When outside the class scope, by using dot notation on the object that the class creates: def main(): root = Tk() root.geometry("300x200+300+200") app = Example() kg = app.entry_kg.get() # This would return an empty string, but it would still be valid root.mainloop() to be used with global methods, such as the current state of convert you need to make app (the object it is an attribute of) global, or pass it explicitly to the method.
has comment: http://stackoverflow.com/comment/84227632
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/84227615
has comment: http://stackoverflow.com/comment/84227654
has comment: http://stackoverflow.com/comment/84227595
has comment: http://stackoverflow.com/comment/84227636
upvote count: 0

http://stackoverflow.com/comment/84059898
type: Comment
has text: There are nearly infinite ways to possibly structure the project. The standard structure works and is what you want unless you're trying to confuse newcomers.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48531960

http://stackoverflow.com/a/48488791
has body: In the case of your example, you can merely reassign the keys: d = {180: [], 192: [], 204: [], 216: [u'NVDA US Equity', u'UPS US Equity'], 228: [], 240: [u'AMZN US Equity'], 252: [u'BRK/B US Equity'], 264: [], 276: [], 288: [], 300: []} d[240], d[252] = d.get(252, []), d.get(240, []) Output: {192: [], 264: [], 204: [], 276: [], 216: [u'NVDA US Equity', u'UPS US Equity'], 288: [], 228: [], 300: [], 240: [u'BRK/B US Equity'], 180: [], 252: [u'AMZN US Equity']}
score: 0
answers question: http://stackoverflow.com/q/48488562
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/83970781
has comment: http://stackoverflow.com/comment/83970722
accepted answer of: http://stackoverflow.com/q/48488562

http://stackoverflow.com/comment/84146651
type: AnswerComment
type: Comment
has text: With the first worked. It was missing the end part (.text) (By.XPATH, '//div[@itemprop="description"]').text
comment on: http://stackoverflow.com/a/48574686
score: 0

http://stackoverflow.com/comment/84023784
has text: Anyway, create a list of all the expiration, and iterate it from 0 to the maximum expiration. count() is a function to count specific item in a list, so in the loop it will append counts of the expiration to output list in sequence, `output[0] = exp_list.count(0)` and so on.
type: AnswerComment
comment on: http://stackoverflow.com/a/48501801
score: 1
type: Comment

http://stackoverflow.com/q/48575709
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48576899
downvote count: 0
has comment: http://stackoverflow.com/comment/84147972
tagged with: python
has comment: http://stackoverflow.com/comment/84148037
has title: Incorrect file format to parse JSON in Python
has answer: http://stackoverflow.com/a/48575789
tagged with: format
has answer: http://stackoverflow.com/a/48576790
answer count: 3
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: file
favorite count: 0
type: Question
has body: My file contains number of JSON records as follows: Input file: {"timestamp":1487271527,"user":"Dave","action":"browse"} {"timestamp":1487271528,"user":"Dave","action":"navigate"} {"timestamp":1487271529,"user":"Dave","action":"browse"} {"timestamp":1487271530,"user":"Dave","action":"view"} {"timestamp":1487271531,"user":"Dave","action":"browse"} {"timestamp":1487271532,"user":"Dave","action":"browse"} {"timestamp":1487271533,"user":"Dave","action":"browse"} {"timestamp":1487271534,"user":"Dave","action":"navigate"} I want to load this data into dictionary similar to what json.load function does How can I do that ? with json.load I am getting following error: Traceback (most recent call last): File "C:/Users/lenovo/AppData/Local/Programs/Python/Python36-32/Granular.py", line 5, in &lt;module&gt; input_data = json.load(open(r"C:\Users\lenovo\Desktop\nlp\input.txt",'r')) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 299, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 342, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 57)
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84148050

http://stackoverflow.com/q/48514589
type: Question
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84023807
tagged with: python
tagged with: python-requests
tagged with: unit-testing
has answer: http://stackoverflow.com/a/48526716
tagged with: docker
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84048308
score: 1
has title: Connection aborted when unit test to request to docker container built in python
answer count: 1
has body: My goal is to write a unit test that builds a docker container and tries to execute a request to the newly built container. The test first builds an docker image, then runs the image and finally tries to execute a request to the newly created container. Currently running the test using py.test gives me requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) whereas running the same code in ipython works just fine. Expected behavior: py.test gives a successful result. Test import pytest import docker import requests @pytest.fixture(scope='module') def docker_env(): return docker.from_env() @pytest.fixture(scope='module') def docker_image(docker_env): client = docker_env image = client.images.build(path = ".", tag = "python-test:latest") yield image, client client.images.remove("python-test:latest") def test_port(docker_image): image, client = docker_image client.containers.run("python-test:latest", entrypoint="/opt/conda/envs/python-docker-test/bin/gunicorn --config /usr/src/app/gunicorn.conf.py app:api", detach=True, ports={'8000/tcp': ('127.0.0.1', 8000)}) resp = requests.get("http://127.0.0.1:8000/hello") assert resp.status == 200 # Expect success, currently getting an error Dockerfile My docker file looks as follows, FROM phusion/baseimage:0.9.22 ENV LANG=C.UTF-8 LC_ALL=C.UTF-8 RUN apt-get update --fix-missing &amp;&amp; apt-get install -y wget bzip2 ca-certificates \ libglib2.0-0 libxext6 libsm6 libxrender1 \ git mercurial subversion RUN echo 'export PATH=/opt/conda/bin:$PATH' &gt; /etc/profile.d/conda.sh &amp;&amp; \ wget --quiet https://repo.continuum.io/miniconda/Miniconda3-4.3.30-Linux-x86_64.sh -O ~/miniconda.sh &amp;&amp; \ /bin/bash ~/miniconda.sh -b -p /opt/conda &amp;&amp; \ rm ~/miniconda.sh ENV PATH /opt/conda/bin:$PATH WORKDIR /usr/src/app COPY . . RUN conda env create -f environment.yml EXPOSE 8000 SHELL ["/bin/bash", "-c"] ENTRYPOINT source activate python-docker-test &amp;&…
tagged with: dockerpy
accepted answer: http://stackoverflow.com/a/48526716
favorite count: 0

http://stackoverflow.com/comment/84222218
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48612766
has text: While suggesting a better way to extract that text is perfectly fine, this actually does not answer the question: *“Why is only the last occurrence being matched?”*

http://stackoverflow.com/q/48513900
has comment: http://stackoverflow.com/comment/84024342
favorite count: 0
type: Question
tagged with: hadoop
has body: I am creating a project to analyze stock data using Hadoop for my college project. I have created the cluster on Google cloud using Cloudera manager. I am a complete beginner. From what I have researched, I need to obtain an API to get the data and process it using MAPR code or any other method. However, I don't know how to integrate that API to import that data into the hadoop cluster. Link to the API I'm trying to use: https://www.alphavantage.co/ A python wrapper class: https://github.com/RomelTorres/alpha_vantage (I dont know the use) Someone please help me and explain to me the basic processes involved to obtain the data. I am open to suggestions as to another API or other suggestions. Any kind of help is highly appreciated.
type: UnansweredQuestion
tagged with: stockquotes
tagged with: python
tagged with: stock
score: -2
has comment: http://stackoverflow.com/comment/84024223
has title: Stock Market Data Analysis using Hadoop
has answer: http://stackoverflow.com/a/48513966
upvote count: 0
downvote count: 2
answer count: 1

http://stackoverflow.com/a/61858103
upvote count: 1
answers question: http://stackoverflow.com/q/48518300
score: 1
type: Answer
has body: If you want to code it with @bot.event you have to do it like so: @bot.event async def on_message(message): if message.content.startswith('!dm') await message.author.send('Hi. This message is send in DM!')
downvote count: 0

http://stackoverflow.com/comment/84204462
type: QuestionComment
type: Comment
has text: What unit test framework are you using? Because the standard `unittest` I don't believe makes use of threading by default. Did you look at the unittest code itself to see if it in fact explicitly using multithreading?
comment on: http://stackoverflow.com/q/48603741
score: 0

http://stackoverflow.com/a/48588807
downvote count: 1
score: 0
has body: You can use itertools.combinations: l= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] s = [('l'+str(b), list(i)) for b, i in enumerate(itertools.combinations(l, 3), start=1)] Output: [('l1', [1, 2, 3]), ('l2', [1, 2, 4]), ('l3', [1, 2, 5]), ('l4', [1, 2, 6]), ('l5', [1, 2, 7]), ('l6', [1, 2, 8]), ('l7', [1, 2, 9]), ('l8', [1, 2, 10]), ('l9', [1, 3, 4]), ('l10', [1, 3, 5]), ('l11', [1, 3, 6]), ('l12', [1, 3, 7]), ('l13', [1, 3, 8]), ('l14', [1, 3, 9]), ('l15', [1, 3, 10]), ('l16', [1, 4, 5]), ('l17', [1, 4, 6]), ('l18', [1, 4, 7]), ('l19', [1, 4, 8]), ('l20', [1, 4, 9]), ('l21', [1, 4, 10]), ('l22', [1, 5, 6]), ('l23', [1, 5, 7]), ('l24', [1, 5, 8]), ('l25', [1, 5, 9]), ('l26', [1, 5, 10]), ('l27', [1, 6, 7]), ('l28', [1, 6, 8]), ('l29', [1, 6, 9]), ('l30', [1, 6, 10]), ('l31', [1, 7, 8]), ('l32', [1, 7, 9]), ('l33', [1, 7, 10]), ('l34', [1, 8, 9]), ('l35', [1, 8, 10]), ('l36', [1, 9, 10]), ('l37', [2, 3, 4]), ('l38', [2, 3, 5]), ('l39', [2, 3, 6]), ('l40', [2, 3, 7]), ('l41', [2, 3, 8]), ('l42', [2, 3, 9]), ('l43', [2, 3, 10]), ('l44', [2, 4, 5]), ('l45', [2, 4, 6]), ('l46', [2, 4, 7]), ('l47', [2, 4, 8]), ('l48', [2, 4, 9]), ('l49', [2, 4, 10]), ('l50', [2, 5, 6]), ('l51', [2, 5, 7]), ('l52', [2, 5, 8]), ('l53', [2, 5, 9]), ('l54', [2, 5, 10]), ('l55', [2, 6, 7]), ('l56', [2, 6, 8]), ('l57', [2, 6, 9]), ('l58', [2, 6, 10]), ('l59', [2, 7, 8]), ('l60', [2, 7, 9]), ('l61', [2, 7, 10]), ('l62', [2, 8, 9]), ('l63', [2, 8, 10]), ('l64', [2, 9, 10]), ('l65', [3, 4, 5]), ('l66', [3, 4, 6]), ('l67', [3, 4, 7]), ('l68', [3, 4, 8]), ('l69', [3, 4, 9]), ('l70', [3, 4, 10]), ('l71', [3, 5, 6]), ('l72', [3, 5, 7]), ('l73', [3, 5, 8]), ('l74', [3, 5, 9]), ('l75', [3, 5, 10]), ('l76', [3, 6, 7]), ('l77', [3, 6, 8]), ('l78', [3, 6, 9]), ('l79', [3, 6, 10]), ('l80', [3, 7, 8]), ('l81', [3, 7, 9]), ('l82', [3, 7, 10]), ('l83', [3, 8, 9]), ('l84', [3, 8, 10]), ('l85', [3, 9, 10]), ('l86', [4, 5, 6]), ('l87', [4, 5, 7]), ('l88', [4, 5, 8]), ('l89', [4, 5, 9]), ('l90', [4, 5, 10]), ('l91', [4, 6, 7])…
answers question: http://stackoverflow.com/q/48588717
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84163039
comment on: http://stackoverflow.com/q/48582925
has text: This seems a bit broad. It is basically impossible to tell if a 2x speedup is possible because it requires the original implementation, benchmarking setup and hardware description. Since we have no information on any of those the chances of you getting a useful answer are very slim. Have you even checked if that algorithm is the bottleneck of your application?
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/48573424
downvote count: 0
has title: python regular expression handling bracket
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48573571
has body: string = '1f23wsedrfth 567tgyh112' expectedChecksum = re.search( "[0-9a-f]{5}",string ).group(0) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'NoneType' object has no attribute 'group' Why is it caused an error? I thought the expectedChecksum should be '1f23w' I tried the following code with {4}, then it is fine. expectedChecksum = re.search( "[0-9a-f]{4}",string ).group(0) expectedChecksum '1f23'
tagged with: regex
has answer: http://stackoverflow.com/a/48573466
has comment: http://stackoverflow.com/comment/84144165
answer count: 2
score: 1

http://stackoverflow.com/q/48625790
has answer: http://stackoverflow.com/a/48635425
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84278722
answer count: 3
has answer: http://stackoverflow.com/a/48644693
has answer: http://stackoverflow.com/a/48658849
downvote count: 0
tagged with: qml
upvote count: 1
score: 1
tagged with: python
has title: QML Image not displaying in Application
favorite count: 0
type: Question
tagged with: qqmlapplicationengine
has comment: http://stackoverflow.com/comment/84250950
has body: I am having trouble displaying a simple image into my application. Here's the main.py: import sys from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtGui import QGuiApplication from PyQt5.QtCore import QObject, QUrl if __name__ == '__main__': sys.argv += ['--style', 'material'] app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine('basic.qml') sys.exit(app.exec_()) And the basic.qml: import QtQuick 2.0 import QtQuick.Controls 2.1 import QtQuick.Controls.Material 2.1 ApplicationWindow { visible: true width: 200 height: 400 title: qsTr("Hello World") Material.theme: Material.Light Material.accent: Material.Orange Column { anchors.centerIn: parent Button { width: 200; height:50; font.capitalization: Font.MixedCase text: qsTr("Button Name") objectName: "button_obj_name" highlighted: true Material.background: Material.Orange } Image{ width: 100; height: 100 fillMode: Image.PreserveAspectFit source: "logo_name.jpg" } } } In the application window it seems that space is allocated but nothing is displaying. [logo_name.jpg is located in the same folder where basic.qml and main.py are in ]
accepted answer: http://stackoverflow.com/a/48644693
has comment: http://stackoverflow.com/comment/84278434
tagged with: pyqt5
possible better answer: http://stackoverflow.com/a/48635425
has comment: http://stackoverflow.com/comment/84260714
has comment: http://stackoverflow.com/comment/84251480

http://stackoverflow.com/q/48593268
tagged with: http://stackoverflow.com/tag/json
tagged with: python
accepted answer: http://stackoverflow.com/a/48593485
has answer: http://stackoverflow.com/a/48593485
has comment: http://stackoverflow.com/comment/84199154
possible better answer: http://stackoverflow.com/a/48593304
has title: Extract json objects from a list using python
tagged with: apache-spark-sql
linked to: http://stackoverflow.com/q/34069282
has answer: http://stackoverflow.com/a/48593304
has answer: http://stackoverflow.com/a/48593428
duplicate of: http://stackoverflow.com/q/34069282
has comment: http://stackoverflow.com/comment/84183856
has body: I have a string type column which contains a list of elements which are nested dictionary objects. E.g str = '[{"method": {"super":0.03,"normal":0.8,"par":0.15,"goal":0.01,"fact":0.04}, "city":["nyc","atlanta"], "description":"some description", "content_type":"media"}, {"method": {"super":0.03,"normal":0.8,"par":0.15,"goal":0.01,"fact":0.04}, "city":["chicago","dallas"], "description":"some description2", "content_type":"web"}, {"method": {"super":0.03,"normal":0.8,"par":0.15,"goal":0.01,"fact":0.04}, "city":["las vegas","buffalo"], "description":"some description3", "content_type":"media"}]' This is actually a column in a spark dataframe which is of a string type. So I want to know how to convert the contents of a string into a list such that I can convert each element in the list using json.loads. Any idea?
type: Question
has comment: http://stackoverflow.com/comment/84183785
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: apache-spark

http://stackoverflow.com/comment/84066145
comment on: http://stackoverflow.com/a/48500056
type: AnswerComment
has text: i'm unable to understand the code.
score: 0
type: Comment

http://stackoverflow.com/comment/84225847
type: AnswerComment
has text: Thank you it worked. All I have to do remove those sys args.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48614387

http://stackoverflow.com/comment/84220749
has text: @StefanPochmann, FYI, I opened a bug report for this: https://bugs.python.org/issue32767
comment on: http://stackoverflow.com/a/48604036
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48640056
linked to: http://stackoverflow.com/q/47155569
has title: How to change to interval of x ticks in matplotlib?
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84277421
answer count: 1
duplicate of: http://stackoverflow.com/q/12945971
duplicate of: http://stackoverflow.com/q/47155569
has body: How can I make xticks of a plot in specific frequency? Here is my code: # read data df = pd.read_csv("newData/000001.csv") df1 = df.loc[df['seqNo'] == 48] df1 = df1.sort_values(by = 'date') df1['date'] = df1['date'].astype(str) # show plot plt.plot(df1['date'], df1['close'], 'yellow', label = 'close') plt.legend() plt.xlabel("date") plt.ylabel("value") plt.title("000001") plt.show() and the plot, the x axis is too dense: and the part of the plot is : The datatype of xaxis is string.
downvote count: 1
favorite count: 0
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48640327
has comment: http://stackoverflow.com/comment/84276614
tagged with: python
score: -1

http://stackoverflow.com/q/48490137
type: Question
upvote count: 4
has title: Set attribute in __new__ subclass with dynamic base_class
has comment: http://stackoverflow.com/comment/83973809
tagged with: built-in
answer count: 2
type: UnansweredQuestion
has body: I have class A which subclasses str to add meta data via kwargs class A(str): def __new__(cls, value, **kwargs): obj = str.__new__(cls, value) obj.__dict__.update(kwargs) return obj Like using: x = A('test', meta=10) x.meta 10 Now, I want to handle the unicode type too, so I adopted the below approach. To dynamically check for the type and use it as base_class class B(object): def __new__(cls, value, **kwargs): base_class = str if isinstance(value, str) else unicode new_type = type(cls.__name__, (base_class,), dict(cls.__dict__)) obj = base_class.__new__(new_type, value) obj.__dict__.update(kwargs) return obj However, that seems to be incorrect way of do it. Gives me a TypeError: descriptor 'dict' for 'B' objects doesn't apply to 'B' object B('test', meta=10) ----------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-533-206366568616&gt; in &lt;module&gt;() ----&gt; 1 B('tes', a=10).a &lt;ipython-input-528-91dc8e50cb78&gt; in __new__(cls, value, **kw) 11 new_type = type(cls.__name__, (base_class,), dict(cls.__dict__)) 12 obj = base_class.__new__(new_type, value) ---&gt; 13 obj.__dict__.update(kw) 14 return obj 15 TypeError: descriptor '__dict__' for 'B' objects doesn't apply to 'B' object I could use class C using setattr instead, which works fine. class C(object): def __new__(cls, value, **kw): base_class = str if isinstance(value, str) else unicode new_type = type(cls.__name__, (base_class,), dict(cls.__dict__)) obj = base_class.__new__(new_type, value) for k, v in kw.items(): setattr(obj, k, v) return obj x = C('test', meta=10) x.meta 10 Could you help me understand what am I missing out on class B and how to use __dict__?
downvote count: 0
tagged with: unicode
favorite count: 0
tagged with: class
has comment: http://stackoverflow.com/comment/83973836
has comment: http://stackoverflow.com/comment/83973755
tagged with: subclass
linked to: http://stackoverflow.com/q/45481440
has answer: http://stackoverflow.com/a/48490537
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/83973889
has answer: http://stackoverflow.com/a/48490234

http://stackoverflow.com/comment/84207002
type: Comment
has text: Element could be in iframe...in that case you have to switch to that frame..or it could be down in page..so you need to scroll through page first.
comment on: http://stackoverflow.com/q/48604607
score: 0
type: QuestionComment

http://stackoverflow.com/q/48510399
tagged with: windows
has comment: http://stackoverflow.com/comment/84016022
has comment: http://stackoverflow.com/comment/84015949
type: Question
has comment: http://stackoverflow.com/comment/84015980
has body: How would I go about getting the list of files currently opened by a single application (.exe). For example, I've running the media player MPV and it's playing a video file, knowing its PID how can I get the files being held by the process? Running this code p = psutil.Process(15228) # manually set PID of MPV for testing pprint.pprint(p.open_files()) It returns the following array [popenfile(path='C:\\Windows\\System32\\pt-BR\\msvfw32.dll.mui', fd=-1), popenfile(path='C:\\Windows\\Fonts\\arial.ttf', fd=-1), popenfile(path='C:\\Windows\\System32\\pt-BR\\kernel32.dll.mui', fd=-1), popenfile(path='C:\\Windows\\System32\\pt-BR\\MMDevAPI.dll.mui', fd=-1), popenfile(path='C:\\Windows\\System32\\pt-BR\\avicap32.dll.mui', fd=-1)] I can successfully obtain the current playing file if I get the cmdline by using p.cmdline() and removing the folders leading up to the file, but that can only be used if the video file was opened directly, if the player has been opened first then the file dragged to it, there's no cmdline to be parsed. For the time being it can be platform dependent solution for Windows.
has comment: http://stackoverflow.com/comment/84015784
tagged with: filesystems
answer count: 0
has comment: http://stackoverflow.com/comment/84015858
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84015847
has comment: http://stackoverflow.com/comment/84015874
has title: List of files opened by process
score: 0

http://stackoverflow.com/a/48605357
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48603827
has body: There are different ways to get rid of the issue. The issue is because you are touching a enumeration while enumerating it. That should always be avoided. You can do that by rewriting your code Using sets instead of array from selenium import webdriver from selenium.common.exceptions import TimeoutException def get_alexa_top_pages(): sites = [] with open('topsites_1000.txt', 'r') as f: for line in f: line = line.strip('\n') sites.append(line) sites = filter(None, sites) sites = ['http://www.' + site for site in sites] return sites def main(): alexa_1000 = set(get_alexa_top_pages()) alexa_invalid = set() out = open('sites_with_login.txt', 'w') sign_in_strings = ['sign in', 'signin', 'login', 'log in', 'sign up', 'signup'] driver = webdriver.Firefox() driver.set_page_load_timeout(30) for index, page in enumerate(alexa_1000): try: print "Loading page %s (num %d)" %(page, index + 1) driver.get(page) html_source = driver.page_source html_source = html_source.lower() present = any([i in html_source for i in sign_in_strings]) if present: out.write(page + '\n') except TimeoutException as ex: alexa_invalid.add(page) continue except Exception as ex: alexa_invalid.add(page) continue alexa_valid = alexa_1000 - alexa_invalid out.close() if __name__ == "__main__": main() In this you use set, one for looping and one for maintaining the list of invalid ones. If exception occurs you update the invalid one. At the end you can subtract the two to find valid sites as well Use reverse array and pop from selenium import webdriver from selenium.common.exceptions import TimeoutException def get_alexa_top_pages(): sites = [] with open('topsites_1000.txt', 'r') as f: for line in f: line = line.strip('\n') sites.append(line) sites = filter(None, sites) sites = ['http://www.' + site for site in sites] return sites def main(): alexa_1000 = get_alexa_top_pages() out = open('sites_with_login.txt', 'w') sign_in_strings = ['sign in', 'signin', 'login', 'log in', 'sign up', 'signup'] driver = webdri…
type: Answer
accepted answer of: http://stackoverflow.com/q/48603827
score: 2
has comment: http://stackoverflow.com/comment/84218920
upvote count: 2

http://stackoverflow.com/q/48509586
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84014234
tagged with: django
tagged with: python
has title: Inputs are not showing in django form
has answer: http://stackoverflow.com/a/48510944
has comment: http://stackoverflow.com/comment/84014261
has comment: http://stackoverflow.com/comment/84015578
score: 0
has comment: http://stackoverflow.com/comment/84014186
has comment: http://stackoverflow.com/comment/84015461
has body: My form inputs are not showing. It's just a button. i think homepage.html doesn't getting this form Forms.py class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) Views.py def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'mainApp/homepage.html', {'form': form}) homepage.html {% extends "mainApp/wrapper.html" %} {% block title %}Главная{% endblock %} {% block content %} Main page {% include "mainApp/includes/somehtml.html" %} {% csrf_token %} {{ form }} {% endblock %} It shoes only "Submit" button. How can I fix it?
type: Question
has answer: http://stackoverflow.com/a/48510585
answer count: 2
has comment: http://stackoverflow.com/comment/84014241

http://stackoverflow.com/a/68656159
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/48617861
has comment: http://stackoverflow.com/comment/130164284
has body: The simplest way that I could work around this issue is by adding a input at the end of the code before the code execution completes. input("Press enter to proceed...") None of the answers I found could provide a similar functionality Additionally how this helped me is, if the user hits enter directly, I made it so that the current instance is closed and a new instance of the app pops up right away. This is helpful if the user had accidentally input a wrong value for a previous input. And if the user enters any other value, the process stops without creating a new instance.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84144274
type: Comment
comment on: http://stackoverflow.com/a/48512467
has text: It's starting to make sense. On "b)" you say it's reading twice. I don't have enough knowledge/experience to understand why, but is there a way to resolve? I only need to read once - maybe I don't need a queue, because once this external signal goes low I will terminate the ExecuteSession thread.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84260628
comment on: http://stackoverflow.com/q/48631672
type: Comment
type: QuestionComment
has text: yuvi that is exactly what I want. THANKS :)
score: 0

http://stackoverflow.com/comment/84046920
has text: @Buaban i cant share the endpoint as its an intranet site
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48490994
type: QuestionComment

http://stackoverflow.com/comment/84023692
type: AnswerComment
comment on: http://stackoverflow.com/a/48514611
type: Comment
has text: Hmm... calling `value_counts` twice seems wasteful. Maybe cache the intermediate result??
score: 0

http://stackoverflow.com/comment/84060172
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48531839
has text: Yes! That's what I meant, my mind was on the comment about normalization with percentages. Thank you.
type: AnswerComment

http://stackoverflow.com/a/48507121
type: Answer
has comment: http://stackoverflow.com/comment/84012270
has comment: http://stackoverflow.com/comment/102649327
accepted answer of: http://stackoverflow.com/q/48506460
has comment: http://stackoverflow.com/comment/131994762
has comment: http://stackoverflow.com/comment/106575497
has comment: http://stackoverflow.com/comment/91445285
has comment: http://stackoverflow.com/comment/131990394
has comment: http://stackoverflow.com/comment/106575669
has comment: http://stackoverflow.com/comment/102648673
has comment: http://stackoverflow.com/comment/102645650
has comment: http://stackoverflow.com/comment/84012756
type: AcceptedAnswer
downvote count: 0
score: 89
upvote count: 89
has body: The closest literal translation of the threading code would create the socket as before, make it non-blocking, and use asyncio low-level socket operations to implement the server. Here is an example, sticking to the more relevant server part (the client is single-threaded and likely fine as-is): import asyncio, socket async def handle_client(client): loop = asyncio.get_event_loop() request = None while request != 'quit': request = (await loop.sock_recv(client, 255)).decode('utf8') response = str(eval(request)) + '\n' await loop.sock_sendall(client, response.encode('utf8')) client.close() async def run_server(): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('localhost', 15555)) server.listen(8) server.setblocking(False) loop = asyncio.get_event_loop() while True: client, _ = await loop.sock_accept(server) loop.create_task(handle_client(client)) asyncio.run(run_server()) The above works, but is not the intended way to use asyncio. It requires precisely matching the use of the socket API to the expectations of asyncio, such as the setblocking() call. There is no buffering out-of-the-box, so something as simple as reading a line from the client becomes a tiresome chore. This API level is really only intended for implementers of alternative event loops, which would provide their implementation of sock_recv, sock_sendall, etc. Asyncio's public API provides two abstraction layers intended for consumption: the lower-level transport/protocol layer modeled after Twisted, and the higher-level streams layer. In new code, you almost certainly want to use the streams API, i.e. call asyncio.start_server and avoid raw sockets. That significantly reduces the line count: import asyncio async def handle_client(reader, writer): request = None while request != 'quit': request = (await reader.read(255)).decode('utf8') response = str(eval(request)) + '\n' writer.write(response.encode('utf8')) await writer.drain() writer.close() async def run_server(): server = aw…
has comment: http://stackoverflow.com/comment/84013043
answers question: http://stackoverflow.com/q/48506460
has comment: http://stackoverflow.com/comment/102648029

http://stackoverflow.com/comment/84041695
type: QuestionComment
has text: @mrCarnivore much appreciate your help. I think you are right and it is only polish notation *inspired* syntax or something like that.
comment on: http://stackoverflow.com/q/48523138
score: 1
type: Comment

http://stackoverflow.com/comment/84106241
comment on: http://stackoverflow.com/q/48555010
score: 0
type: Comment
type: QuestionComment
has text: how do I know what's the exact error causing this ?

http://stackoverflow.com/a/48645932
type: Answer
downvote count: 0
has body: already added confirmation=no to ~/.taskrc a possible answer to the question could be echo 'all' | task del 1,2,3 but there could be a better one
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84575179
answers question: http://stackoverflow.com/q/48606717

http://stackoverflow.com/q/48629555
possible better answer: http://stackoverflow.com/a/48629619
accepted answer: http://stackoverflow.com/a/48629613
tagged with: python
has title: Unbound variable error with if statements
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/84256048
score: 1
has body: I am getting 'UnboundLocalError: local variable 'fileName' referenced before assignment' when using variables underneath if/elif statements. The code takes a file name and uses a regex to split the junk off the start and end. It then returns the new filename and foldername.: input: '[subcompany] series title - 01 [more junk].mkv' desired output: ('series title - 01.mkv', 'series title') troublesome code: def nameFix(f): start, end = os.path.splitext(f) if f.endswith('mkv') and f.startswith('[H'): fileName = fileReg.findall(f) elif f.endswith('mkv') and f.startswith('['): fileName=altReg.findall(f) folder = folderReg.findall(fileName[0][1]) fileFix = fileName[0][1] + end fixFolderName = folder[0] return (fileFix, fixFolderName)
has answer: http://stackoverflow.com/a/48629613
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48629619

http://stackoverflow.com/q/48521360
favorite count: 0
has answer: http://stackoverflow.com/a/48521583
type: Question
has comment: http://stackoverflow.com/comment/84037412
has title: Pandas - fill NaN based on the previous value of another cell
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/84037389
has comment: http://stackoverflow.com/comment/84037321
type: AnsweredQuestion
upvote count: 4
has comment: http://stackoverflow.com/comment/84037473
tagged with: pandas
has comment: http://stackoverflow.com/comment/84037594
has comment: http://stackoverflow.com/comment/84037231
has body: I have some stocks data in a dataframe that I'm resampling, which results in some NaN values. Here's a section of the raw feed: In [34]: feeddf Out[34]: open high low close volume date 2017-12-03 07:00:00 14.46 14.46 14.46 14.46 25000 2017-12-03 07:01:00 14.46 14.46 14.46 14.46 20917 2017-12-03 07:06:00 14.50 14.50 14.50 14.50 2000 2017-12-03 07:12:00 14.50 14.56 14.50 14.56 17000 The feed is supposed to be minute-by-minute, but when there's not data available, the row is skipped. When resampling the dataframe and aggregating for the opens, highs, lows, and closes, it looks like this: In [35]: feeddf.resample('3Min').agg({'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last'}) Out[35]: open high low close date 2017-12-03 07:00:00 14.46 14.46 14.46 14.46 2017-12-03 07:03:00 NaN NaN NaN NaN 2017-12-03 07:06:00 14.50 14.50 14.50 14.50 2017-12-03 07:09:00 NaN NaN NaN NaN 2017-12-03 07:12:00 14.50 14.56 14.50 14.56 My question: I want to forward-fill the missing data based on the last row's close value. df.fillna(method='ffill') is not helping because it fills it based on the last value on the same column. Any idea?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84037558
accepted answer: http://stackoverflow.com/a/48521583
has comment: http://stackoverflow.com/comment/84037357

http://stackoverflow.com/comment/84189593
type: QuestionComment
comment on: http://stackoverflow.com/q/48585988
type: Comment
has text: I tried changing the file encoding. Still get the same error.
score: 0

http://stackoverflow.com/comment/84220441
type: QuestionComment
comment on: http://stackoverflow.com/q/48611946
has text: Besides being a duplicate, this is a very good question. It includes a good statement of the problem, the actual code used, the actual **and** expected outputs, and even an attempt at fixing the problem!
score: 0
type: Comment

http://stackoverflow.com/comment/84092688
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48547160
has text: Look at `x.dtypes`. That column probably is `object`. So the column cells contain pointers to arrays elsewhere in memory. `asmatrix` is creating the same thing with `numpy` - an array of pointers to arrays. Try `np.stack(x)`. Assuming all those arrays are the same size, that should concatenate them as rows of a new array.

http://stackoverflow.com/comment/84043543
type: QuestionComment
comment on: http://stackoverflow.com/q/48524397
has text: try `np.argmax()` or `pixel_histogram.index(max(pixel_histogram))`
score: 0
type: Comment

http://stackoverflow.com/a/48531442
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84058694
answers question: http://stackoverflow.com/q/48531008
has body: i figured out the answer thanks to all the help in the comments: credits: @SIM, @match, @t.m.adam and @dax here goes. text.encode('utf-8').strip() thanks to all. code as is: ... for cell2n3 in row.findAll('div', attrs={'class': 'KambiBC-event-participants__name'}): cell2n3append.append(cell2n3.text.encode('utf-8').strip()) ... ps in terminal the output is as before...eg. before('Cear\xe1-CE') -->now('Cear\xc3\xa1-CE') but in csv it is Ceará-CE
accepted answer of: http://stackoverflow.com/q/48531008

http://stackoverflow.com/comment/84028725
has text: Sorry. I've adjusted the code and have the same issue. When I perform a `print` function on `visuals[0]` or `visuals[1]`, it returns `[]`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48516068
type: AnswerComment

http://stackoverflow.com/q/48550224
tagged with: qlistview
upvote count: 1
has title: One Model, two different views - PySide
has answer: http://stackoverflow.com/a/48552714
has body: I have QAbstractTableModel with 4 columns. I'm trying to display the first 3 columns on a view (QTableView), and when a row is selected on such view a second view (a QListView) should display the 4th column of the model. I found something about a QProxyModel, but I'm having a hard time wrapping my mind on it. Also there are a 'solutions' I found something similar HERE but somehow I want the inverse result. The data I'm trying to dispaly is something like this: [['green', 'car', 'available',['a','b','c','d']]] So, on the Table View it would show: green - car - available. And when clicking on such row, the List view would display the array on the last position: a - b - c - d. I hope it makes sense. Tips on directions, documentations, examples? Thank you for your time.
tagged with: qabstracttablemodel
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/25901069
tagged with: python
tagged with: qtableview
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48552714
score: 1
tagged with: pyside2
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48626405
has comment: http://stackoverflow.com/comment/84427501
type: Question
has answer: http://stackoverflow.com/a/48756324
downvote count: 0
possible better answer: http://stackoverflow.com/a/50177554
upvote count: 1
tagged with: python
tagged with: swashbuckle
has answer: http://stackoverflow.com/a/50177554
accepted answer: http://stackoverflow.com/a/48756324
favorite count: 0
type: AnsweredQuestion
tagged with: flask-restplus
answer count: 3
score: 1
tagged with: swagger
tagged with: http://stackoverflow.com/tag/json
has title: is it possible to generate swagger metadata json automatically with flask-RESTplus?
has comment: http://stackoverflow.com/comment/84291326
has answer: http://stackoverflow.com/a/51811447
has body: I have created an api using the python library flask-Restplus and have it's associated swagger ui being exposed to e.g http://serverURL:80/api/v1/documentation. Is it possible to expose this documentation page as a json somehow? I know this is possible using the .Net library "Swashbuckle" (for e.g http://serverURL:80/api/v1/documentation.json would return the documentation in json format). I am looking for a way for this same type of functionality in python.

http://stackoverflow.com/q/48631472
has comment: http://stackoverflow.com/comment/84273693
favorite count: 0
tagged with: security
score: 3
has title: Key Kollision in DES3 Implementation of PyCrypto
has body: I'm pretty new to cryptography and only a user really. I stumbled however over a very interesting "vulnerability" of the DES3 Cipher of the PyCrypto library. I experimented with generating Private Keys and encrypting them with DES3. Everything is fine with the following code: from Crypto.PublicKey import RSA from Crypto.Cipher import DES3 from Crypto import Random random_generator = Random.new().read key = RSA.generate(1024,random_generator) public_key = key.publickey() enc_data = public_key.encrypt('abcdefgh', 32) exported_key = key.exportKey('PEM', '12345678abcdefgh', pkcs=1) print(exported_key) imported_key = RSA.importKey(exported_key,'12345678abcdefgi') print(imported_key.exportKey('PEM')) Note the minor change in the passphrase when importing the key. As expected, the result of the import is a fail, as the Private Key can not be decrypted correctly with the 16 byte passphrase provided. When I change the passphrase to the correct one, everything is fine. However, when I experimented with encrypting something with DES3 (the standard encryption used in passphrase encrypting in this code), I stumbled accross something. Regard the code: from Crypto.Cipher import DES3 des = DES3.new("12345678abcdefgh") secret = des.encrypt("1234abcd") print(secret) des2 = DES3.new("12345678abcdefgi") result = des2.decrypt(secret) print(result) Which produces the following result: ��@e��� 1234abcd I can decode the message despite having an unauthorized key. For every other change I have tried so far ("12345678absdefgj" e.g.), encryption works as expected. Is this a vulnerability in the DES3 cipher, an incorrect implementation or a fault in my "experiment"? Thanks for your help!
tagged with: encryption
tagged with: pycrypto
type: Question
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/84271498
type: UnansweredQuestion
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/84309214
has text: The code below gave me the results I need, however I'm curious about your proposal as well. I tried to apply it to my data frame in the code above --> dfB[series.str.contains(pattern)] but received an error "NameError: name 'series' is not defined". What goes in the "series"?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48616470
score: 0

http://stackoverflow.com/q/48585899
has comment: http://stackoverflow.com/comment/84168667
has answer: http://stackoverflow.com/a/48586120
tagged with: importerror
tagged with: python
score: -1
tagged with: module
has body: I keep getting this same error and I have tried everything I know how to fix it. The error I am getting is this: ImportError: No module name parse Does anyone know how to fix this? I am currently running python 2.7.12. Also here is my code: # -*- coding: utf-8 -*- import http.client, urllib.parse, json # ********************************************** # *** Update or verify the following values. *** # ********************************************** # Replace the subscriptionKey string value with your valid subscription key. subscriptionKey = "My_Access_Key" # Verify the endpoint URI. At this writing, only one endpoint is used for Bing # search APIs. In the future, regional endpoints may be available. If you # encounter unexpected authorization errors, double-check this value against # the endpoint for your Bing Web search instance in your Azure dashboard. host = "api.cognitive.microsoft.com" path = "/bing/v7.0/search" term = "Microsoft Cognitive Services" def BingWebSearch(search): "Performs a Bing Web search and returns the results." headers = {'Ocp-Apim-Subscription-Key': subscriptionKey} conn = http.client.HTTPSConnection(host) query = urllib.parse.quote(search) conn.request("GET", path + "?q=" + query, headers=headers) response = conn.getresponse() headers = [k + ": " + v for (k, v) in response.getheaders() if k.startswith("BingAPIs-") or k.startswith("X-MSEdge-")] return headers, response.read().decode("utf8") if len(subscriptionKey) == 32: print('Searching the Web for: ', term) headers, result = BingWebSearch(term) print("\nRelevant HTTP Headers:\n") print("\n".join(headers)) print("\nJSON Response:\n") print(json.dumps(json.loads(result), indent=4)) else: print("Invalid Bing Search API subscription key!") print("Please paste yours into the source code.")
type: Question
upvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84169145
has title: Python ImportError: No module name parse
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84169209
answer count: 1
downvote count: 1
tagged with: error-handling
has comment: http://stackoverflow.com/comment/84168701
has comment: http://stackoverflow.com/comment/84169051
favorite count: 0

http://stackoverflow.com/q/48511764
downvote count: 1
favorite count: 0
type: Question
has title: Selecting the required fields from JSON in python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48511842
type: UnansweredQuestion
tagged with: python
score: -1
has body: Below is the JSON data that i have and i am trying to get only name , after_count . { "total_count": 125, "limit": 100, "operatingsystems": [ { "category": null, "name": "abc", "total_count": 1, "notes": "", "after_count": 11, "id": 1, "aliases": [] }, { "category": null, "name": "cdef", "total_count": 2, "notes": "", "after_count": 62, "id": 2, "aliases": [] }, My code: data = [item for item in objects if item["after_count"] &gt;= 0] Output i am getting: " a l i a s e s " : [ ] Can someone please guide me in right direction.
tagged with: python-2.7
upvote count: 0
answer count: 1
tagged with: python-requests

django-testing
tags question: http://stackoverflow.com/q/48582148
tags question: http://stackoverflow.com/q/48518170
tag name: django-testing
type: Tag

http://stackoverflow.com/a/48500313
downvote count: 0
has comment: http://stackoverflow.com/comment/83993930
type: Answer
has body: Here's an alternative, which removes split requirement. from os.path import splitext, basename splitext(basename('http://example.com/comp/project.sec'))[0]
upvote count: 2
answers question: http://stackoverflow.com/q/48500140
has comment: http://stackoverflow.com/comment/83993931
score: 2

http://stackoverflow.com/q/48616625
has title: MongoDB doesn't handle aggregation with allowDiskUsage:True
tagged with: mongodb
has answer: http://stackoverflow.com/a/48787253
score: 3
has comment: http://stackoverflow.com/comment/84264995
tagged with: database
has comment: http://stackoverflow.com/comment/84478633
tagged with: python
tagged with: nosql
answer count: 2
upvote count: 3
type: UnansweredQuestion
has body: the data structure is like: way: { _id:'9762264' node: ['253333910', '3304026514'] } and I'm trying to count the frequency of nodes' appearance in ways. Here is my code using pymongo: node = db.way.aggregate([ {'$unwind': '$node'}, { '$group': { '_id': '$node', 'appear_count': {'$sum': 1} } }, {'$sort': {'appear_count': -1}}, {'$limit': 10} ], {'allowDiskUse': True} ) it will report an error: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File ".../OSM Wrangling/explore.py", line 78, in most_passed_node {'allowDiskUse': True} File ".../pymongo/collection.py", line 2181, in aggregate **kwargs) File ".../pymongo/collection.py", line 2088, in _aggregate client=self.__database.client) File ".../pymongo/pool.py", line 464, in command self.validate_session(client, session) File ".../pymongo/pool.py", line 609, in validate_session if session._client is not client: AttributeError: 'dict' object has no attribute '_client' However, if I removed the {'allowDiskUse': True} and test it on a smaller set of data, it works well. It seems that the allowDiskUse statement brings something wrong? And there is no information about this mistake in the docs of MongoDB How should I solve this problem and get the answer I want?
downvote count: 0
has answer: http://stackoverflow.com/a/48616905
favorite count: 0
type: Question

http://stackoverflow.com/a/48639257
answers question: http://stackoverflow.com/q/48636128
score: 0
has body: You can do this: import pandas as pd data = [{'column1': 1, 'column2': 12,'column3': 15, 'column4': 6}] df = pd.DataFrame(data) #dict of columns {'column1': 1, 'column2': 2, ...} column_dict = dict(zip(df.columns, list(range(len(df.columns))+1))) # rename dataframe columns using rename method new_df = df.rename(columns=column_dict) Or this: # create a df without specify columns names # will generate columns as numbers from 0 to len(df.columns) - 1 new_df = pd.DataFrame(df.values) # add 1 to starts by 1 new_df.columns = new_df.columns + 1
type: Answer